0.10.0: Sicherheitsfixes und neue Werkzeuge (Konflikte, Versionen, Geräte)

Fixes:
- resume_folder braucht confirm bei sendreceive/sendonly (Löschungen würden
  sich auf alle Geräte verteilen)
- accept_folder legt Ordner unter <Default-Pfad>/<Label> an statt direkt im
  Default-Pfad; belegte Pfade werden abgelehnt
- override/revert prüfen den Ordnertyp
- Fehler als MCP-ToolError (isError) mit verständlichem Text
- truncate hält JSON gültig
- pause/resume patchen nur "paused"; Bearer-Vergleich zeitkonstant
- uv.lock zum mcp<2.0-Pin synchronisiert

Neu: syncthing_find_conflicts, syncthing_list_versions,
syncthing_restore_version, syncthing_folder_stats, syncthing_add_device,
syncthing_share_folder, syncthing_set_device_paused

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michael RollandClaude Opus 5.5 committed 2026-11-23 12:48:13 +01:00
1 parent 73eb016863
commit b678f1da1c
24 files changed
+1041 -103

No files matched your search

+30
View File
@@ -4,6 +4,36 @@ All notable changes to `syncthing-blade-mcp` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [0.10.0] - 2026-11-23
### Fixed
- `syncthing_resume_folder` now requires `confirm=true` on sendreceive/sendonly
folders: deletions made while paused (the documented "safe removal" workflow)
would otherwise be propagated to every device.
- `syncthing_accept_folder` without `path` used Syncthing's default folder root
itself, so every accepted folder landed in the same directory. It now uses
`<default path>/<label>` like the web UI and refuses paths already in use.
- `syncthing_override_folder` / `syncthing_revert_folder` check the folder type
(sendonly / receiveonly) instead of sending a request Syncthing rejects.
- Failures are raised as MCP tool errors (`isError: true`) with actionable text
instead of being returned as normal results.
- Truncated large responses stay valid JSON (lists are shortened, a `truncated`
note is added) instead of being cut mid-structure.
- Pause/resume patch only `paused` instead of re-sending the whole folder config.
- Bearer token compared in constant time (HTTP transport).
- `uv.lock` re-synced with the `mcp<2.0` pin.
### Added
- `syncthing_find_conflicts`: `*.sync-conflict-*` copies with original file,
conflict time and causing device, newest first.
- `syncthing_list_versions` / `syncthing_restore_version` (confirm): archived file
versions of folders with versioning.
- `syncthing_folder_stats`: last scan and last synced file per folder.
- `syncthing_add_device` (confirm), `syncthing_share_folder` (confirm),
`syncthing_set_device_paused`.
## [0.9.0] - 2026-06-11
### Security
+24 -2
View File
@@ -14,7 +14,7 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing'
- **HTTP transport** — Streamable HTTP with bearer-token auth, Cloudflare Tunnel support
- **SKILL.md** — LLM skill guide for optimal tool usage
## Tools (39 total)
## Tools (45 total)
### Instance Management
@@ -52,6 +52,9 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing'
| Tool | Description | Mutating |
|------|-------------|----------|
| `syncthing_device_completion` | Aggregated completion for a device | No |
| `syncthing_add_device` | Add a device by ID (no pending request needed) | Yes |
| `syncthing_share_folder` | Share an existing folder with a configured device | Yes |
| `syncthing_set_device_paused` | Pause or resume all syncing with one device | Yes |
### Folder Operations
@@ -59,7 +62,8 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing'
|------|-------------|----------|
| `syncthing_scan_folder` | Trigger an immediate rescan | Yes |
| `syncthing_pause_folder` | Pause a folder (prevents deletion propagation) | Yes |
| `syncthing_resume_folder` | Resume a paused folder | Yes |
| `syncthing_resume_folder` | Resume a paused folder (`confirm=true` for sendreceive/sendonly) | Yes |
| `syncthing_folder_stats` | Last scan and last synced file per folder | No |
### File-Level Queries
@@ -76,6 +80,9 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing'
|------|-------------|----------|
| `syncthing_override_folder` | Override remote changes (send-only folder) | Yes |
| `syncthing_revert_folder` | Revert local changes (receive-only folder) | Yes |
| `syncthing_find_conflicts` | List `*.sync-conflict-*` copies with original file, time and device | No |
| `syncthing_list_versions` | Archived file versions (folder versioning) | No |
| `syncthing_restore_version` | Restore one archived version of one file | Yes |
### Config Mutation: Pending Devices & Folders
@@ -115,6 +122,19 @@ call itself, with a refusal message explaining what the operation will do:
| `syncthing_accept_device` | Admits a pending device into the cluster |
| `syncthing_accept_folder` | Starts syncing a remote folder's contents to local disk |
| `syncthing_set_ignores` | Replaces the folder's entire `.stignore` pattern set |
| `syncthing_resume_folder` | sendreceive/sendonly only: local deletions made while paused propagate to all devices |
| `syncthing_restore_version` | Replaces the current file on every device |
| `syncthing_add_device` | Lets a new device connect |
| `syncthing_share_folder` | Gives the device all files of the folder |
`syncthing_override_folder` and `syncthing_revert_folder` check the folder type
first and refuse on folders where the operation does not apply.
`syncthing_accept_folder` creates the folder in `<default path>/<label>` (like the
web UI) unless `path` is given, and refuses a path already used by another folder.
Failures (HTTP errors, unreachable Syncthing, invalid IDs) are raised as MCP tool
errors (`isError: true`); gate and confirm refusals are normal results that explain
what to do next.
## Token Efficiency
@@ -199,6 +219,8 @@ Every tool accepts an optional `instance` parameter to target a specific node. W
4. Delete the local data outside of Syncthing
5. Optionally remove the folder from this device's config via the Syncthing web UI
> **Never resume after deleting:** `syncthing_resume_folder` on a `sendreceive` folder would now delete those files on every device. That is why it requires `confirm=true`.
> **Important:** Always pause before deleting. In a `sendreceive` folder, deleting files without pausing will propagate the deletion to all connected devices.
The `safe` flag requires: at least one remote device at 100% completion with `remoteState: valid`, the folder in `idle` state, and the folder not paused. This is deliberately conservative.
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "syncthing-blade-mcp"
version = "0.9.0"
version = "0.10.0"
description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation."
requires-python = ">=3.11"
dependencies = [
+1 -1
View File
@@ -1,3 +1,3 @@
"""Syncthing MCP Server — manage Syncthing instances via MCP tools."""
__version__ = "0.9.0"
__version__ = "0.10.0"
+3 -1
View File
@@ -1,5 +1,7 @@
"""Bearer token authentication middleware for Streamable HTTP transport."""
import hmac
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
@@ -23,7 +25,7 @@ class BearerAuthMiddleware(BaseHTTPMiddleware):
return await call_next(request)
auth = request.headers.get("authorization", "")
if not auth.startswith("Bearer ") or auth[7:] != self.token:
if not auth.startswith("Bearer ") or not hmac.compare_digest(auth[7:], self.token):
return JSONResponse(
{"error": "Invalid or missing bearer token"},
status_code=401,
+44 -1
View File
@@ -85,10 +85,53 @@ def format_bytes(n: int | float) -> str:
return f"{n:.1f} PB"
def _largest_list(node: Any) -> list | None:
"""Return the longest list anywhere inside ``node`` (by item count)."""
best: list | None = None
stack = [node]
while stack:
cur = stack.pop()
if isinstance(cur, list):
if best is None or len(cur) > len(best):
best = cur
stack.extend(cur)
elif isinstance(cur, dict):
stack.extend(cur.values())
return best
def truncate(text: str, limit: int = CHARACTER_LIMIT) -> str:
"""Truncate text that exceeds the character limit, with guidance."""
"""Keep output under ``limit`` characters.
JSON payloads are shrunk structurally (the longest list is cut first), so the
result is still valid JSON and carries a ``truncated`` note. Non-JSON text is
cut at a line boundary as before.
"""
if len(text) <= limit:
return text
try:
data = json.loads(text)
except ValueError:
data = None
if isinstance(data, (dict, list)):
compact = "\n" not in text
removed = 0
while True:
target = _largest_list(data)
if not target:
break
cut = max(1, len(target) // 4)
del target[-cut:]
removed += cut
note = {
"original_chars": len(text),
"items_removed": removed,
"hint": "Use pagination or filters to narrow results.",
}
wrapped = {**data, "truncated": note} if isinstance(data, dict) else {"items": data, "truncated": note}
out = fmt(wrapped, concise=compact)
if len(out) <= limit:
return out
cut = text[:limit]
last_nl = cut.rfind("\n")
if last_nl > limit * 0.8:
+76 -1
View File
@@ -7,7 +7,6 @@ import os
from pydantic import BaseModel, ConfigDict, Field
# ---------------------------------------------------------------------------
# DD-278 scope-tag vocabulary (Phase A.1 — Track 1)
# ---------------------------------------------------------------------------
@@ -172,6 +171,18 @@ class ConfirmWriteParams(WriteParams):
confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION)
class ResumeFolderInput(FolderWriteParams):
"""Resume a folder. send-receive / send-only folders need confirm=true."""
confirm: bool = Field(
False,
description=(
"Required for sendreceive/sendonly folders: local deletions made while "
"paused are propagated to every device when the folder resumes."
),
)
class ConfirmFolderWriteParams(FolderWriteParams):
"""Folder write tool requiring explicit confirmation (destructive/disruptive)."""
@@ -280,6 +291,70 @@ class RemoteNeedInput(ReadParams):
per_page: int = Field(50, description="Items per page", ge=1, le=500)
# ---------------------------------------------------------------------------
# Maintenance: conflicts, versions, folder stats, device management
# ---------------------------------------------------------------------------
_DEVICE_ID_HELP = "Full Syncthing device ID (8 groups of 7 characters, e.g. ABCDEFG-HIJKLMN-...)."
class FindConflictsInput(ReadParams):
"""Find Syncthing conflict copies (*.sync-conflict-*)."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str | None = Field(
None, description="Folder ID. Omit to scan every folder (slower on large folders)."
)
limit: int = Field(50, description="Maximum conflicts returned", ge=1, le=500)
class ListVersionsInput(ReadParams):
"""List archived file versions (needs file versioning on the folder)."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Folder ID", min_length=1)
path_prefix: str = Field("", description="Only files whose path starts with this prefix.")
limit: int = Field(50, description="Maximum files returned", ge=1, le=500)
class RestoreVersionInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Folder ID", min_length=1)
file: str = Field(..., description="File path exactly as listed by syncthing_list_versions", min_length=1)
version_time: str = Field(
..., description="versionTime exactly as listed by syncthing_list_versions", min_length=1
)
confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION)
class FolderStatsInput(ReadParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str | None = Field(None, description="Folder ID. Omit for all folders.")
class AddDeviceInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(..., description=_DEVICE_ID_HELP, min_length=1)
name: str = Field(..., description="Friendly device name", min_length=1)
addresses: list[str] | None = Field(
None, description="Optional addresses, e.g. ['tcp://192.168.1.20:22000']. Default: dynamic."
)
confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION)
class ShareFolderInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Folder ID", min_length=1)
device_id: str = Field(..., description="Device ID (must already be configured)", min_length=1)
confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION)
class SetDevicePausedInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(..., description="Device ID", min_length=1)
paused: bool = Field(..., description="true pauses all syncing with this device, false resumes")
# ---------------------------------------------------------------------------
# Backward-compatible aliases (referenced by existing tests)
# ---------------------------------------------------------------------------
+35 -2
View File
@@ -70,13 +70,46 @@ def get_all_instances() -> dict[str, SyncthingClient]:
return _instances
def handle_error_global(e: Exception) -> str:
"""Fallback error handler when instance cannot be determined."""
def describe_error(e: Exception) -> str:
"""Human-readable, actionable error text (never contains the API key)."""
import httpx
if isinstance(e, httpx.HTTPStatusError):
status = e.response.status_code
detail = (e.response.text or "").strip().replace("\n", " ")[:300]
path = e.request.url.path if e.request is not None else ""
hints = {
401: "Unauthorized - check SYNCTHING_API_KEY.",
403: "Forbidden - the API key may lack permissions.",
404: "Not found - check the folder/device ID.",
}
hint = hints.get(status) or (
"Syncthing rejected the request - often an unknown folder/device ID or a "
"folder type that does not support this operation."
if status in (400, 500) else ""
)
return f"Error {status} from Syncthing {path}: {hint} {detail}".strip()
if isinstance(e, httpx.ConnectError):
return "Error: cannot connect to Syncthing. Is it running and is SYNCTHING_URL correct?"
if isinstance(e, httpx.TimeoutException):
return "Error: request to Syncthing timed out. It may be busy or unreachable."
if isinstance(e, ValueError):
return f"Error: {e}"
return f"Error: {type(e).__name__}: {e}"
def handle_error_global(e: Exception) -> str:
"""Fallback error handler when instance cannot be determined."""
return describe_error(e)
def tool_error(e: Exception) -> Exception:
"""Wrap any failure as an MCP ToolError so clients see ``isError: true``."""
from mcp.server.fastmcp.exceptions import ToolError
return ToolError(describe_error(e))
def reload_instances() -> None:
"""Re-read environment and rebuild the instance registry (for testing)."""
global _instances
+3 -4
View File
@@ -6,16 +6,15 @@ from typing import Any
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from starlette.requests import Request
from starlette.responses import JSONResponse
from stallari_mcp_helpers import (
Pattern,
compute_domain_hint,
load_patterns_from_yaml,
)
from syncthing_mcp.registry import get_all_instances
from starlette.requests import Request
from starlette.responses import JSONResponse
from syncthing_mcp.registry import get_all_instances
# ---------------------------------------------------------------------------
# DD-338 A.2.dom.c — BladeConfigStore reader + Syncthing field projector
+8 -5
View File
@@ -1,7 +1,10 @@
"""Import all tool sub-modules so their @mcp.tool decorators run at import time."""
from syncthing_mcp.tools import config # noqa: F401
from syncthing_mcp.tools import devices # noqa: F401
from syncthing_mcp.tools import folders # noqa: F401
from syncthing_mcp.tools import instances # noqa: F401
from syncthing_mcp.tools import system # noqa: F401
from syncthing_mcp.tools import (
config, # noqa: F401
devices, # noqa: F401
folders, # noqa: F401
instances, # noqa: F401
maintenance, # noqa: F401
system, # noqa: F401
)
+36 -15
View File
@@ -1,6 +1,6 @@
"""Config mutation tools: pending devices/folders, ignores, accept/reject."""
from syncthing_mcp.formatters import fmt, truncate
from syncthing_mcp.formatters import fmt
from syncthing_mcp.models import (
AcceptDeviceInput,
AcceptFolderInput,
@@ -10,13 +10,22 @@ from syncthing_mcp.models import (
RejectFolderInput,
SetDefaultIgnoresInput,
SetIgnoresInput,
WriteParams,
require_write,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.registry import get_instance, tool_error
from syncthing_mcp.server import mcp
def _child_path(base: str, name: str) -> str:
"""Join Syncthing's default folder root with a sanitized folder name."""
safe = "".join("_" if ch in '/\\:*?"<>|' else ch for ch in name).strip(" .") or "folder"
return base.rstrip("/\\") + "/" + safe
def _norm_path(path: str) -> str:
return path.rstrip("/\\")
# =====================================================================
# Pending Devices & Folders
# =====================================================================
@@ -42,7 +51,7 @@ async def syncthing_pending_devices(params: ReadParams) -> str:
concise=params.concise,
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -65,7 +74,7 @@ async def syncthing_pending_folders(params: ReadParams) -> str:
concise=params.concise,
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -109,7 +118,7 @@ async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -140,7 +149,7 @@ async def syncthing_reject_device(params: DeviceWriteParams) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -180,8 +189,20 @@ async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
new_folder = defaults.copy()
new_folder["id"] = params.folder_id
new_folder["label"] = label
if params.path:
new_folder["path"] = params.path
# Syncthing's default folder path is the *parent* directory; the GUI
# appends the label. Copying it unchanged would place every accepted
# folder in the same directory.
new_folder["path"] = params.path or _child_path(defaults.get("path") or "~", label or params.folder_id)
existing = await client._get("/rest/config/folders")
clash = [
f.get("id") for f in existing or []
if _norm_path(f.get("path", "")) == _norm_path(new_folder["path"])
]
if clash:
return fmt({"error": (
f"Path {new_folder['path']!r} is already used by folder(s) {clash}. "
"Pass a different path."
)})
device_list = [{"deviceID": my_id}]
for did in offering_devices:
device_list.append({"deviceID": did})
@@ -195,7 +216,7 @@ async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -226,7 +247,7 @@ async def syncthing_reject_folder(params: RejectFolderInput) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
# =====================================================================
@@ -260,7 +281,7 @@ async def syncthing_get_ignores(params: FolderReadParams) -> str:
data["expanded"] = result.get("expanded", []) or []
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -299,7 +320,7 @@ async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
"count": len(params.patterns),
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -322,7 +343,7 @@ async def syncthing_get_default_ignores(params: ReadParams) -> str:
"lines": result.get("lines", []) or [],
}, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -353,4 +374,4 @@ async def syncthing_set_default_ignores(params: SetDefaultIgnoresInput) -> str:
"count": len(params.lines),
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
+169 -8
View File
@@ -1,5 +1,6 @@
"""Device listing, completion, connection, and stats tools."""
"""Device listing, completion, connection, stats and management tools."""
import re
import time
from typing import Any
@@ -10,10 +11,18 @@ from syncthing_mcp.formatters import (
format_connection,
format_device,
meta_envelope,
truncate,
short_id,
)
from syncthing_mcp.models import DeviceReadParams, ReadParams, _resolve_scope_folders
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.models import (
AddDeviceInput,
DeviceReadParams,
ReadParams,
SetDevicePausedInput,
ShareFolderInput,
_resolve_scope_folders,
require_write,
)
from syncthing_mcp.registry import get_instance, tool_error
from syncthing_mcp.server import compute_domain_hints_for_records, mcp
@@ -91,7 +100,7 @@ async def syncthing_list_devices(params: ReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -125,7 +134,7 @@ async def syncthing_device_completion(params: DeviceReadParams) -> str:
data["needItems"] = comp.get("needItems", 0)
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -162,7 +171,7 @@ async def syncthing_connections(params: ReadParams) -> str:
]
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -197,4 +206,156 @@ async def syncthing_device_stats(params: ReadParams) -> str:
result.append(entry)
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
# =====================================================================
# Device management
# =====================================================================
_DEVICE_ID = re.compile(r"^[A-Z2-7]{7}(-[A-Z2-7]{7}){7}$")
def _normalize_device_id(device_id: str) -> str:
raw = device_id.strip().upper().replace(" ", "")
compact = raw.replace("-", "")
if len(compact) == 56 and "-" not in raw:
raw = "-".join(compact[i:i + 7] for i in range(0, 56, 7))
if not _DEVICE_ID.match(raw):
raise ValueError(
"Invalid device ID: expected 8 groups of 7 characters (A-Z, 2-7) separated by dashes."
)
return raw
async def _configured_device(client, device_id: str) -> dict:
devices = await client._get("/rest/config/devices")
for dev in devices or []:
if str(dev.get("deviceID", "")).upper() == device_id.upper():
return dev
raise ValueError(f"Device {device_id[:7]} is not configured on this instance.")
@mcp.tool(
name="syncthing_add_device",
annotations={
"title": "Add a Device by ID",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": False,
"openWorldHint": False,
},
)
async def syncthing_add_device(params: AddDeviceInput) -> str:
"""Add a remote device by its device ID (no pending request needed). The device
can then connect; no folder is shared until syncthing_share_folder.
Requires SYNCTHING_WRITE_ENABLED=true and confirm=true."""
gate = require_write()
if gate:
return fmt({"error": gate})
try:
device_id = _normalize_device_id(params.device_id)
client = get_instance(params.instance)
existing = await client._get("/rest/config/devices")
if any(str(d.get("deviceID", "")).upper() == device_id for d in existing or []):
return fmt({"error": f"Device {device_id[:7]} is already configured."})
if not params.confirm:
return fmt({"error": (
f"Adding device {params.name!r} ({device_id[:7]}) lets it connect to this "
"instance. Set confirm=true to proceed."
)})
new_device = dict(await client._get("/rest/config/defaults/device"))
new_device.update({"deviceID": device_id, "name": params.name})
if params.addresses:
new_device["addresses"] = params.addresses
await client._post("/rest/config/devices", body=new_device)
return fmt({
"status": "added",
"deviceID": short_id(device_id),
"name": params.name,
"addresses": new_device.get("addresses", ["dynamic"]),
"instance": client.name,
})
except Exception as e:
raise tool_error(e) from None
@mcp.tool(
name="syncthing_share_folder",
annotations={
"title": "Share a Folder with a Device",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_share_folder(params: ShareFolderInput) -> str:
"""Share an existing folder with an already configured device. The device receives
a folder offer and, once accepted there, starts syncing the folder's contents.
Requires SYNCTHING_WRITE_ENABLED=true and confirm=true."""
gate = require_write()
if gate:
return fmt({"error": gate})
try:
client = get_instance(params.instance)
device = await _configured_device(client, params.device_id)
device_id = device["deviceID"]
folder = await client._get(f"/rest/config/folders/{params.folder_id}")
devices = list(folder.get("devices") or [])
if any(str(d.get("deviceID", "")).upper() == device_id.upper() for d in devices):
return fmt({
"status": "already_shared",
"folder": params.folder_id,
"device": device.get("name") or short_id(device_id),
"instance": client.name,
})
if not params.confirm:
return fmt({"error": (
f"Sharing folder {folder.get('label') or params.folder_id!r} ({folder.get('type')}) "
f"with {device.get('name') or short_id(device_id)!r} gives that device all of "
"its files. Set confirm=true to proceed."
)})
devices.append({"deviceID": device_id})
await client._patch(f"/rest/config/folders/{params.folder_id}", body={"devices": devices})
return fmt({
"status": "shared",
"folder": params.folder_id,
"label": folder.get("label"),
"device": device.get("name") or short_id(device_id),
"devices_now": len(devices),
"instance": client.name,
})
except Exception as e:
raise tool_error(e) from None
@mcp.tool(
name="syncthing_set_device_paused",
annotations={
"title": "Pause or Resume a Device",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_set_device_paused(params: SetDevicePausedInput) -> str:
"""Pause or resume all syncing with one device. Reversible; deletes nothing.
Requires SYNCTHING_WRITE_ENABLED=true."""
gate = require_write()
if gate:
return fmt({"error": gate})
try:
client = get_instance(params.instance)
device = await _configured_device(client, params.device_id)
await client._patch(
f"/rest/config/devices/{device['deviceID']}", body={"paused": params.paused}
)
return fmt({
"status": "paused" if params.paused else "resumed",
"device": device.get("name") or short_id(device["deviceID"]),
"instance": client.name,
})
except Exception as e:
raise tool_error(e) from None
+45 -24
View File
@@ -22,13 +22,13 @@ from syncthing_mcp.models import (
FolderWriteParams,
ReadParams,
RemoteNeedInput,
ResumeFolderInput,
_resolve_scope_folders,
require_write,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.registry import get_instance, tool_error
from syncthing_mcp.server import mcp
# =====================================================================
# Folder Status & Replication
# =====================================================================
@@ -104,7 +104,7 @@ async def syncthing_folder_status(params: FolderReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -178,7 +178,7 @@ async def syncthing_folder_completion(params: FolderReadParams) -> str:
"devices": completions,
}, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -298,7 +298,7 @@ async def syncthing_replication_report(params: ReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
# =====================================================================
@@ -325,16 +325,15 @@ async def syncthing_pause_folder(params: FolderWriteParams) -> str:
return fmt({"error": gate})
try:
client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_cfg["paused"] = True
await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg)
await client._get(f"/rest/config/folders/{params.folder_id}") # 404 for unknown ids
await client._patch(f"/rest/config/folders/{params.folder_id}", body={"paused": True})
return fmt({
"status": "paused",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -347,10 +346,12 @@ async def syncthing_pause_folder(params: FolderWriteParams) -> str:
"openWorldHint": False,
},
)
async def syncthing_resume_folder(params: FolderWriteParams) -> str:
"""Resume syncing for a paused folder. WARNING: if local data was deleted
while paused, behaviour depends on folder type (sendreceive may propagate
deletions; receiveonly will re-download).
async def syncthing_resume_folder(params: ResumeFolderInput) -> str:
"""Resume syncing for a paused folder.
sendreceive / sendonly folders require confirm=true: files deleted locally while
the folder was paused are deleted on every other device once it resumes.
receiveonly folders simply re-download and need no confirmation.
Requires SYNCTHING_WRITE_ENABLED=true."""
gate = require_write()
if gate:
@@ -359,8 +360,14 @@ async def syncthing_resume_folder(params: FolderWriteParams) -> str:
client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_type = folder_cfg.get("type", "sendreceive")
folder_cfg["paused"] = False
await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg)
if folder_type in ("sendreceive", "sendonly") and not params.confirm:
return fmt({"error": (
f"Folder '{folder_cfg.get('label') or params.folder_id}' is {folder_type}: "
"anything deleted locally while it was paused will be deleted on all "
"other devices when it resumes. Make sure the local copy is complete, "
"then set confirm=true to proceed."
), "type": folder_type})
await client._patch(f"/rest/config/folders/{params.folder_id}", body={"paused": False})
return fmt({
"status": "resumed",
"folder": params.folder_id,
@@ -368,7 +375,7 @@ async def syncthing_resume_folder(params: FolderWriteParams) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -396,7 +403,7 @@ async def syncthing_scan_folder(params: FolderWriteParams) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -466,7 +473,7 @@ async def syncthing_folder_errors(params: FolderReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
# =====================================================================
@@ -518,7 +525,7 @@ async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -564,7 +571,7 @@ async def syncthing_file_info(params: FileInfoInput) -> str:
"local": result.get("local"),
}, concise=False)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -625,7 +632,7 @@ async def syncthing_folder_need(params: FolderNeedInput) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -690,7 +697,7 @@ async def syncthing_remote_need(params: RemoteNeedInput) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
# =====================================================================
@@ -722,6 +729,13 @@ async def syncthing_override_folder(params: ConfirmFolderWriteParams) -> str:
)})
try:
client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_type = folder_cfg.get("type", "sendreceive")
if folder_type not in ('sendonly',):
return fmt({"error": (
f"Override only applies to sendonly folders; "
f"'{params.folder_id}' is {folder_type}. Nothing was changed."
), "type": folder_type})
await client._post("/rest/db/override", params={"folder": params.folder_id})
return fmt({
"status": "override_requested",
@@ -729,7 +743,7 @@ async def syncthing_override_folder(params: ConfirmFolderWriteParams) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -756,6 +770,13 @@ async def syncthing_revert_folder(params: ConfirmFolderWriteParams) -> str:
)})
try:
client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_type = folder_cfg.get("type", "sendreceive")
if folder_type not in ('receiveonly', 'receiveencrypted'):
return fmt({"error": (
f"Revert only applies to receiveonly / receiveencrypted folders; "
f"'{params.folder_id}' is {folder_type}. Nothing was changed."
), "type": folder_type})
await client._post("/rest/db/revert", params={"folder": params.folder_id})
return fmt({
"status": "revert_requested",
@@ -763,4 +784,4 @@ async def syncthing_revert_folder(params: ConfirmFolderWriteParams) -> str:
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
+2 -2
View File
@@ -8,7 +8,7 @@ from syncthing_mcp.models import ReadParams, _resolve_scope_folders
from syncthing_mcp.registry import (
get_all_instances,
get_instance,
handle_error_global,
tool_error,
)
from syncthing_mcp.server import compute_domain_hints_for_records, mcp
@@ -127,4 +127,4 @@ async def syncthing_list_folders(params: ReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
+238
View File
@@ -0,0 +1,238 @@
"""Maintenance tools: sync conflicts, archived file versions, folder statistics."""
import re
from typing import Any
from syncthing_mcp.formatters import fmt, format_bytes, truncate
from syncthing_mcp.models import (
FindConflictsInput,
FolderStatsInput,
ListVersionsInput,
RestoreVersionInput,
require_write,
)
from syncthing_mcp.registry import get_instance, tool_error
from syncthing_mcp.server import mcp
# name.sync-conflict-20260101-120000-ABCDEFG.ext (extension optional)
_CONFLICT = re.compile(r"^(?P<stem>.*)\.sync-conflict-(?P<date>\d{8})-(?P<time>\d{6})-(?P<device>[A-Z0-9]{7})(?P<ext>\.[^/]*)?$")
def _walk(entries: Any, prefix: str = ""):
"""Yield (path, entry) for every file in a /rest/db/browse tree."""
if isinstance(entries, dict): # legacy map format: {name: children | [modTime, size]}
for name, value in entries.items():
path = f"{prefix}{name}"
if isinstance(value, dict):
yield from _walk(value, path + "/")
else:
mod, size = (value + [None, None])[:2] if isinstance(value, list) else (None, None)
yield path, {"modTime": mod, "size": size}
return
for entry in entries or []:
if not isinstance(entry, dict):
continue
path = f"{prefix}{entry.get('name', '')}"
if "DIRECTORY" in str(entry.get("type", "")) or entry.get("children"):
yield from _walk(entry.get("children") or [], path + "/")
else:
yield path, entry
def find_conflicts(tree: Any) -> list[dict[str, Any]]:
conflicts = []
for path, entry in _walk(tree):
folder, _, name = path.rpartition("/")
match = _CONFLICT.match(name)
if not match:
continue
original = f"{match['stem']}{match['ext'] or ''}"
d, t = match["date"], match["time"]
conflicts.append({
"conflict_file": path,
"original_file": f"{folder}/{original}" if folder else original,
"conflict_time": f"{d[:4]}-{d[4:6]}-{d[6:]} {t[:2]}:{t[2:4]}:{t[4:]}",
"from_device": match["device"],
"size": format_bytes(entry["size"]) if isinstance(entry.get("size"), int) else None,
})
conflicts.sort(key=lambda item: item["conflict_time"], reverse=True)
return conflicts
@mcp.tool(
name="syncthing_find_conflicts",
annotations={
"title": "Find Sync Conflicts",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_find_conflicts(params: FindConflictsInput) -> str:
"""List Syncthing conflict copies (*.sync-conflict-*) with their original file,
conflict time and the device that caused them. Newest first. READ ONLY."""
try:
client = get_instance(params.instance)
if params.folder_id:
folders = [{"id": params.folder_id, "label": params.folder_id}]
else:
folders = await client._get("/rest/config/folders")
result = []
total = 0
for folder in folders:
tree = await client._get("/rest/db/browse", params={"folder": folder["id"]})
found = find_conflicts(tree)
total += len(found)
if found:
result.append({
"folder": folder["id"],
"label": folder.get("label") or folder["id"],
"conflicts": len(found),
"items": found[: params.limit],
})
return truncate(fmt({
"instance": client.name,
"folders_scanned": len(folders),
"total_conflicts": total,
"folders": result,
"hint": (
"Compare conflict_file with original_file, keep the right one and delete "
"the other on disk; Syncthing syncs the result."
) if total else None,
}, concise=params.concise))
except Exception as e:
raise tool_error(e) from None
@mcp.tool(
name="syncthing_list_versions",
annotations={
"title": "List Archived File Versions",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_list_versions(params: ListVersionsInput) -> str:
"""Archived older versions of files in a folder (requires file versioning on the
folder). Use with syncthing_restore_version. READ ONLY."""
try:
client = get_instance(params.instance)
versions = await client._get("/rest/folder/versions", params={"folder": params.folder_id})
files = sorted(
(path, items) for path, items in (versions or {}).items()
if path.startswith(params.path_prefix)
)
rows = [
{
"file": path,
"versions": [
{
"version_time": item.get("versionTime"),
"mod_time": item.get("modTime"),
"size": format_bytes(item["size"]) if isinstance(item.get("size"), int) else None,
}
for item in sorted(items or [], key=lambda v: str(v.get("versionTime")), reverse=True)[:10]
],
}
for path, items in files[: params.limit]
]
return truncate(fmt({
"instance": client.name,
"folder": params.folder_id,
"files_with_versions": len(files),
"returned": len(rows),
"files": rows,
}, concise=params.concise))
except Exception as e:
raise tool_error(e) from None
@mcp.tool(
name="syncthing_restore_version",
annotations={
"title": "Restore an Archived File Version",
"readOnlyHint": False,
"destructiveHint": True,
"idempotentHint": False,
"openWorldHint": False,
},
)
async def syncthing_restore_version(params: RestoreVersionInput) -> str:
"""Restore one archived version of one file. The current file is replaced (and,
with versioning on, archived itself) and the restored file syncs to all devices.
Requires SYNCTHING_WRITE_ENABLED=true and confirm=true."""
gate = require_write()
if gate:
return fmt({"error": gate})
try:
client = get_instance(params.instance)
versions = await client._get("/rest/folder/versions", params={"folder": params.folder_id})
available = [str(v.get("versionTime")) for v in (versions or {}).get(params.file, [])]
if params.version_time not in available:
return fmt({"error": (
f"No version {params.version_time!r} of {params.file!r}. "
"Use syncthing_list_versions and copy file and version_time exactly."
), "available_versions": available[:10]})
if not params.confirm:
return fmt({"error": (
f"Restoring replaces the current {params.file!r} with the version from "
f"{params.version_time} on every device. Set confirm=true to proceed."
)})
errors = await client._post(
"/rest/folder/versions",
params={"folder": params.folder_id},
body={params.file: params.version_time},
)
failed = {k: v for k, v in (errors or {}).items() if k != "status" and v}
if failed:
return fmt({"error": "Syncthing could not restore the file.", "details": failed})
return fmt({
"status": "restored",
"folder": params.folder_id,
"file": params.file,
"version_time": params.version_time,
"instance": client.name,
})
except Exception as e:
raise tool_error(e) from None
@mcp.tool(
name="syncthing_folder_stats",
annotations={
"title": "Folder Statistics (Last Scan / Last File)",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_folder_stats(params: FolderStatsInput) -> str:
"""When each folder was last scanned and which file was synced last. READ ONLY."""
try:
client = get_instance(params.instance)
stats = await client._get("/rest/stats/folder")
folders = await client._get("/rest/config/folders")
labels = {f.get("id"): f.get("label") or f.get("id") for f in folders or []}
rows = []
for folder_id in sorted(stats or {}):
if params.folder_id and folder_id != params.folder_id:
continue
entry = stats[folder_id] or {}
last = entry.get("lastFile") or {}
rows.append({
"folder": folder_id,
"label": labels.get(folder_id, folder_id),
"last_scan": entry.get("lastScan"),
"last_file": last.get("filename") or None,
"last_file_at": last.get("at"),
"last_file_deleted": bool(last.get("deleted")),
})
if params.folder_id and not rows:
raise ValueError(f"No statistics for folder '{params.folder_id}'")
return fmt({"instance": client.name, "folders": rows}, concise=params.concise)
except Exception as e:
raise tool_error(e) from None
+18 -12
View File
@@ -5,7 +5,13 @@ from typing import Any
import httpx
from syncthing_mcp.formatters import append_meta, fmt, format_bytes, meta_envelope, truncate
from syncthing_mcp.formatters import (
append_meta,
fmt,
format_bytes,
meta_envelope,
truncate,
)
from syncthing_mcp.models import (
ConfirmWriteParams,
ReadParams,
@@ -13,7 +19,7 @@ from syncthing_mcp.models import (
_resolve_scope_folders,
require_write,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.registry import get_instance, tool_error
from syncthing_mcp.server import mcp
@@ -55,11 +61,11 @@ async def syncthing_system_status(params: ReadParams) -> str:
return fmt(data, concise=params.concise)
except Exception as e:
if isinstance(e, ValueError):
return handle_error_global(e)
raise tool_error(e) from None
try:
return get_instance(None).handle_error(e)
except Exception:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -85,7 +91,7 @@ async def syncthing_system_errors(params: ReadParams) -> str:
}
return truncate(fmt(data, concise=params.concise))
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -109,7 +115,7 @@ async def syncthing_clear_errors(params: WriteParams) -> str:
await client._post("/rest/system/error/clear")
return fmt({"status": "cleared", "instance": client.name})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -135,7 +141,7 @@ async def syncthing_system_log(params: ReadParams) -> str:
}
return truncate(fmt(data, concise=params.concise))
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -211,7 +217,7 @@ async def syncthing_recent_changes(params: ReadParams) -> str:
),
)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -234,7 +240,7 @@ async def syncthing_restart_required(params: ReadParams) -> str:
"restartRequired": result.get("requiresRestart", False),
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -271,7 +277,7 @@ async def syncthing_restart(params: ConfirmWriteParams) -> str:
"message": f"Syncthing '{client.name}' is restarting.",
})
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -306,7 +312,7 @@ async def syncthing_check_upgrade(params: ReadParams) -> str:
})
raise
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
@mcp.tool(
@@ -420,4 +426,4 @@ async def syncthing_health_summary(params: ReadParams) -> str:
data["folders"] = folder_health
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
raise tool_error(e) from None
+8 -1
View File
@@ -1,5 +1,5 @@
name: syncthing-blade-mcp
version: "0.9.0"
version: "0.10.0"
description: "Syncthing replication management MCP — multi-instance, token-efficient output, safe disk-space reclamation"
author: groupthink-dev
license: MIT
@@ -37,11 +37,18 @@ services:
info: syncthing_file_info
need: syncthing_folder_need
remote_need: syncthing_remote_need
conflicts: syncthing_find_conflicts
versions: syncthing_list_versions
restore_version: syncthing_restore_version
stats: syncthing_folder_stats
devices:
list: syncthing_list_devices
completion: syncthing_device_completion
connections: syncthing_connections
stats: syncthing_device_stats
add: syncthing_add_device
share_folder: syncthing_share_folder
set_paused: syncthing_set_device_paused
config:
pending_devices: syncthing_pending_devices
pending_folders: syncthing_pending_folders
+7 -6
View File
@@ -17,6 +17,7 @@ Plus a determinism harness (N=5 byte-equal) for each.
"""
import json
from mcp.server.fastmcp.exceptions import ToolError
import pytest
import respx
@@ -139,9 +140,9 @@ class TestListFoldersScope:
async def test_scope_public_raises(self, mock_api):
from syncthing_mcp.tools.instances import syncthing_list_folders
out = await syncthing_list_folders(ReadParams(scope="public"))
assert out.startswith("Error:")
assert "public" in out
with pytest.raises(ToolError, match="public"):
await syncthing_list_folders(ReadParams(scope="public"))
async def test_meta_envelope_shape(self, mock_api):
from syncthing_mcp.tools.instances import syncthing_list_folders
@@ -282,9 +283,9 @@ class TestRecentChangesScope:
async def test_scope_public_raises(self, mock_api):
from syncthing_mcp.tools.system import syncthing_recent_changes
out = await syncthing_recent_changes(ReadParams(scope="public"))
assert out.startswith("Error:")
assert "public" in out
with pytest.raises(ToolError, match="public"):
await syncthing_recent_changes(ReadParams(scope="public"))
async def test_meta_envelope_shape(self, mock_api):
from syncthing_mcp.tools.system import syncthing_recent_changes
+20 -1
View File
@@ -92,12 +92,31 @@ class TestAcceptFolder:
"path": "/home/user/Sync",
"type": "sendreceive",
})
mock_api.post("/rest/config/folders").respond(status_code=200, content=b"")
mock_api.get("/rest/config/folders").respond(json=[{"id": "old", "path": "/home/user/Sync/Old"}])
post = mock_api.post("/rest/config/folders").respond(status_code=200, content=b"")
result = json.loads(await syncthing_accept_folder(
AcceptFolderInput(folder_id="new-folder", confirm=True)
))
assert result["status"] == "accepted"
assert result["label"] == "Shared Docs"
# Default path is the parent directory: the label is appended, like the GUI does.
assert result["path"] == "/home/user/Sync/Shared Docs"
assert json.loads(post.calls.last.request.content)["path"] == "/home/user/Sync/Shared Docs"
async def test_refuses_path_used_by_other_folder(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.config import syncthing_accept_folder
mock_api.get("/rest/cluster/pending/folders").respond(json={
"new-folder": {"offeredBy": {DEVICE_ID_REMOTE: {"label": "Shared Docs"}}}
})
mock_api.get("/rest/config/defaults/folder").respond(json={"path": "~"})
mock_api.get("/rest/config/folders").respond(json=[{"id": "x", "path": "/data/shared/"}])
post = mock_api.post("/rest/config/folders").respond(status_code=200, content=b"")
result = json.loads(await syncthing_accept_folder(
AcceptFolderInput(folder_id="new-folder", path="/data/shared", confirm=True)
))
assert "already used" in result["error"]
assert not post.called
async def test_not_pending(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.config import syncthing_accept_folder
+5 -4
View File
@@ -1,6 +1,7 @@
"""Tests for device tools (list, completion, connections, stats)."""
import json
from mcp.server.fastmcp.exceptions import ToolError
import pytest
@@ -97,10 +98,10 @@ class TestListDevices:
async def test_scope_public_raises(self, mock_api):
from syncthing_mcp.tools.devices import syncthing_list_devices
# ValueError surfaces via handle_error_global as a plain string
out = await syncthing_list_devices(ReadParams(scope="public"))
assert out.startswith("Error:")
assert "public" in out
# ValueError surfaces as an MCP ToolError (isError=true)
with pytest.raises(ToolError, match="public"):
await syncthing_list_devices(ReadParams(scope="public"))
# DD-338 Phase A.1 — Track 2 — sort-before-return deterministic across N=5
async def test_deterministic_n5(self, mock_api):
+57 -9
View File
@@ -1,6 +1,7 @@
"""Tests for folder tools (status, completion, replication, operations, new tools)."""
import json
from mcp.server.fastmcp.exceptions import ToolError
import pytest
import respx
@@ -14,6 +15,7 @@ from syncthing_mcp.models import (
FolderNeedInput,
FolderReadParams,
PauseFolderInput,
ResumeFolderInput,
ReadParams,
RemoteNeedInput,
)
@@ -237,9 +239,9 @@ class TestReplicationReport:
async def test_scope_public_raises(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_replication_report
out = await syncthing_replication_report(ReadParams(scope="public"))
assert out.startswith("Error:")
assert "public" in out
with pytest.raises(ToolError, match="public"):
await syncthing_replication_report(ReadParams(scope="public"))
# DD-338 Phase A.1 — Track 2 — deterministic N=5 with tie-breaker fixture
async def test_deterministic_n5_with_tiebreaker(self, mock_api):
@@ -297,19 +299,41 @@ class TestPauseFolder:
class TestResumeFolder:
async def test_resume(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_resume_folder
def _mock(self, mock_api, folder_type):
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(
json={"id": FOLDER_ID, "type": "sendreceive", "paused": True}
json={"id": FOLDER_ID, "label": "Docs", "type": folder_type, "paused": True}
)
mock_api.patch(f"/rest/config/folders/{FOLDER_ID}").respond(
return mock_api.patch(f"/rest/config/folders/{FOLDER_ID}").respond(
json={"id": FOLDER_ID, "paused": False},
headers={"content-type": "application/json"},
)
result = json.loads(await syncthing_resume_folder(PauseFolderInput(folder_id=FOLDER_ID)))
async def test_sendreceive_needs_confirm(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_resume_folder
patch_route = self._mock(mock_api, "sendreceive")
result = json.loads(await syncthing_resume_folder(ResumeFolderInput(folder_id=FOLDER_ID)))
assert "confirm=true" in result["error"]
assert "deleted on all" in result["error"]
assert not patch_route.called
async def test_resume_with_confirm_patches_only_paused(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_resume_folder
patch_route = self._mock(mock_api, "sendreceive")
result = json.loads(await syncthing_resume_folder(
ResumeFolderInput(folder_id=FOLDER_ID, confirm=True)
))
assert result["status"] == "resumed"
assert result["type"] == "sendreceive"
assert json.loads(patch_route.calls.last.request.content) == {"paused": False}
async def test_receiveonly_needs_no_confirm(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_resume_folder
self._mock(mock_api, "receiveonly")
result = json.loads(await syncthing_resume_folder(ResumeFolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "resumed"
class TestScanFolder:
@@ -581,19 +605,43 @@ class TestOverrideFolder:
async def test_override(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_override_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={"id": FOLDER_ID, "type": "sendonly"})
mock_api.post("/rest/db/override").respond(status_code=200, content=b"")
result = json.loads(await syncthing_override_folder(
ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True)
))
assert result["status"] == "override_requested"
async def test_override_refuses_wrong_folder_type(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_override_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={"id": FOLDER_ID, "type": "sendreceive"})
route = mock_api.post("/rest/db/override").respond(status_code=200, content=b"")
result = json.loads(await syncthing_override_folder(
ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True)
))
assert "only applies" in result["error"]
assert not route.called
class TestRevertFolder:
async def test_revert(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_revert_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={"id": FOLDER_ID, "type": "receiveonly"})
mock_api.post("/rest/db/revert").respond(status_code=200, content=b"")
result = json.loads(await syncthing_revert_folder(
ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True)
))
assert result["status"] == "revert_requested"
async def test_revert_refuses_wrong_folder_type(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.folders import syncthing_revert_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={"id": FOLDER_ID, "type": "sendreceive"})
route = mock_api.post("/rest/db/revert").respond(status_code=200, content=b"")
result = json.loads(await syncthing_revert_folder(
ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True)
))
assert "only applies" in result["error"]
assert not route.called
+207
View File
@@ -0,0 +1,207 @@
"""Tests for conflict, version, folder-stats and device-management tools."""
import json
import pytest
from mcp.server.fastmcp.exceptions import ToolError
from syncthing_mcp.formatters import truncate
from syncthing_mcp.models import (
AddDeviceInput,
FindConflictsInput,
FolderStatsInput,
ListVersionsInput,
RestoreVersionInput,
SetDevicePausedInput,
ShareFolderInput,
)
from tests.conftest import DEVICE_ID_LOCAL, DEVICE_ID_REMOTE, FOLDER_ID
NEW_DEVICE = "DDDDDDD-DDDDDDD-DDDDDDD-DDDDDDD-DDDDDDD-DDDDDDD-DDDDDDD-DDDDDDD"
TREE = [
{"name": "Docs", "type": "FILE_INFO_TYPE_DIRECTORY", "children": [
{"name": "plan.odt", "type": "FILE_INFO_TYPE_FILE", "size": 100},
{"name": "plan.sync-conflict-20261101-101500-BBBBBBB.odt", "type": "FILE_INFO_TYPE_FILE", "size": 120},
]},
{"name": "notes.sync-conflict-20261120-080000-CCCCCCC", "type": "FILE_INFO_TYPE_FILE", "size": 5},
{"name": "ok.txt", "type": "FILE_INFO_TYPE_FILE", "size": 1},
]
class TestFindConflicts:
async def test_finds_nested_conflicts_newest_first(self, mock_api):
from syncthing_mcp.tools.maintenance import syncthing_find_conflicts
mock_api.get("/rest/db/browse").respond(json=TREE)
result = json.loads(await syncthing_find_conflicts(FindConflictsInput(folder_id=FOLDER_ID)))
assert result["total_conflicts"] == 2
items = result["folders"][0]["items"]
assert items[0]["conflict_file"] == "notes.sync-conflict-20261120-080000-CCCCCCC"
assert items[0]["original_file"] == "notes"
assert items[1]["original_file"] == "Docs/plan.odt"
assert items[1]["from_device"] == "BBBBBBB"
assert items[1]["conflict_time"] == "2026-11-01 10:15:00"
async def test_all_folders_without_conflicts(self, mock_api):
from syncthing_mcp.tools.maintenance import syncthing_find_conflicts
mock_api.get("/rest/config/folders").respond(json=[{"id": "a", "label": "A"}, {"id": "b"}])
mock_api.get("/rest/db/browse").respond(json=[{"name": "x.txt", "type": "FILE_INFO_TYPE_FILE"}])
result = json.loads(await syncthing_find_conflicts(FindConflictsInput()))
assert result["folders_scanned"] == 2
assert result["total_conflicts"] == 0
VERSIONS = {
"Docs/plan.odt": [
{"versionTime": "2026-11-01T10:00:00+01:00", "modTime": "2026-11-01T09:00:00+01:00", "size": 90},
{"versionTime": "2026-11-10T10:00:00+01:00", "modTime": "2026-11-10T09:00:00+01:00", "size": 95},
],
"other.txt": [{"versionTime": "2026-10-01T00:00:00Z", "size": 1}],
}
class TestVersions:
async def test_list_filters_prefix_and_sorts_newest_first(self, mock_api):
from syncthing_mcp.tools.maintenance import syncthing_list_versions
mock_api.get("/rest/folder/versions").respond(json=VERSIONS)
result = json.loads(await syncthing_list_versions(ListVersionsInput(folder_id=FOLDER_ID, path_prefix="Docs/")))
assert result["files_with_versions"] == 1
assert result["files"][0]["versions"][0]["version_time"] == "2026-11-10T10:00:00+01:00"
async def test_restore_needs_existing_version_and_confirm(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.maintenance import syncthing_restore_version
mock_api.get("/rest/folder/versions").respond(json=VERSIONS)
post = mock_api.post("/rest/folder/versions").respond(json={})
wrong = json.loads(await syncthing_restore_version(RestoreVersionInput(
folder_id=FOLDER_ID, file="Docs/plan.odt", version_time="2020-01-01", confirm=True)))
assert "No version" in wrong["error"]
unconfirmed = json.loads(await syncthing_restore_version(RestoreVersionInput(
folder_id=FOLDER_ID, file="Docs/plan.odt", version_time="2026-11-01T10:00:00+01:00")))
assert "confirm=true" in unconfirmed["error"]
assert not post.called
ok = json.loads(await syncthing_restore_version(RestoreVersionInput(
folder_id=FOLDER_ID, file="Docs/plan.odt", version_time="2026-11-01T10:00:00+01:00", confirm=True)))
assert ok["status"] == "restored"
assert json.loads(post.calls.last.request.content) == {"Docs/plan.odt": "2026-11-01T10:00:00+01:00"}
async def test_restore_reports_syncthing_errors(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.maintenance import syncthing_restore_version
mock_api.get("/rest/folder/versions").respond(json=VERSIONS)
mock_api.post("/rest/folder/versions").respond(json={"other.txt": "permission denied"})
result = json.loads(await syncthing_restore_version(RestoreVersionInput(
folder_id=FOLDER_ID, file="other.txt", version_time="2026-10-01T00:00:00Z", confirm=True)))
assert result["details"] == {"other.txt": "permission denied"}
async def test_versioning_disabled_is_a_tool_error(self, mock_api):
from syncthing_mcp.tools.maintenance import syncthing_list_versions
mock_api.get("/rest/folder/versions").respond(status_code=500, text="no versioner configured")
with pytest.raises(ToolError, match="500"):
await syncthing_list_versions(ListVersionsInput(folder_id=FOLDER_ID))
class TestFolderStats:
async def test_stats_with_labels(self, mock_api):
from syncthing_mcp.tools.maintenance import syncthing_folder_stats
mock_api.get("/rest/stats/folder").respond(json={FOLDER_ID: {
"lastScan": "2026-11-23T10:00:00Z",
"lastFile": {"at": "2026-11-23T09:00:00Z", "filename": "a.txt", "deleted": False},
}})
mock_api.get("/rest/config/folders").respond(json=[{"id": FOLDER_ID, "label": "Docs"}])
result = json.loads(await syncthing_folder_stats(FolderStatsInput()))
assert result["folders"][0]["label"] == "Docs"
assert result["folders"][0]["last_file"] == "a.txt"
with pytest.raises(ToolError):
await syncthing_folder_stats(FolderStatsInput(folder_id="missing"))
DEVICES = [
{"deviceID": DEVICE_ID_LOCAL, "name": "server"},
{"deviceID": DEVICE_ID_REMOTE, "name": "laptop"},
]
class TestDeviceManagement:
async def test_add_device_validates_and_confirms(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.devices import syncthing_add_device
mock_api.get("/rest/config/devices").respond(json=DEVICES)
mock_api.get("/rest/config/defaults/device").respond(json={"addresses": ["dynamic"], "paused": False})
post = mock_api.post("/rest/config/devices").respond(status_code=200, content=b"")
with pytest.raises(ToolError, match="Invalid device ID"):
await syncthing_add_device(AddDeviceInput(device_id="nope", name="x", confirm=True))
dup = json.loads(await syncthing_add_device(AddDeviceInput(device_id=DEVICE_ID_REMOTE, name="x", confirm=True)))
assert "already configured" in dup["error"]
ask = json.loads(await syncthing_add_device(AddDeviceInput(device_id=NEW_DEVICE.lower(), name="Phone")))
assert "confirm=true" in ask["error"]
assert not post.called
ok = json.loads(await syncthing_add_device(AddDeviceInput(
device_id=NEW_DEVICE.replace("-", ""), name="Phone", confirm=True)))
assert ok["status"] == "added"
assert json.loads(post.calls.last.request.content)["deviceID"] == NEW_DEVICE
async def test_share_folder(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.devices import syncthing_share_folder
mock_api.get("/rest/config/devices").respond(json=DEVICES)
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={
"id": FOLDER_ID, "label": "Docs", "type": "sendreceive", "devices": [{"deviceID": DEVICE_ID_LOCAL}],
})
patch = mock_api.patch(f"/rest/config/folders/{FOLDER_ID}").respond(status_code=200, content=b"")
ask = json.loads(await syncthing_share_folder(ShareFolderInput(folder_id=FOLDER_ID, device_id=DEVICE_ID_REMOTE)))
assert "confirm=true" in ask["error"]
ok = json.loads(await syncthing_share_folder(ShareFolderInput(
folder_id=FOLDER_ID, device_id=DEVICE_ID_REMOTE, confirm=True)))
assert ok["status"] == "shared"
assert json.loads(patch.calls.last.request.content) == {
"devices": [{"deviceID": DEVICE_ID_LOCAL}, {"deviceID": DEVICE_ID_REMOTE}]
}
async def test_share_folder_unknown_device(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.devices import syncthing_share_folder
mock_api.get("/rest/config/devices").respond(json=DEVICES)
with pytest.raises(ToolError, match="not configured"):
await syncthing_share_folder(ShareFolderInput(folder_id=FOLDER_ID, device_id=NEW_DEVICE, confirm=True))
async def test_pause_device(self, mock_api, write_enabled_env):
from syncthing_mcp.tools.devices import syncthing_set_device_paused
mock_api.get("/rest/config/devices").respond(json=DEVICES)
patch = mock_api.patch(f"/rest/config/devices/{DEVICE_ID_REMOTE}").respond(status_code=200, content=b"")
result = json.loads(await syncthing_set_device_paused(SetDevicePausedInput(device_id=DEVICE_ID_REMOTE, paused=True)))
assert result == {"status": "paused", "device": "laptop", "instance": "default"}
assert json.loads(patch.calls.last.request.content) == {"paused": True}
@pytest.mark.parametrize("tool_name, params", [
("syncthing_add_device", AddDeviceInput(device_id=NEW_DEVICE, name="x", confirm=True)),
("syncthing_share_folder", ShareFolderInput(folder_id=FOLDER_ID, device_id=DEVICE_ID_REMOTE, confirm=True)),
("syncthing_set_device_paused", SetDevicePausedInput(device_id=DEVICE_ID_REMOTE, paused=True)),
])
async def test_write_gate(self, mock_api, tool_name, params):
from syncthing_mcp.tools import devices
result = json.loads(await getattr(devices, tool_name)(params))
assert "SYNCTHING_WRITE_ENABLED" in result["error"]
class TestJsonSafeTruncate:
def test_large_json_stays_valid(self):
text = json.dumps({"folder": "x", "entries": [{"name": f"file-{i}", "size": i} for i in range(5000)]})
out = truncate(text, limit=2000)
data = json.loads(out)
assert len(out) <= 2000
assert data["folder"] == "x"
assert data["truncated"]["items_removed"] > 0
def test_top_level_list_is_wrapped(self):
out = truncate(json.dumps(list(range(10000))), limit=500)
data = json.loads(out)
assert isinstance(data["items"], list)
assert "truncated" in data
+1
View File
@@ -112,6 +112,7 @@ class TestGatedOnProceeds:
assert result["status"] == "restart_initiated"
async def test_override_with_confirm(self, mock_api, write_enabled_env):
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(json={"id": FOLDER_ID, "type": "sendonly"})
mock_api.post("/rest/db/override").respond(status_code=200, content=b"")
result = json.loads(await syncthing_override_folder(
ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True)
Generated
+3 -3
View File
@@ -1,5 +1,5 @@
version = 1
revision = 3
revision = 5
requires-python = ">=3.11"
[[package]]
@@ -837,7 +837,7 @@ wheels = [
[[package]]
name = "syncthing-blade-mcp"
version = "0.9.0"
version = "0.10.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },
@@ -859,7 +859,7 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "mcp", extras = ["cli"], specifier = ">=1.0.0" },
{ name = "mcp", extras = ["cli"], specifier = ">=1.0.0,<2.0" },
{ name = "pydantic", specifier = ">=2.0.0" },
{ name = "pyyaml", specifier = ">=6.0" },
{ name = "stallari-mcp-helpers", specifier = ">=0.1.0,<1.0.0" },