Skip to content

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

feat(mcp): search, read and update documentation from MCP

Pouzor4a7708988416
diff --git a/README.md b/README.md
index f8b739e..ad1e671 100644
--- a/README.md
+++ b/README.md
@@ -440,6 +440,9 @@ Or add it manually to `~/.claude.json`:
- *"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."*
+- *"Search the documentation for what we wrote about the backup schedule."*
+- *"Write a runbook page for restoring a Proxmox backup, then link it from the NAS document."*
+- *"Show me what changed in the firewall document, and restore the version before the last edit."*
### Security
diff --git a/backend/app/api/routes/documents.py b/backend/app/api/routes/documents.py
index 9d8b96b..8d9b4fa 100644
--- a/backend/app/api/routes/documents.py
+++ b/backend/app/api/routes/documents.py
@@ -587,7 +587,7 @@ async def update_document(
doc.slug = await unique_slug(db, doc.title, parent_id=parent_id, exclude_id=doc.id)
if "body" in sent and sent["body"] is not None and sent["body"] != doc.body:
- await _record_revision(db, doc, "edit")
+ await _record_revision(db, doc, sent.get("revision_reason") or "edit")
_apply_body(doc, sent["body"])
doc.edited_at = _now()
# An explicit title in the same request still wins: it is applied below.
diff --git a/backend/app/schemas/documents.py b/backend/app/schemas/documents.py
index da5a682..e298fd8 100644
--- a/backend/app/schemas/documents.py
+++ b/backend/app/schemas/documents.py
@@ -13,6 +13,11 @@ from app.services.doc_tree import DOCUMENT_KINDS
# user asks (by zone, subnet, type…) without the server storing a tree.
DOC_KINDS = set(DOCUMENT_KINDS)
+# The reasons a caller may put its own name to. Everything else a revision can
+# say — "restore", "regenerate", "scaffold", "migrate" — belongs to the action
+# that takes it, so no client can dress a plain edit up as one of those.
+CLIENT_REVISION_REASONS = frozenset({"edit", "mcp", "import"})
+
class DocumentCreate(BaseModel):
kind: str = "page"
@@ -55,6 +60,17 @@ class DocumentUpdate(BaseModel):
# Accept the device's current facts as documented, clearing the drift
# banner without touching the body.
resync_facts: bool | None = None
+ # What the history should say caused this edit. Only read when the body
+ # actually changes — a starred flag or a rename snapshots nothing, so there
+ # is no revision to attribute. Defaults to "edit", the human in the editor.
+ revision_reason: str | None = None
+
+ @field_validator("revision_reason")
+ @classmethod
+ def _known_reason(cls, v: str | None) -> str | None:
+ if v is not None and v not in CLIENT_REVISION_REASONS:
+ raise ValueError(f"revision_reason must be one of {sorted(CLIENT_REVISION_REASONS)}")
+ return v
class DocumentSummary(BaseModel):
diff --git a/backend/tests/test_documents.py b/backend/tests/test_documents.py
index 7d228da..89e8631 100644
--- a/backend/tests/test_documents.py
+++ b/backend/tests/test_documents.py
@@ -573,6 +573,38 @@ async def test_saving_an_unchanged_body_records_nothing(client: AsyncClient, hea
assert (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json() == []
+async def test_an_edit_can_say_it_came_from_an_ai_client(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="first")
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}",
+ json={"body": "second", "revision_reason": "mcp"},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ revisions = (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json()
+ assert [r["reason"] for r in revisions] == ["mcp"]
+
+
+async def test_an_unknown_revision_reason_is_rejected(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="first")
+ res = await client.patch(
+ f"/api/v1/documents/{doc['id']}",
+ json={"body": "second", "revision_reason": "restore"},
+ headers=headers,
+ )
+ assert res.status_code == 422
+
+
+async def test_a_revision_reason_without_a_body_change_records_nothing(client: AsyncClient, headers: dict):
+ doc = await _create(client, headers, title="Page", body="same")
+ await client.patch(
+ f"/api/v1/documents/{doc['id']}",
+ json={"starred": True, "revision_reason": "mcp"},
+ headers=headers,
+ )
+ assert (await client.get(f"/api/v1/documents/{doc['id']}/revisions", headers=headers)).json() == []
+
+
async def test_restoring_brings_back_an_old_body_and_is_itself_undoable(client: AsyncClient, headers: dict):
doc = await _create(client, headers, title="Page", body="first")
await client.patch(f"/api/v1/documents/{doc['id']}", json={"body": "second"}, headers=headers)
diff --git a/docs/documentation.md b/docs/documentation.md
index efe3663..fbc2f46 100644
--- a/docs/documentation.md
+++ b/docs/documentation.md
@@ -232,6 +232,36 @@ Non-destructive and repeatable.
---
+## MCP tools
+
+An AI client reads and writes documents through the MCP server
+(`mcp/app/documents.py`). Every tool is a call to the API above — the server
+never touches the database itself.
+
+| Tool | What |
+|---|---|
+| `search_documentation` | Full-text search, one snippet per hit. The entry point. |
+| `list_documentation` | Summaries, filterable by `kind` / `parent_id` / `device_id` / `tag`. Never a body. |
+| `read_document` | One document in full. |
+| `list_document_revisions`, `read_document_revision` | The history, and the body one revision holds. |
+| `document_backlinks` | What links here. |
+| `create_document` | A new document, from a body or a template. |
+| `update_document` | An edit. The full replacement body, not a patch. |
+| `restore_document_revision` | Put an earlier body back. |
+
+Resources: `homelable://documents` (summaries) and
+`homelable://documents/<id>` (one document, body included).
+
+**Every AI edit is historized.** `update_document` sends
+`revision_reason: "mcp"` whatever the client asks for — `DocumentUpdate` only
+accepts `edit`, `mcp` or `import`, so no caller can dress an edit up as a
+restore either. The replaced body is snapshotted like any other edit and the
+rail says *Saved by an AI client*; restoring it is one click, and that restore is
+itself undoable. There is no delete tool: destroying documentation stays a human
+action.
+
+---
+
## Standalone mode
Documents are **full-mode only**. Standalone has no backend to store or search
@@ -244,6 +274,5 @@ into `localStorage` with no search and no history.
## Not built yet
Export/import of the tree as `.md` files, a print/handbook view, an aggregated
-open-tasks view, image upload inside a document (would reuse
-`api/routes/media.py`, full-mode only), and the MCP tools — those are the
-planned second lot.
+open-tasks view, and image upload inside a document (would reuse
+`api/routes/media.py`, full-mode only) — the planned second lot.
diff --git a/frontend/src/documentation/__tests__/DocHistory.test.tsx b/frontend/src/documentation/__tests__/DocHistory.test.tsx
index 34b8139..7da82ec 100644
--- a/frontend/src/documentation/__tests__/DocHistory.test.tsx
+++ b/frontend/src/documentation/__tests__/DocHistory.test.tsx
@@ -109,6 +109,13 @@ describe('DocViewer — history', () => {
expect(screen.getByText(/2 kB/)).toBeTruthy()
})
+ it('names an AI client as the author of the revision it took', () => {
+ const history = controls({ open: true, revisions: [revision({ reason: 'mcp' })] })
+ render(<DocViewer {...base} doc={makeDoc()} history={history} />)
+
+ expect(screen.getByText('Saved by an AI client')).toBeTruthy()
+ })
+
it('explains an empty history rather than showing an empty list', () => {
render(<DocViewer {...base} doc={makeDoc()} history={controls({ open: true })} />)
expect(screen.getByText(/No earlier version yet/)).toBeTruthy()
diff --git a/frontend/src/documentation/components/DocHistory.tsx b/frontend/src/documentation/components/DocHistory.tsx
index 6a4c118..300662d 100644
--- a/frontend/src/documentation/components/DocHistory.tsx
+++ b/frontend/src/documentation/components/DocHistory.tsx
@@ -28,6 +28,7 @@ const REASONS: Record<DocRevision['reason'], string> = {
migrate: 'Migrated from notes',
scaffold: 'Generated',
regenerate: 'Regenerated',
+ mcp: 'Saved by an AI client',
}
function size(bytes: number): string {
diff --git a/frontend/src/documentation/types.ts b/frontend/src/documentation/types.ts
index 87cb55f..c6ab9f6 100644
--- a/frontend/src/documentation/types.ts
+++ b/frontend/src/documentation/types.ts
@@ -46,7 +46,7 @@ export interface DocRevision {
id: string
document_id: string
title: string
- reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold' | 'regenerate'
+ reason: 'edit' | 'restore' | 'import' | 'migrate' | 'scaffold' | 'regenerate' | 'mcp'
saved_at: string
size: number
}
diff --git a/mcp/app/documents.py b/mcp/app/documents.py
new file mode 100644
index 0000000..1d31d5b
--- /dev/null
+++ b/mcp/app/documents.py
@@ -0,0 +1,170 @@
+"""Documentation tools.
+
+The documentation space (`documents`) is the homelab written down: one markdown
+document per Device Inventory row, per canvas, per piece of canvas furniture,
+plus a Library tree of free pages and folders. The body is the source of truth —
+frontmatter and tags are derived from it — so every write here sends a body and
+lets the backend re-derive the rest.
+
+Reading is meant to be cheap: `search_documentation` is the entry point,
+`list_documentation` returns summaries with no bodies, and only `read_document`
+pays for a full body.
+"""
+
+from typing import Any
+from urllib.parse import urlencode
+
+from mcp.types import Tool
+
+from .backend_client import backend
+
+# Kept in sync with DOCUMENT_KINDS (backend/app/services/doc_tree.py), which is
+# itself the DocKind union in frontend/src/documentation/types.ts.
+DOC_KINDS = ["device", "node", "design", "page", "folder"]
+
+# Filters `GET /api/v1/documents` understands. Anything else in the args is a
+# tool argument the backend has no query parameter for, and is dropped.
+_LIST_FILTERS = ("kind", "parent_id", "device_id", "tag")
+
+# Kept in sync with TEMPLATE_IDS (backend/app/services/doc_template.py).
+# "device" is the only one that reads the live inventory facts; the rest are
+# empty skeletons of headings.
+DOC_TEMPLATES = [
+ "device",
+ "blank",
+ "runbook",
+ "service",
+ "network",
+ "incident",
+ "procedure",
+ "decision",
+ "zone",
+]
+
+# What the history records for anything written through this server. Not a tool
+# argument: an AI client cannot sign its edits as a human's.
+_MCP_REASON = "mcp"
+
+DOC_TOOLS = [
+ Tool(name="search_documentation", description="Full-text search across every document, returning a snippet per hit. The first thing to call when the question is 'what do we know about X' — cheaper than listing and reading documents. `engine` is 'fts5', or 'like' on a SQLite build without FTS5, where snippets are unhighlighted.", inputSchema={
+ "type": "object",
+ "required": ["q"],
+ "properties": {
+ "q": {"type": "string", "description": "Query text. FTS5 syntax (AND, OR, \"quoted phrase\", prefix*) when the engine is fts5."},
+ "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 25},
+ },
+ }),
+ Tool(name="list_documentation", description="List documents as summaries — id, kind, title, tags, frontmatter, drift and review dates, never a body. Use it to find what exists; call read_document for the text.", inputSchema={
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": DOC_KINDS, "description": "'device'/'node'/'design' describe one thing elsewhere in the app; 'page'/'folder' live in the Library tree."},
+ "parent_id": {"type": "string", "description": "Library children of this folder."},
+ "device_id": {"type": "string", "description": "The document describing this inventory device."},
+ "tag": {"type": "string", "description": "Documents carrying this frontmatter tag."},
+ },
+ }),
+ Tool(name="read_document", description="One document in full: its markdown body, frontmatter, tags, and the facts snapshot it was written against.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {"id": {"type": "string", "description": "Document id. Call search_documentation or list_documentation to discover ids."}},
+ }),
+ Tool(name="list_document_revisions", description="The edit history of one document, newest first: who caused each revision ('edit' a human in the editor, 'mcp' an AI client, 'restore', 'regenerate', 'scaffold', 'migrate') and how big the body was. Bodies are not included — read_document_revision fetches one.", inputSchema={
+ "type": "object",
+ "required": ["document_id"],
+ "properties": {"document_id": {"type": "string"}},
+ }),
+ Tool(name="read_document_revision", description="The body a document had at one point in its history. Pair it with read_document to see what an edit changed.", inputSchema={
+ "type": "object",
+ "required": ["revision_id"],
+ "properties": {"revision_id": {"type": "string", "description": "Revision id, from list_document_revisions."}},
+ }),
+ Tool(name="document_backlinks", description="The documents linking to this one with [[wiki links]], and the line each link sits on. Inverted server-side, so it finds links a document does not know it has received.", inputSchema={
+ "type": "object",
+ "required": ["document_id"],
+ "properties": {"document_id": {"type": "string"}},
+ }),
+ Tool(name="create_document", description="Write a new document. Send a body to write it outright, or a template_id to scaffold one from headings. A device/node/design document must name the thing it describes; a page or folder may name a parent folder.", inputSchema={
+ "type": "object",
+ "required": ["title"],
+ "properties": {
+ "title": {"type": "string"},
+ "kind": {"type": "string", "enum": DOC_KINDS, "default": "page"},
+ "body": {"type": "string", "description": "Markdown, optionally opening with a `---` frontmatter block. Wins over template_id."},
+ "icon": {"type": "string"},
+ "parent_id": {"type": "string", "description": "Library folder this page or folder is filed under."},
+ "device_id": {"type": "string", "description": "Inventory device this document describes (kind 'device')."},
+ "node_id": {"type": "string", "description": "Canvas node this document describes (kind 'node')."},
+ "design_id": {"type": "string", "description": "Canvas this document describes (kind 'design')."},
+ "template_id": {"type": "string", "enum": DOC_TEMPLATES, "description": "Scaffold the body from this template when no body is sent. 'device' is implied for a device document and is the only one that reads the live facts."},
+ },
+ }),
+ Tool(name="update_document", description="Edit a document. Only the fields sent are applied. Changing the body snapshots the previous one into the history first, tagged as an AI edit, so nothing written here is lost and a human can restore what was there before.", inputSchema={
+ "type": "object",
+ "required": ["id"],
+ "properties": {
+ "id": {"type": "string"},
+ "body": {"type": "string", "description": "The full replacement body — not a patch. Read the document first and send it back edited, or the rest of it is dropped."},
+ "title": {"type": "string", "description": "Renames the document. A `title:` in the body's frontmatter does the same and is the way the UI does it."},
+ "icon": {"type": "string"},
+ "parent_id": {"type": "string", "description": "Refile a page or folder under another folder."},
+ "sort_order": {"type": "integer"},
+ "starred": {"type": "boolean"},
+ "reviewed": {"type": "boolean", "description": "Records 'I have re-read this and it is still true' at the server's clock."},
+ "resync_facts": {"type": "boolean", "description": "Accept the device's current facts as documented, clearing the drift banner without touching the body."},
+ },
+ }),
+ Tool(name="restore_document_revision", description="Put an earlier body back. The body being replaced becomes history too, so a restore is itself undoable.", inputSchema={
+ "type": "object",
+ "required": ["document_id", "revision_id"],
+ "properties": {
+ "document_id": {"type": "string"},
+ "revision_id": {"type": "string", "description": "From list_document_revisions."},
+ },
+ }),
+]
+
+DOC_TOOL_NAMES = {tool.name for tool in DOC_TOOLS}
+
+
+async def dispatch_document(name: str, args: dict) -> Any:
+ if name == "search_documentation":
+ query: dict[str, Any] = {"q": args["q"]}
+ if args.get("limit"):
+ query["limit"] = args["limit"]
+ return await backend.get(f"/api/v1/documents/search?{urlencode(query)}")
+
+ if name == "list_documentation":
+ filters = {k: args[k] for k in _LIST_FILTERS if args.get(k)}
+ path = "/api/v1/documents"
+ if filters:
+ path += f"?{urlencode(filters)}"
+ return await backend.get(path)
+
+ if name == "read_document":
+ return await backend.get(f"/api/v1/documents/{args['id']}")
+
+ if name == "list_document_revisions":
+ return await backend.get(f"/api/v1/documents/{args['document_id']}/revisions")
+
+ if name == "read_document_revision":
+ return await backend.get(f"/api/v1/documents/revisions/{args['revision_id']}")
+
+ if name == "document_backlinks":
+ return await backend.get(f"/api/v1/documents/{args['document_id']}/backlinks")
+
+ if name == "create_document":
+ return await backend.post("/api/v1/documents", args)
+
+ if name == "update_document":
+ body = {k: v for k, v in args.items() if k not in ("id", "revision_reason")}
+ # Every body this server writes is attributed to it, whatever the
+ # client asked for. The backend ignores the reason when the body is
+ # unchanged, so a starred flag still snapshots nothing.
+ body["revision_reason"] = _MCP_REASON
+ return await backend.patch(f"/api/v1/documents/{args['id']}", body)
+
+ if name == "restore_document_revision":
+ path = f"/api/v1/documents/{args['document_id']}/revisions/{args['revision_id']}/restore"
+ return await backend.post(path, {})
+
+ raise ValueError(f"Unknown documentation tool: {name}")
diff --git a/mcp/app/resources.py b/mcp/app/resources.py
index c12a68d..ed118a6 100644
--- a/mcp/app/resources.py
+++ b/mcp/app/resources.py
@@ -10,6 +10,7 @@ RESOURCE_LIST = [
Resource(uri="homelable://edges", name="Edges", description="All network edges/links", mimeType="application/json"),
Resource(uri="homelable://scan/pending", name="Pending devices", description="Discovered devices awaiting approval", mimeType="application/json"),
Resource(uri="homelable://scan/runs", name="Scan history", description="Recent scan run history", mimeType="application/json"),
+ Resource(uri="homelable://documents", name="Documentation", description="Every document as a summary — no bodies; read homelable://documents/<id> for one", mimeType="application/json"),
]
ROUTES = {
@@ -18,6 +19,7 @@ ROUTES = {
"homelable://edges": "/api/v1/edges",
"homelable://scan/pending": "/api/v1/scan/pending",
"homelable://scan/runs": "/api/v1/scan/runs",
+ "homelable://documents": "/api/v1/documents",
}
# read_resource() also serves homelable://nodes/<id>, which is not in
@@ -31,6 +33,12 @@ RESOURCE_TEMPLATES = [
description="A single node by id",
mimeType="application/json",
),
+ ResourceTemplate(
+ uriTemplate="homelable://documents/{document_id}",
+ name="Document",
+ description="One document in full, body included",
+ mimeType="application/json",
+ ),
]
@@ -49,6 +57,11 @@ async def read_resource(uri: str) -> list[ReadResourceContents]:
data = await backend.get(f"/api/v1/nodes/{node_id}")
return [_json_contents(data)]
+ if uri.startswith("homelable://documents/") and uri != "homelable://documents/":
+ document_id = uri.split("/")[-1]
+ data = await backend.get(f"/api/v1/documents/{document_id}")
+ return [_json_contents(data)]
+
if uri not in ROUTES:
raise ValueError(f"Unknown resource URI: {uri}")
diff --git a/mcp/app/tools.py b/mcp/app/tools.py
index 90f3823..7f21235 100644
--- a/mcp/app/tools.py
+++ b/mcp/app/tools.py
@@ -4,6 +4,7 @@ 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 .documents import DOC_TOOL_NAMES, DOC_TOOLS, dispatch_document
from .racks import RACK_TOOL_NAMES, RACK_TOOLS, dispatch_rack
@@ -316,9 +317,10 @@ def _build_tools() -> list[Tool]:
]
-# 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
+# The rack canvas, the inventory write routes and the documentation space live
+# in their own modules — each is big enough to bury the logical-canvas tools
+# this file is about.
+TOOLS = _build_tools() + RACK_TOOLS + DEVICE_TOOLS + DOC_TOOLS
def register_tools(server: Server):
@@ -411,6 +413,9 @@ async def _dispatch(name: str, args: dict) -> dict:
if name in DEVICE_TOOL_NAMES:
return await dispatch_device(name, args)
+ if name in DOC_TOOL_NAMES:
+ return await dispatch_document(name, args)
+
if name == "create_node":
return await backend.post("/api/v1/nodes", args)
diff --git a/mcp/tests/test_doc_kinds_sync.py b/mcp/tests/test_doc_kinds_sync.py
new file mode 100644
index 0000000..282aee6
--- /dev/null
+++ b/mcp/tests/test_doc_kinds_sync.py
@@ -0,0 +1,29 @@
+import re
+from pathlib import Path
+
+from app.documents import DOC_KINDS
+
+DOC_TREE_FILE = (
+ Path(__file__).resolve().parents[2] / "backend" / "app" / "services" / "doc_tree.py"
+)
+
+
+def _backend_document_kinds() -> set[str]:
+ src = DOC_TREE_FILE.read_text()
+ match = re.search(r"DOCUMENT_KINDS = frozenset\(\{([^}]+)\}\)", src)
+ assert match, (
+ "Could not locate DOCUMENT_KINDS in backend/app/services/doc_tree.py — "
+ "update this parser if the file's shape changed."
+ )
+ return set(re.findall(r'"([^"]+)"', match.group(1)))
+
+
+def test_doc_kinds_in_sync_with_the_backend():
+ """A kind the MCP advertises but the backend rejects is a 422 the client cannot fix."""
+ backend_kinds = _backend_document_kinds()
+ mcp_kinds = set(DOC_KINDS)
+ assert mcp_kinds == backend_kinds, (
+ "mcp/app/documents.py DOC_KINDS is out of sync with backend DOCUMENT_KINDS.\n"
+ f"Missing from DOC_KINDS: {sorted(backend_kinds - mcp_kinds)}\n"
+ f"Extra in DOC_KINDS: {sorted(mcp_kinds - backend_kinds)}"
+ )
diff --git a/mcp/tests/test_doc_templates_sync.py b/mcp/tests/test_doc_templates_sync.py
new file mode 100644
index 0000000..97605ff
--- /dev/null
+++ b/mcp/tests/test_doc_templates_sync.py
@@ -0,0 +1,30 @@
+import re
+from pathlib import Path
+
+from app.documents import DOC_TEMPLATES
+
+DOC_TEMPLATE_FILE = (
+ Path(__file__).resolve().parents[2] / "backend" / "app" / "services" / "doc_template.py"
+)
+
+
+def _backend_template_ids() -> set[str]:
+ """Every TEMPLATE_* constant — TEMPLATE_IDS is the device one plus the library ones."""
+ src = DOC_TEMPLATE_FILE.read_text()
+ ids = set(re.findall(r'^TEMPLATE_[A-Z]+ = "([^"]+)"', src, re.MULTILINE))
+ assert ids, (
+ "Could not locate the TEMPLATE_* constants in backend/app/services/doc_template.py — "
+ "update this parser if the file's shape changed."
+ )
+ return ids
+
+
+def test_doc_templates_in_sync_with_the_backend():
+ """template_id is validated server-side: an advertised one that is gone is a 422."""
+ backend_templates = _backend_template_ids()
+ mcp_templates = set(DOC_TEMPLATES)
+ assert mcp_templates == backend_templates, (
+ "mcp/app/documents.py DOC_TEMPLATES is out of sync with backend TEMPLATE_IDS.\n"
+ f"Missing from DOC_TEMPLATES: {sorted(backend_templates - mcp_templates)}\n"
+ f"Extra in DOC_TEMPLATES: {sorted(mcp_templates - backend_templates)}"
+ )
diff --git a/mcp/tests/test_documents.py b/mcp/tests/test_documents.py
new file mode 100644
index 0000000..5d402fc
--- /dev/null
+++ b/mcp/tests/test_documents.py
@@ -0,0 +1,155 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from app.documents import DOC_TOOL_NAMES, DOC_TOOLS, dispatch_document
+
+
+def mock_backend():
+ with patch("app.documents.backend") as m:
+ m.get = AsyncMock(return_value={})
+ m.post = AsyncMock(return_value={"id": "doc-1"})
+ m.patch = AsyncMock(return_value={"id": "doc-1"})
+ m.delete = AsyncMock(return_value={})
+ yield m
+
+
+def _path(mock) -> str:
+ return mock.get.call_args[0][0]
+
+
+# ── search / list ───────────────────────────────────────────────────────────
+
+
+async def test_search_sends_the_query(mock_backend):
+ mock_backend.get.return_value = {"engine": "fts5", "hits": []}
+ result = await dispatch_document("search_documentation", {"q": "nas backup"})
+ assert _path(mock_backend) == "/api/v1/documents/search?q=nas+backup"
+ assert result == {"engine": "fts5", "hits": []}
+
+
+async def test_search_carries_the_limit(mock_backend):
+ await dispatch_document("search_documentation", {"q": "vlan", "limit": 5})
+ assert _path(mock_backend) == "/api/v1/documents/search?q=vlan&limit=5"
+
+
+async def test_list_without_a_filter_asks_for_everything(mock_backend):
+ await dispatch_document("list_documentation", {})
+ assert _path(mock_backend) == "/api/v1/documents"
+
+
+async def test_list_forwards_only_the_filters_the_backend_knows(mock_backend):
+ await dispatch_document(
+ "list_documentation", {"kind": "page", "device_id": "d1", "limit": 10}
+ )
+ assert _path(mock_backend) == "/api/v1/documents?kind=page&device_id=d1"
+
+
+# ── read ────────────────────────────────────────────────────────────────────
+
+
+async def test_read_document(mock_backend):
+ await dispatch_document("read_document", {"id": "doc-1"})
+ assert _path(mock_backend) == "/api/v1/documents/doc-1"
+
+
+async def test_list_revisions(mock_backend):
+ await dispatch_document("list_document_revisions", {"document_id": "doc-1"})
+ assert _path(mock_backend) == "/api/v1/documents/doc-1/revisions"
+
+
+async def test_read_revision_is_addressed_by_revision_id_alone(mock_backend):
+ """The revision route hangs off /documents/revisions, not off the document."""
+ await dispatch_document("read_document_revision", {"revision_id": "rev-1"})
+ assert _path(mock_backend) == "/api/v1/documents/revisions/rev-1"
+
+
+async def test_backlinks(mock_backend):
+ await dispatch_document("document_backlinks", {"document_id": "doc-1"})
+ assert _path(mock_backend) == "/api/v1/documents/doc-1/backlinks"
+
+
+# ── write ───────────────────────────────────────────────────────────────────
+
+
+async def test_create_document_forwards_the_arguments(mock_backend):
+ args = {"title": "VLAN plan", "kind": "page", "body": "# VLANs", "template_id": "network"}
+ result = await dispatch_document("create_document", dict(args))
+ mock_backend.post.assert_called_once_with("/api/v1/documents", args)
+ assert result == {"id": "doc-1"}
+
+
+async def test_update_document_sends_everything_but_the_id(mock_backend):
+ await dispatch_document("update_document", {"id": "doc-1", "body": "new", "starred": True})
+ path, body = mock_backend.patch.call_args[0]
+ assert path == "/api/v1/documents/doc-1"
+ assert body["body"] == "new"
+ assert body["starred"] is True
+ assert "id" not in body
+
+
+async def test_an_edit_is_recorded_as_an_ai_edit(mock_backend):
+ await dispatch_document("update_document", {"id": "doc-1", "body": "new"})
+ _, body = mock_backend.patch.call_args[0]
+ assert body["revision_reason"] == "mcp"
+
+
+async def test_a_client_cannot_sign_its_edit_as_a_human(mock_backend):
+ """The history has to be able to say an AI wrote this, whatever was asked."""
+ await dispatch_document(
+ "update_document", {"id": "doc-1", "body": "new", "revision_reason": "edit"}
+ )
+ _, body = mock_backend.patch.call_args[0]
+ assert body["revision_reason"] == "mcp"
+
+
+async def test_restore_posts_to_the_document_that_owns_the_revision(mock_backend):
+ await dispatch_document(
+ "restore_document_revision", {"document_id": "doc-1", "revision_id": "rev-1"}
+ )
+ mock_backend.post.assert_called_once_with(
+ "/api/v1/documents/doc-1/revisions/rev-1/restore", {}
+ )
+
+
+async def test_there_is_no_delete_tool():
+ """Destroying documentation stays a human action."""
+ assert not [name for name in DOC_TOOL_NAMES if "delete" in name]
+
+
+# ── wiring ──────────────────────────────────────────────────────────────────
+
+
+async def test_an_unknown_tool_is_refused():
+ with pytest.raises(ValueError, match="Unknown documentation tool"):
+ await dispatch_document("delete_everything", {})
+
+
+def test_every_advertised_tool_dispatches():
+ """A tool the server lists but cannot route is a dead entry in the client."""
+ import inspect
+
+ from app import documents
+
+ source = inspect.getsource(documents.dispatch_document)
+ for name in DOC_TOOL_NAMES:
+ assert f'"{name}"' in source
+
+
+def test_tool_names_are_unique():
+ assert len({tool.name for tool in DOC_TOOLS}) == len(DOC_TOOLS)
diff --git a/mcp/tests/test_resources.py b/mcp/tests/test_resources.py
index 477b681..d043f0a 100644
--- a/mcp/tests/test_resources.py
+++ b/mcp/tests/test_resources.py
@@ -37,6 +37,24 @@ async def test_read_single_node(mock_backend):
mock_backend.get.assert_called_once_with("/api/v1/nodes/abc123")
+async def test_read_documents(mock_backend):
+ await read_resource("homelable://documents")
+ mock_backend.get.assert_called_once_with("/api/v1/documents")
+
+
+async def test_read_single_document(mock_backend):
+ await read_resource("homelable://documents/doc-1")
+ mock_backend.get.assert_called_once_with("/api/v1/documents/doc-1")
+
+
+async def test_read_single_document_anyurl(mock_backend):
+ await read_resource(AnyUrl("homelable://documents/doc-1"))
+ mock_backend.get.assert_called_once_with("/api/v1/documents/doc-1")
+
+
@pytest.mark.anyio
async def test_read_scan_pending(mock_backend):
await read_resource("homelable://scan/pending")
@@ -110,4 +128,7 @@ async def test_resource_templates_are_registered():
result = await handler(None)
templates = result.root.resourceTemplates
- assert [t.uriTemplate for t in templates] == ["homelable://nodes/{node_id}"]
+ assert [t.uriTemplate for t in templates] == [
+ "homelable://nodes/{node_id}",
+ "homelable://documents/{document_id}",
+ ]