|
| 1 | +"""Files Versions tools — list and restore file versions via WebDAV API.""" |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import json |
| 5 | +import xml.etree.ElementTree as ET |
| 6 | +from typing import Any |
| 7 | +from urllib.parse import unquote as url_unquote |
| 8 | + |
| 9 | +from mcp.server.fastmcp import FastMCP |
| 10 | + |
| 11 | +from ..annotations import ADDITIVE_IDEMPOTENT, READONLY |
| 12 | +from ..client import DAV_NS, NC_NS |
| 13 | +from ..permissions import PermissionLevel, require_permission |
| 14 | +from ..state import get_client, get_config |
| 15 | + |
| 16 | +_VERSION_PROPS = [ |
| 17 | + (f"{{{DAV_NS}}}getlastmodified", "last_modified"), |
| 18 | + (f"{{{DAV_NS}}}getcontentlength", "size"), |
| 19 | + (f"{{{DAV_NS}}}getcontenttype", "content_type"), |
| 20 | + (f"{{{NC_NS}}}version-author", "author"), |
| 21 | + (f"{{{NC_NS}}}version-label", "label"), |
| 22 | +] |
| 23 | + |
| 24 | + |
| 25 | +def _parse_versions_xml(xml_text: str, user: str, file_id: int) -> list[dict[str, Any]]: |
| 26 | + """Parse a versions PROPFIND response into a list of version dicts.""" |
| 27 | + root = ET.fromstring(xml_text) # noqa: S314 |
| 28 | + entries: list[dict[str, Any]] = [] |
| 29 | + prefix = f"/remote.php/dav/versions/{user}/versions/{file_id}/" |
| 30 | + |
| 31 | + for response in root.findall(f"{{{DAV_NS}}}response"): |
| 32 | + href_el = response.find(f"{{{DAV_NS}}}href") |
| 33 | + if href_el is None or href_el.text is None: |
| 34 | + continue |
| 35 | + href = url_unquote(href_el.text) |
| 36 | + if href.rstrip("/") == prefix.rstrip("/"): |
| 37 | + continue |
| 38 | + version_id = href.split(prefix, 1)[1].rstrip("/") if prefix in href else "" |
| 39 | + if not version_id: |
| 40 | + continue |
| 41 | + propstat = response.find(f"{{{DAV_NS}}}propstat") |
| 42 | + if propstat is None: |
| 43 | + continue |
| 44 | + prop = propstat.find(f"{{{DAV_NS}}}prop") |
| 45 | + if prop is None: |
| 46 | + continue |
| 47 | + entry: dict[str, Any] = {"version_id": version_id} |
| 48 | + for tag, key in _VERSION_PROPS: |
| 49 | + el = prop.find(tag) |
| 50 | + if el is not None and el.text: |
| 51 | + entry[key] = el.text |
| 52 | + if "size" in entry: |
| 53 | + with contextlib.suppress(ValueError, TypeError): |
| 54 | + entry["size"] = int(entry["size"]) |
| 55 | + entries.append(entry) |
| 56 | + |
| 57 | + return entries |
| 58 | + |
| 59 | + |
| 60 | +def _register_read_tools(mcp: FastMCP) -> None: |
| 61 | + @mcp.tool(annotations=READONLY) |
| 62 | + @require_permission(PermissionLevel.READ) |
| 63 | + async def list_versions(file_id: int) -> str: |
| 64 | + """List all versions of a file by its file ID. |
| 65 | +
|
| 66 | + Returns the version history including the current version. |
| 67 | + Use the file_id from list_directory or search_files results. |
| 68 | +
|
| 69 | + Args: |
| 70 | + file_id: The numeric Nextcloud file ID. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + JSON list of versions, each with: version_id (unix timestamp), |
| 74 | + last_modified, size, content_type, author, and optionally label. |
| 75 | + Use version_id with restore_version to revert the file. |
| 76 | + """ |
| 77 | + client = get_client() |
| 78 | + xml_text = await client.versions_propfind(file_id) |
| 79 | + entries = _parse_versions_xml(xml_text, get_config().user, file_id) |
| 80 | + return json.dumps(entries, indent=2, default=str) |
| 81 | + |
| 82 | + |
| 83 | +def _register_write_tools(mcp: FastMCP) -> None: |
| 84 | + @mcp.tool(annotations=ADDITIVE_IDEMPOTENT) |
| 85 | + @require_permission(PermissionLevel.WRITE) |
| 86 | + async def restore_version(file_id: int, version_id: str) -> str: |
| 87 | + """Restore a file to a previous version. |
| 88 | +
|
| 89 | + The file's current content is replaced with the content from the |
| 90 | + specified version. The pre-restore content is preserved as a new |
| 91 | + version in the history, so no data is lost. |
| 92 | +
|
| 93 | + Args: |
| 94 | + file_id: The numeric Nextcloud file ID. |
| 95 | + version_id: The version identifier from list_versions |
| 96 | + (a unix timestamp string, e.g. "1711000000"). |
| 97 | +
|
| 98 | + Returns: |
| 99 | + Confirmation message. |
| 100 | + """ |
| 101 | + client = get_client() |
| 102 | + await client.versions_restore(file_id, version_id) |
| 103 | + return f"Restored file {file_id} to version {version_id}." |
| 104 | + |
| 105 | + |
| 106 | +def register(mcp: FastMCP) -> None: |
| 107 | + """Register file version tools with the MCP server.""" |
| 108 | + _register_read_tools(mcp) |
| 109 | + _register_write_tools(mcp) |
0 commit comments