Refactor into package, add 6 new tools, add 96 tests

Split the monolithic syncthing_mcp.py into a proper src/syncthing_mcp/
package with focused modules: client, models, registry, server, and
tool submodules (system, folders, devices, config, instances).

New tools: browse_folder, file_info, folder_need (file-level queries),
override_folder, revert_folder (conflict resolution), check_upgrade
(system management). Bumps tool count from 30 to 36.

Adds comprehensive test suite (96 tests) using pytest + respx for
HTTP mocking, covering client methods, registry logic, model validation,
and all tool functions.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Piers Dawson-DamerandClaude Opus 4.6 committed 2026-02-15 10:13:37 +11:00
1 parent 5b54c09cd5
commit 3a33d34bd1
26 files changed
+3398 -1897

No files matched your search

+2
View File
@@ -4,3 +4,5 @@ __pycache__/
*.egg-info/
dist/
.DS_Store
*.old
.pytest_cache/
+49 -14
View File
@@ -10,7 +10,7 @@ Syncthing syncs folders across devices, but its web UI doesn't make it easy to a
This MCP server exposes that information as structured tool calls, so you can ask an AI assistant to audit your replication status and guide you through safe cleanup.
## Tools
## Tools (36 total)
### Instance Management
@@ -31,6 +31,7 @@ This MCP server exposes that information as structured tool calls, so you can as
| `syncthing_system_log` | Recent log entries with timestamps and levels | No |
| `syncthing_recent_changes` | Recent file change events (local + remote) | No |
| `syncthing_health_summary` | Single-call health overview: status, alerts, folder/device/pending counts | No |
| `syncthing_check_upgrade` | Check if a newer version of Syncthing is available | No |
### Folder Status & Replication
@@ -55,6 +56,21 @@ This MCP server exposes that information as structured tool calls, so you can as
| `syncthing_pause_folder` | Pause a folder (prevents deletion propagation) | Yes |
| `syncthing_resume_folder` | Resume a paused folder | Yes |
### File-Level Queries
| Tool | Description | Mutating |
|------|-------------|----------|
| `syncthing_browse_folder` | Browse folder contents at a path prefix (directory listing from Syncthing's DB) | No |
| `syncthing_file_info` | Detailed info about a specific file (versions, availability, conflicts) | No |
| `syncthing_folder_need` | List out-of-sync files a folder still needs (with pagination) | No |
### Conflict Resolution
| Tool | Description | Mutating |
|------|-------------|----------|
| `syncthing_override_folder` | Override remote changes on a send-only folder (make local authoritative) | Yes |
| `syncthing_revert_folder` | Revert local changes on a receive-only folder (pull remote state) | Yes |
### Config Mutation: Pending Devices & Folders
| Tool | Description | Mutating |
@@ -77,6 +93,28 @@ This MCP server exposes that information as structured tool calls, so you can as
| `syncthing_get_default_ignores` | Get default ignore patterns for new folders | No |
| `syncthing_set_default_ignores` | Set default ignore patterns for new folders | Yes |
## Project Structure
```
syncthing-mcp/
├── src/syncthing_mcp/
│ ├── __init__.py # Package version
│ ├── __main__.py # Entry point
│ ├── client.py # SyncthingClient (HTTP methods + error handling)
│ ├── models.py # Pydantic input models
│ ├── registry.py # Multi-instance registry from env vars
│ ├── server.py # FastMCP server + lifespan
│ └── tools/
│ ├── system.py # System status, health, errors, log, restart, upgrade
│ ├── folders.py # Folder status, completion, replication, operations, file queries
│ ├── devices.py # Device completion, connections
│ ├── config.py # Pending accept/reject, ignore patterns
│ └── instances.py # Instance listing, folder listing
├── tests/ # 96 tests with respx HTTP mocking
├── pyproject.toml
└── README.md
```
## Multi-Instance Support
Connect to multiple Syncthing nodes simultaneously by setting the `SYNCTHING_INSTANCES` environment variable with a JSON object:
@@ -100,7 +138,7 @@ Every tool accepts an optional `instance` parameter to target a specific node. W
"command": "uv",
"args": [
"--directory", "/path/to/syncthing-mcp",
"run", "syncthing_mcp.py"
"run", "python", "-m", "syncthing_mcp"
],
"env": {
"SYNCTHING_INSTANCES": "{\"mini\":{\"url\":\"http://mini.local:8384\",\"api_key\":\"abc123\"},\"tn-sb\":{\"url\":\"http://tn-sb.local:8384\",\"api_key\":\"def456\"}}"
@@ -155,7 +193,7 @@ Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/cla
"command": "uv",
"args": [
"--directory", "/path/to/syncthing-mcp",
"run", "syncthing_mcp.py"
"run", "python", "-m", "syncthing_mcp"
],
"env": {
"SYNCTHING_API_KEY": "your-api-key-here",
@@ -166,6 +204,13 @@ Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/cla
}
```
### Running Tests
```bash
uv sync
uv run pytest -v
```
### Environment Variables
| Variable | Required | Default | Description |
@@ -176,16 +221,6 @@ Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/cla
\* Required unless `SYNCTHING_INSTANCES` is set.
## Roadmap
Planned directions include:
- **Event stream integration** — subscribe to Syncthing's `/rest/events` endpoint for real-time sync status and conflict detection
- **Historical tracking** — persist folder size and completion data over time to surface trends
- **Conflict management** — surface and resolve sync conflicts through tool calls
- **Folder lifecycle tools** — add/remove folders and device sharing relationships programmatically
- **Dashboard artifact** — a standalone HTML/React view that visualises replication topology across all nodes
## Performance Notes
- `syncthing_folder_status` and `syncthing_replication_report` call Syncthing's `/rest/db/status` endpoint, which the Syncthing docs describe as "an expensive call, increasing CPU and RAM usage on the device." Use judiciously on low-power hardware.
@@ -194,7 +229,7 @@ Planned directions include:
## Contributing
Issues and PRs welcome. This is an early-stage project — the API surface may change as the roadmap develops.
Issues and PRs welcome.
## License
+3 -2
View File
@@ -12,11 +12,12 @@ rsync -a --delete \
--exclude '__pycache__' \
--exclude '*.pyc' \
--exclude '.DS_Store' \
--exclude 'tests' \
. "$DEST/"
# Install/update deps in the runtime location
cd "$DEST"
uv sync --quiet
echo "✅ Deployed $SERVER_NAME to $DEST"
echo " Restart Claude Desktop to pick up changes."
echo "Deployed $SERVER_NAME to $DEST"
echo " Restart Claude Desktop to pick up changes."
+19 -2
View File
@@ -1,7 +1,7 @@
[project]
name = "syncthing-mcp"
version = "0.1.0"
description = "MCP server for Syncthing — query folder replication status and identify datasets safe to remove locally."
version = "0.2.0"
description = "MCP server for Syncthing — query folder replication status, manage configuration, and identify datasets safe to remove locally."
requires-python = ">=3.11"
dependencies = [
"mcp[cli]>=1.0.0",
@@ -9,6 +9,23 @@ dependencies = [
"pydantic>=2.0.0",
]
[project.scripts]
syncthing-mcp = "syncthing_mcp.__main__:main"
[dependency-groups]
dev = [
"pytest>=8.0",
"pytest-asyncio>=0.24",
"respx>=0.22",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/syncthing_mcp"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
+3
View File
@@ -0,0 +1,3 @@
"""Syncthing MCP Server — manage Syncthing instances via MCP tools."""
__version__ = "0.2.0"
+11
View File
@@ -0,0 +1,11 @@
"""Entry point for `python -m syncthing_mcp` and the `syncthing-mcp` console script."""
from syncthing_mcp.server import mcp
def main() -> None:
mcp.run()
if __name__ == "__main__":
main()
+106
View File
@@ -0,0 +1,106 @@
"""HTTP client for a single Syncthing instance."""
from typing import Any
import httpx
class SyncthingClient:
"""HTTP client for a single Syncthing instance."""
def __init__(self, name: str, url: str, api_key: str) -> None:
self.name = name
self.url = url.rstrip("/")
self.api_key = api_key
def _headers(self) -> dict[str, str]:
return {
"X-API-Key": self.api_key,
"Accept": "application/json",
}
async def _get(self, path: str, params: dict | None = None) -> Any:
"""Authenticated GET against this instance."""
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.get(
f"{self.url}{path}",
headers=self._headers(),
params=params,
)
resp.raise_for_status()
return resp.json()
async def _post(self, path: str, params: dict | None = None, body: Any = None) -> Any:
"""Authenticated POST against this instance."""
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(
f"{self.url}{path}",
headers=self._headers(),
params=params,
json=body,
)
resp.raise_for_status()
ct = resp.headers.get("content-type", "")
if ct.startswith("application/json") and resp.content:
return resp.json()
return {"status": "ok"}
async def _patch(self, path: str, body: Any = None) -> Any:
"""Authenticated PATCH against this instance."""
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.patch(
f"{self.url}{path}",
headers=self._headers(),
json=body,
)
resp.raise_for_status()
ct = resp.headers.get("content-type", "")
if ct.startswith("application/json") and resp.content:
return resp.json()
return {"status": "ok"}
async def _put(self, path: str, body: Any = None) -> Any:
"""Authenticated PUT against this instance."""
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.put(
f"{self.url}{path}",
headers=self._headers(),
json=body,
)
resp.raise_for_status()
ct = resp.headers.get("content-type", "")
if ct.startswith("application/json") and resp.content:
return resp.json()
return {"status": "ok"}
async def _delete(self, path: str, params: dict | None = None) -> Any:
"""Authenticated DELETE against this instance."""
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.delete(
f"{self.url}{path}",
headers=self._headers(),
params=params,
)
resp.raise_for_status()
ct = resp.headers.get("content-type", "")
if ct.startswith("application/json") and resp.content:
return resp.json()
return {"status": "ok"}
def handle_error(self, e: Exception) -> str:
"""Consistent error formatting referencing this instance."""
prefix = f"[{self.name}] " if self.name != "default" else ""
if isinstance(e, httpx.HTTPStatusError):
status = e.response.status_code
if status == 401:
return f"{prefix}Error 401: Unauthorized. Check API key for instance '{self.name}'."
if status == 403:
return f"{prefix}Error 403: Forbidden. API key may lack permissions."
if status == 404:
return f"{prefix}Error 404: Not found. Check the folder/device ID. Detail: {e.response.text}"
return f"{prefix}Error {status}: {e.response.text}"
if isinstance(e, httpx.ConnectError):
return f"{prefix}Error: Cannot connect to Syncthing at {self.url}. Is it running?"
if isinstance(e, httpx.TimeoutException):
return f"{prefix}Error: Request timed out. Syncthing may be busy or unreachable."
return f"{prefix}Error: {type(e).__name__}: {e}"
+133
View File
@@ -0,0 +1,133 @@
"""Pydantic input models for Syncthing MCP tools."""
from pydantic import BaseModel, ConfigDict, Field
class EmptyInput(BaseModel):
model_config = ConfigDict(extra="forbid")
instance: str | None = Field(
None, description="Instance name. Omit if only one instance is configured."
)
class FolderInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Syncthing folder ID (e.g. 'abcd-1234')", min_length=1
)
instance: str | None = Field(None, description="Instance name")
class DeviceInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(
...,
description="Syncthing device ID (long alphanumeric string with dashes)",
min_length=1,
)
instance: str | None = Field(None, description="Instance name")
class FolderDeviceInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
device_id: str = Field(..., description="Syncthing device ID", min_length=1)
instance: str | None = Field(None, description="Instance name")
class PauseFolderInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Syncthing folder ID to pause/resume", min_length=1
)
instance: str | None = Field(None, description="Instance name")
class AcceptDeviceInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(
..., description="Device ID to accept (from pending list)", min_length=1
)
name: str | None = Field(
None,
description="Friendly name to assign. If omitted, uses the name from the pending request.",
)
instance: str | None = Field(None, description="Instance name")
class AcceptFolderInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Folder ID to accept (from pending list)", min_length=1
)
path: str | None = Field(
None,
description="Local path for the folder. If omitted, uses Syncthing's default path.",
)
instance: str | None = Field(None, description="Instance name")
class RejectFolderInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Folder ID to reject", min_length=1
)
device_id: str | None = Field(
None,
description="Device ID that offered the folder. If omitted, rejects from all devices.",
)
instance: str | None = Field(None, description="Instance name")
class SetIgnoresInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Folder ID", min_length=1)
patterns: list[str] = Field(
...,
description="List of ignore patterns (e.g. ['*.tmp', '.DS_Store', '// #include'])",
)
instance: str | None = Field(None, description="Instance name")
class SetDefaultIgnoresInput(BaseModel):
model_config = ConfigDict(extra="forbid")
lines: list[str] = Field(
...,
description="Default ignore patterns for new folders (e.g. ['.DS_Store', 'Thumbs.db'])",
)
instance: str | None = Field(None, description="Instance name")
# --- New models for added tools ---
class BrowseFolderInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
prefix: str | None = Field(
None,
description="Path prefix to browse (e.g. 'Documents/reports'). Omit for root.",
)
levels: int | None = Field(
None,
description="How many directory levels deep to return (default: 1).",
ge=0,
)
instance: str | None = Field(None, description="Instance name")
class FileInfoInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
file_path: str = Field(
..., description="Relative path of the file within the folder", min_length=1
)
instance: str | None = Field(None, description="Instance name")
class FolderNeedInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
page: int = Field(1, description="Page number (1-based)", ge=1)
per_page: int = Field(50, description="Items per page", ge=1, le=500)
instance: str | None = Field(None, description="Instance name")
+85
View File
@@ -0,0 +1,85 @@
"""Instance registry — load Syncthing instances from environment variables."""
import json
import os
from syncthing_mcp.client import SyncthingClient
def format_bytes(n: int) -> str:
"""Human-readable byte size."""
for unit in ("B", "KB", "MB", "GB", "TB"):
if abs(n) < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
def load_instances() -> dict[str, SyncthingClient]:
"""Build instance registry from environment variables.
Supports two modes:
- Multi-instance via SYNCTHING_INSTANCES (JSON object)
- Single-instance via SYNCTHING_API_KEY + SYNCTHING_URL
"""
instances_json = os.environ.get("SYNCTHING_INSTANCES", "").strip()
if instances_json:
try:
cfg = json.loads(instances_json)
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid SYNCTHING_INSTANCES JSON: {exc}") from exc
if not isinstance(cfg, dict) or not cfg:
raise ValueError("SYNCTHING_INSTANCES must be a non-empty JSON object.")
instances: dict[str, SyncthingClient] = {}
for name, entry in cfg.items():
if not isinstance(entry, dict):
raise ValueError(f"Instance '{name}' config must be a JSON object.")
url = entry.get("url", "http://localhost:8384")
api_key = entry.get("api_key", "")
instances[name] = SyncthingClient(name, url, api_key)
return instances
# Backward-compatible single-instance fallback
url = os.environ.get("SYNCTHING_URL", "http://localhost:8384")
api_key = os.environ.get("SYNCTHING_API_KEY", "")
return {"default": SyncthingClient("default", url, api_key)}
# Module-level registry, initialised at import time.
_instances: dict[str, SyncthingClient] = load_instances()
def get_instance(instance: str | None = None) -> SyncthingClient:
"""Resolve an instance by name, or auto-select when there is only one."""
if instance is None:
if len(_instances) == 1:
return next(iter(_instances.values()))
names = list(_instances.keys())
raise ValueError(
f"Multiple instances configured ({names}). "
"Specify 'instance' parameter to choose one."
)
if instance not in _instances:
raise ValueError(
f"Instance '{instance}' not found. Available: {list(_instances.keys())}"
)
return _instances[instance]
def get_all_instances() -> dict[str, SyncthingClient]:
"""Return the full instance registry."""
return _instances
def handle_error_global(e: Exception) -> str:
"""Fallback error handler when instance cannot be determined."""
if isinstance(e, ValueError):
return f"Error: {e}"
return f"Error: {type(e).__name__}: {e}"
def reload_instances() -> None:
"""Re-read environment and rebuild the instance registry (for testing)."""
global _instances
_instances = load_instances()
+29
View File
@@ -0,0 +1,29 @@
"""FastMCP server creation and lifespan."""
from contextlib import asynccontextmanager
from mcp.server.fastmcp import FastMCP
from syncthing_mcp.registry import get_all_instances
@asynccontextmanager
async def app_lifespan(app):
import sys
instances = get_all_instances()
missing = [n for n, c in instances.items() if not c.api_key]
if missing:
print(f"WARNING: API key missing for instance(s): {missing}", file=sys.stderr)
print(
f"Syncthing MCP: {len(instances)} instance(s) configured — "
f"{list(instances.keys())}",
file=sys.stderr,
)
yield {}
mcp = FastMCP("syncthing_mcp", lifespan=app_lifespan)
# Import all tool modules so they register with `mcp` via decorators.
import syncthing_mcp.tools # noqa: E402, F401
+7
View File
@@ -0,0 +1,7 @@
"""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
+426
View File
@@ -0,0 +1,426 @@
"""Config mutation tools: pending devices/folders, ignores, accept/reject."""
import json
from syncthing_mcp.models import (
AcceptDeviceInput,
AcceptFolderInput,
DeviceInput,
EmptyInput,
FolderInput,
RejectFolderInput,
SetDefaultIgnoresInput,
SetIgnoresInput,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
# =====================================================================
# Pending Devices & Folders
# =====================================================================
@mcp.tool(
name="syncthing_pending_devices",
annotations={
"title": "List Pending Device Requests",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_pending_devices(params: EmptyInput) -> str:
"""List remote devices that have tried to connect but are not yet configured.
Returns:
str: JSON object keyed by device ID, each with name, address, and time.
"""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices")
return json.dumps(
{"instance": client.name, "pendingDevices": pending},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_pending_folders",
annotations={
"title": "List Pending Folder Offers",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_pending_folders(params: EmptyInput) -> str:
"""List folders that remote devices have offered to share but are not yet accepted.
Returns:
str: JSON object keyed by folder ID, each listing offering devices with labels.
"""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/folders")
return json.dumps(
{"instance": client.name, "pendingFolders": pending},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_accept_device",
annotations={
"title": "Accept Pending Device",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": False,
"openWorldHint": False,
},
)
async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
"""Accept a pending device by adding it to the Syncthing configuration.
The device will be added with 'dynamic' addressing. You can optionally
provide a friendly name.
Args:
params: AcceptDeviceInput with device_id and optional name.
Returns:
str: Confirmation message with the device details.
"""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices")
pending_info = pending.get(params.device_id, {})
name = params.name
if not name:
name = pending_info.get("name", params.device_id[:8])
defaults = await client._get("/rest/config/defaults/device")
new_device = defaults.copy()
new_device["deviceID"] = params.device_id
new_device["name"] = name
await client._post("/rest/config/devices", body=new_device)
return json.dumps(
{
"status": "accepted",
"deviceID": params.device_id,
"name": name,
"instance": client.name,
"message": f"Device '{name}' ({params.device_id[:8]}...) has been added.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_reject_device",
annotations={
"title": "Reject Pending Device",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_reject_device(params: DeviceInput) -> str:
"""Dismiss a pending device connection request.
This only clears the pending notification. The device can try again later;
for permanent blocking, use Syncthing's ignore-device feature via the web UI.
Args:
params: DeviceInput with device_id.
Returns:
str: Confirmation message.
"""
try:
client = get_instance(params.instance)
await client._delete(
"/rest/cluster/pending/devices",
params={"device": params.device_id},
)
return json.dumps(
{
"status": "rejected",
"deviceID": params.device_id,
"instance": client.name,
"message": f"Pending device '{params.device_id[:8]}...' has been dismissed.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_accept_folder",
annotations={
"title": "Accept Pending Folder Offer",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": False,
"openWorldHint": False,
},
)
async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
"""Accept a pending folder share offer by adding it to the configuration.
Uses the default folder configuration as a template. If no path is provided,
Syncthing's default folder path is used.
Args:
params: AcceptFolderInput with folder_id and optional path.
Returns:
str: Confirmation with assigned path and sharing details.
"""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/folders")
folder_pending = pending.get(params.folder_id, {})
if not folder_pending:
return json.dumps(
{"error": f"Folder '{params.folder_id}' not found in pending offers."}
)
offering_devices = list(folder_pending.get("offeredBy", {}).keys())
first_offer = next(iter(folder_pending.get("offeredBy", {}).values()), {})
label = first_offer.get("label", params.folder_id)
status = await client._get("/rest/system/status")
my_id = status.get("myID", "")
defaults = await client._get("/rest/config/defaults/folder")
new_folder = defaults.copy()
new_folder["id"] = params.folder_id
new_folder["label"] = label
if params.path:
new_folder["path"] = params.path
device_list = [{"deviceID": my_id}]
for did in offering_devices:
device_list.append({"deviceID": did})
new_folder["devices"] = device_list
await client._post("/rest/config/folders", body=new_folder)
return json.dumps(
{
"status": "accepted",
"folderID": params.folder_id,
"label": label,
"path": new_folder.get("path", "(default)"),
"sharedWith": offering_devices,
"instance": client.name,
"message": (
f"Folder '{label}' ({params.folder_id}) has been added "
f"at '{new_folder.get('path', '(default)')}'."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_reject_folder",
annotations={
"title": "Reject Pending Folder Offer",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_reject_folder(params: RejectFolderInput) -> str:
"""Dismiss a pending folder share offer.
Args:
params: RejectFolderInput with folder_id and optional device_id.
If device_id is omitted, rejects the offer from all devices.
Returns:
str: Confirmation message.
"""
try:
client = get_instance(params.instance)
delete_params: dict[str, str] = {"folder": params.folder_id}
if params.device_id:
delete_params["device"] = params.device_id
await client._delete("/rest/cluster/pending/folders", params=delete_params)
return json.dumps(
{
"status": "rejected",
"folderID": params.folder_id,
"deviceID": params.device_id or "(all)",
"instance": client.name,
"message": f"Pending folder offer for '{params.folder_id}' has been dismissed.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
# =====================================================================
# Ignore Patterns
# =====================================================================
@mcp.tool(
name="syncthing_get_ignores",
annotations={
"title": "Get Folder Ignore Patterns",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_get_ignores(params: FolderInput) -> str:
"""Get the current .stignore patterns for a folder.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with ignore patterns list and whether the folder has expanded patterns.
"""
try:
client = get_instance(params.instance)
result = await client._get(
"/rest/db/ignores", params={"folder": params.folder_id}
)
return json.dumps(
{
"folder": params.folder_id,
"instance": client.name,
"patterns": result.get("ignore", []) or [],
"expanded": result.get("expanded", []) or [],
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_set_ignores",
annotations={
"title": "Set Folder Ignore Patterns",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
"""Set the .stignore patterns for a folder. Replaces all existing patterns.
Common patterns: '*.tmp', '.DS_Store', 'Thumbs.db', '(?d).Trash*',
'// #include common-ignores' (to include shared pattern files).
Args:
params: SetIgnoresInput with folder_id and patterns list.
Returns:
str: Confirmation with the applied patterns.
"""
try:
client = get_instance(params.instance)
await client._post(
"/rest/db/ignores",
params={"folder": params.folder_id},
body={"ignore": params.patterns},
)
return json.dumps(
{
"status": "updated",
"folder": params.folder_id,
"instance": client.name,
"patternCount": len(params.patterns),
"patterns": params.patterns,
"message": f"Ignore patterns for '{params.folder_id}' have been updated.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_get_default_ignores",
annotations={
"title": "Get Default Ignore Patterns",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_get_default_ignores(params: EmptyInput) -> str:
"""Get the default ignore patterns applied to newly created folders.
Returns:
str: JSON with default ignore pattern lines.
"""
try:
client = get_instance(params.instance)
result = await client._get("/rest/config/defaults/ignores")
return json.dumps(
{
"instance": client.name,
"lines": result.get("lines", []) or [],
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_set_default_ignores",
annotations={
"title": "Set Default Ignore Patterns",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_set_default_ignores(params: SetDefaultIgnoresInput) -> str:
"""Set the default ignore patterns for newly created folders.
These patterns will be automatically applied when new folders are added.
Args:
params: SetDefaultIgnoresInput with lines list.
Returns:
str: Confirmation with the applied patterns.
"""
try:
client = get_instance(params.instance)
await client._put(
"/rest/config/defaults/ignores",
body={"lines": params.lines},
)
return json.dumps(
{
"status": "updated",
"instance": client.name,
"lineCount": len(params.lines),
"lines": params.lines,
"message": "Default ignore patterns have been updated for new folders.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
+142
View File
@@ -0,0 +1,142 @@
"""Device completion and connection tools."""
import json
from syncthing_mcp.models import DeviceInput, EmptyInput
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp
@mcp.tool(
name="syncthing_list_devices",
annotations={
"title": "List All Devices",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_list_devices(params: EmptyInput) -> str:
"""List all configured devices with their names, connection status, and last seen time.
Returns:
str: JSON array of devices with deviceID, name, connected, paused, address, lastSeen.
"""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
connections = await client._get("/rest/system/connections")
stats = await client._get("/rest/stats/device")
conn_data = connections.get("connections", {})
result = []
for dev in config.get("devices", []):
did = dev["deviceID"]
conn = conn_data.get(did, {})
stat = stats.get(did, {})
result.append(
{
"deviceID": did,
"name": dev.get("name", did[:8]),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"lastSeen": stat.get("lastSeen", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
}
)
return json.dumps(result, indent=2)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_device_completion",
annotations={
"title": "Device Completion (All Folders)",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_device_completion(params: DeviceInput) -> str:
"""Get the aggregated sync completion for a specific remote device across all shared folders.
Args:
params: DeviceInput with device_id.
Returns:
str: JSON with overall completion %, globalBytes, needBytes for that device.
"""
try:
client = get_instance(params.instance)
comp = await client._get(
"/rest/db/completion", params={"device": params.device_id}
)
return json.dumps(
{
"deviceID": params.device_id,
"instance": client.name,
"completion": round(comp.get("completion", 0), 2),
"globalBytes": comp.get("globalBytes", 0),
"globalSize": format_bytes(comp.get("globalBytes", 0)),
"needBytes": comp.get("needBytes", 0),
"needSize": format_bytes(comp.get("needBytes", 0)),
"needItems": comp.get("needItems", 0),
"remoteState": comp.get("remoteState", "unknown"),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_connections",
annotations={
"title": "Active Connections",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_connections(params: EmptyInput) -> str:
"""Get current connection details for all devices.
Returns:
str: JSON with per-device connection info including address,
bytes transferred, crypto, and connection type.
"""
try:
client = get_instance(params.instance)
connections = await client._get("/rest/system/connections")
config = await client._get("/rest/config")
devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", [])
}
result = []
for did, conn in connections.get("connections", {}).items():
result.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
"crypto": conn.get("crypto", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
}
)
return json.dumps(result, indent=2)
except Exception as e:
return handle_error_global(e)
+724
View File
@@ -0,0 +1,724 @@
"""Folder status, completion, replication, operations, and file-level query tools."""
import json
from typing import Any
from syncthing_mcp.models import (
BrowseFolderInput,
FileInfoInput,
FolderInput,
FolderNeedInput,
PauseFolderInput,
EmptyInput,
)
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp
# =====================================================================
# Folder Status & Replication
# =====================================================================
@mcp.tool(
name="syncthing_folder_status",
annotations={
"title": "Folder Status",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_folder_status(params: FolderInput) -> str:
"""Get detailed status for a specific folder — local/global file counts, bytes, sync state.
Note: This is an expensive call on the Syncthing side. Use sparingly.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with globalBytes, globalFiles, localBytes, localFiles, needBytes,
needFiles, state, stateChanged, and human-readable size strings.
"""
try:
client = get_instance(params.instance)
status = await client._get("/rest/db/status", params={"folder": params.folder_id})
stats = await client._get("/rest/stats/folder")
folder_stats = stats.get(params.folder_id, {})
return json.dumps(
{
"folder": params.folder_id,
"instance": client.name,
"state": status.get("state"),
"stateChanged": status.get("stateChanged"),
"globalFiles": status.get("globalFiles"),
"globalBytes": status.get("globalBytes"),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"localFiles": status.get("localFiles"),
"localBytes": status.get("localBytes"),
"localSize": format_bytes(status.get("localBytes", 0)),
"needFiles": status.get("needFiles"),
"needBytes": status.get("needBytes"),
"needSize": format_bytes(status.get("needBytes", 0)),
"inSyncFiles": status.get("inSyncFiles"),
"inSyncBytes": status.get("inSyncBytes"),
"globalDeleted": status.get("globalDeleted"),
"localDeleted": status.get("localDeleted"),
"ignorePatterns": status.get("ignorePatterns"),
"lastScan": folder_stats.get("lastScan", ""),
"lastFile": folder_stats.get("lastFile", {}),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_folder_completion",
annotations={
"title": "Folder Completion by Device",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_folder_completion(params: FolderInput) -> str:
"""Get the replication completion percentage for a folder across ALL devices that share it.
This is the key tool for determining whether a folder is fully replicated
on remote devices before removing it locally.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with folder info and per-device completion percentages,
including whether each device is connected and has a valid remote state.
"""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
connections = await client._get("/rest/system/connections")
conn_data = connections.get("connections", {})
status = await client._get("/rest/system/status")
my_id = status.get("myID", "")
folder_cfg = None
for f in config.get("folders", []):
if f["id"] == params.folder_id:
folder_cfg = f
break
if not folder_cfg:
return json.dumps({"error": f"Folder '{params.folder_id}' not found in config."})
devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", [])
}
completions = []
for dev in folder_cfg.get("devices", []):
did = dev.get("deviceID", "")
if did == my_id:
continue
try:
comp = await client._get(
"/rest/db/completion",
params={"folder": params.folder_id, "device": did},
)
connected = conn_data.get(did, {}).get("connected", False)
completions.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": connected,
"completion": round(comp.get("completion", 0), 2),
"globalBytes": comp.get("globalBytes", 0),
"globalSize": format_bytes(comp.get("globalBytes", 0)),
"needBytes": comp.get("needBytes", 0),
"needSize": format_bytes(comp.get("needBytes", 0)),
"needItems": comp.get("needItems", 0),
"needDeletes": comp.get("needDeletes", 0),
"remoteState": comp.get("remoteState", "unknown"),
}
)
except Exception:
completions.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": False,
"completion": None,
"error": "Could not query completion for this device.",
}
)
fully_replicated_count = sum(
1
for c in completions
if c.get("completion") == 100 and c.get("remoteState") == "valid"
)
return json.dumps(
{
"folder": params.folder_id,
"label": folder_cfg.get("label", params.folder_id),
"instance": client.name,
"totalRemoteDevices": len(completions),
"fullyReplicatedOn": fully_replicated_count,
"devices": completions,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_replication_report",
annotations={
"title": "Replication Report — Safe to Remove?",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_replication_report(params: EmptyInput) -> str:
"""Generate a comprehensive replication report for ALL folders on this device.
For each folder, shows:
- Local disk usage (bytes and human-readable)
- Number of remote devices sharing it
- How many of those have a 100% complete, valid replica
- A 'safeToRemove' flag: True when at least one remote device has a full valid replica
- A 'reclaimableBytes' total for folders that are safe to remove
This is the primary tool for deciding which folders to remove to free local disk space.
Returns:
str: JSON with per-folder replication analysis and a summary section with
total reclaimable space.
"""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
connections = await client._get("/rest/system/connections")
conn_data = connections.get("connections", {})
status = await client._get("/rest/system/status")
my_id = status.get("myID", "")
devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", [])
}
folders = config.get("folders", [])
report = []
total_reclaimable = 0
for folder_cfg in folders:
fid = folder_cfg["id"]
label = folder_cfg.get("label", fid)
paused = folder_cfg.get("paused", False)
try:
fstatus = await client._get("/rest/db/status", params={"folder": fid})
except Exception:
report.append({"folder": fid, "label": label, "error": "Could not get folder status."})
continue
local_bytes = fstatus.get("localBytes", 0)
global_bytes = fstatus.get("globalBytes", 0)
state = fstatus.get("state", "unknown")
remote_devices = [
d for d in folder_cfg.get("devices", []) if d.get("deviceID") != my_id
]
device_completions = []
for dev in remote_devices:
did = dev.get("deviceID", "")
connected = conn_data.get(did, {}).get("connected", False)
try:
comp = await client._get(
"/rest/db/completion",
params={"folder": fid, "device": did},
)
device_completions.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": connected,
"completion": round(comp.get("completion", 0), 2),
"remoteState": comp.get("remoteState", "unknown"),
"needBytes": comp.get("needBytes", 0),
}
)
except Exception:
device_completions.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": connected,
"completion": None,
"remoteState": "unknown",
}
)
fully_replicated = [
d
for d in device_completions
if d.get("completion") == 100 and d.get("remoteState") == "valid"
]
safe = len(fully_replicated) >= 1 and state == "idle" and not paused
if safe:
total_reclaimable += local_bytes
report.append(
{
"folder": fid,
"label": label,
"path": folder_cfg.get("path", ""),
"type": folder_cfg.get("type", "sendreceive"),
"paused": paused,
"state": state,
"localBytes": local_bytes,
"localSize": format_bytes(local_bytes),
"globalBytes": global_bytes,
"globalSize": format_bytes(global_bytes),
"totalRemoteDevices": len(remote_devices),
"fullyReplicatedOn": len(fully_replicated),
"fullyReplicatedDevices": [d["deviceName"] for d in fully_replicated],
"safeToRemove": safe,
"devices": device_completions,
}
)
report.sort(key=lambda x: (-int(x.get("safeToRemove", False)), -x.get("localBytes", 0)))
return json.dumps(
{
"instance": client.name,
"summary": {
"totalFolders": len(report),
"safeToRemoveCount": sum(1 for r in report if r.get("safeToRemove")),
"totalReclaimableBytes": total_reclaimable,
"totalReclaimableSize": format_bytes(total_reclaimable),
},
"folders": report,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
# =====================================================================
# Folder Operations
# =====================================================================
@mcp.tool(
name="syncthing_pause_folder",
annotations={
"title": "Pause a Folder",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_pause_folder(params: PauseFolderInput) -> str:
"""Pause syncing for a specific folder. Useful before removing data locally.
This does NOT delete data — it only pauses sync activity so you can safely
remove the local copy without Syncthing propagating the deletion to other devices.
Args:
params: PauseFolderInput with folder_id.
Returns:
str: Confirmation message.
"""
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)
return json.dumps(
{
"status": "paused",
"folder": params.folder_id,
"instance": client.name,
"message": (
f"Folder '{params.folder_id}' is now paused. "
"Syncthing will NOT sync changes (including deletions) for this folder. "
"You can now safely remove the local data without affecting remote copies."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_resume_folder",
annotations={
"title": "Resume a Folder",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_resume_folder(params: PauseFolderInput) -> str:
"""Resume syncing for a previously paused folder.
WARNING: If you deleted local data while paused, resuming will cause Syncthing
to either re-download the data (receive-only/sendreceive) or propagate deletions
to other devices (sendreceive). Understand the folder type before resuming.
Args:
params: PauseFolderInput with folder_id.
Returns:
str: Confirmation message with warnings.
"""
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")
folder_cfg["paused"] = False
await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg)
return json.dumps(
{
"status": "resumed",
"folder": params.folder_id,
"folderType": folder_type,
"instance": client.name,
"message": f"Folder '{params.folder_id}' is now active again (type: {folder_type}).",
"warning": (
"If local data was deleted while paused, behaviour depends on folder type: "
"'sendreceive' may propagate deletions to peers; "
"'receiveonly' will re-download missing files."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_scan_folder",
annotations={
"title": "Trigger Folder Scan",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_scan_folder(params: FolderInput) -> str:
"""Request an immediate rescan of a folder to refresh its status.
Useful to ensure completion data is up to date before deciding to remove files.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that scan was requested.
"""
try:
client = get_instance(params.instance)
await client._post("/rest/db/scan", params={"folder": params.folder_id})
return json.dumps(
{
"status": "scan_requested",
"folder": params.folder_id,
"instance": client.name,
"message": "Scan initiated. Folder status will update shortly.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_folder_errors",
annotations={
"title": "Folder Errors",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_folder_errors(params: FolderInput) -> str:
"""Get current sync errors for a specific folder.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with error list and count.
"""
try:
client = get_instance(params.instance)
errors = await client._get(
"/rest/folder/errors", params={"folder": params.folder_id}
)
return json.dumps(
{
"folder": params.folder_id,
"instance": client.name,
"errorCount": len(errors.get("errors", []) or []),
"errors": errors.get("errors", []),
"page": errors.get("page", 1),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
# =====================================================================
# New: File-level queries
# =====================================================================
@mcp.tool(
name="syncthing_browse_folder",
annotations={
"title": "Browse Folder Contents",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
"""Browse the contents of a folder at a given path prefix.
Returns a directory-style listing of files and subdirectories known to
Syncthing's database — useful for inspecting what is being synced without
direct filesystem access.
Args:
params: BrowseFolderInput with folder_id, optional prefix and levels.
Returns:
str: JSON with the folder contents at the requested path.
"""
try:
client = get_instance(params.instance)
query: dict[str, str] = {"folder": params.folder_id}
if params.prefix:
query["prefix"] = params.prefix
if params.levels is not None:
query["levels"] = str(params.levels)
result = await client._get("/rest/db/browse", params=query)
return json.dumps(
{
"folder": params.folder_id,
"instance": client.name,
"prefix": params.prefix or "",
"entries": result,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_file_info",
annotations={
"title": "File Info",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_file_info(params: FileInfoInput) -> str:
"""Get detailed information about a specific file within a folder.
Returns version vectors, availability on devices, modification time,
size, and whether the file is locally present. Useful for diagnosing
sync conflicts or understanding file state across the cluster.
Args:
params: FileInfoInput with folder_id and file_path.
Returns:
str: JSON with file metadata including global and local info.
"""
try:
client = get_instance(params.instance)
result = await client._get(
"/rest/db/file",
params={"folder": params.folder_id, "file": params.file_path},
)
# Enrich with human-readable sizes
for key in ("global", "local"):
entry = result.get(key)
if isinstance(entry, dict) and "size" in entry:
entry["sizeFormatted"] = format_bytes(entry["size"])
return json.dumps(
{
"folder": params.folder_id,
"file": params.file_path,
"instance": client.name,
"availability": result.get("availability"),
"global": result.get("global"),
"local": result.get("local"),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_folder_need",
annotations={
"title": "Folder Need (Out-of-Sync Files)",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_folder_need(params: FolderNeedInput) -> str:
"""List files that the folder still needs — items that are out of sync locally.
Supports pagination for large result sets.
Args:
params: FolderNeedInput with folder_id, page, per_page.
Returns:
str: JSON with lists of files needed (progress, queued, rest) and a total page count.
"""
try:
client = get_instance(params.instance)
result = await client._get(
"/rest/db/need",
params={
"folder": params.folder_id,
"page": str(params.page),
"perpage": str(params.per_page),
},
)
return json.dumps(
{
"folder": params.folder_id,
"instance": client.name,
"page": result.get("page", params.page),
"perpage": result.get("perpage", params.per_page),
"progress": result.get("progress", []),
"queued": result.get("queued", []),
"rest": result.get("rest", []),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
# =====================================================================
# New: Conflict resolution
# =====================================================================
@mcp.tool(
name="syncthing_override_folder",
annotations={
"title": "Override Remote Changes (Send-Only)",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_override_folder(params: FolderInput) -> str:
"""Override remote changes on a send-only folder, making local state authoritative.
Use this when a send-only folder shows 'out of sync' items that you want
to push to remote devices. Only meaningful for folders configured as
'sendonly'.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that the override was requested.
"""
try:
client = get_instance(params.instance)
await client._post("/rest/db/override", params={"folder": params.folder_id})
return json.dumps(
{
"status": "override_requested",
"folder": params.folder_id,
"instance": client.name,
"message": (
f"Override requested for folder '{params.folder_id}'. "
"Local state will be pushed to remote devices."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_revert_folder",
annotations={
"title": "Revert Local Changes (Receive-Only)",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_revert_folder(params: FolderInput) -> str:
"""Revert local changes on a receive-only folder, pulling the remote state.
Use this when a receive-only folder has local modifications that should be
discarded in favour of the remote version.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that the revert was requested.
"""
try:
client = get_instance(params.instance)
await client._post("/rest/db/revert", params={"folder": params.folder_id})
return json.dumps(
{
"status": "revert_requested",
"folder": params.folder_id,
"instance": client.name,
"message": (
f"Revert requested for folder '{params.folder_id}'. "
"Local changes will be replaced by the remote state."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
+104
View File
@@ -0,0 +1,104 @@
"""Tools for instance management and listing folders (config-level)."""
import json
from typing import Any
from syncthing_mcp.models import EmptyInput
from syncthing_mcp.registry import (
format_bytes,
get_all_instances,
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp
@mcp.tool(
name="syncthing_list_instances",
annotations={
"title": "List Configured Instances",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_list_instances(params: EmptyInput) -> str:
"""List all configured Syncthing instances and probe their availability.
Returns:
str: JSON array with instance name, URL, availability, and device ID.
"""
results = []
for name, client in get_all_instances().items():
entry: dict[str, Any] = {"name": name, "url": client.url}
try:
status = await client._get("/rest/system/status")
version = await client._get("/rest/system/version")
config = await client._get("/rest/config")
my_id = status.get("myID", "")
my_name = my_id[:8]
for dev in config.get("devices", []):
if dev.get("deviceID") == my_id:
my_name = dev.get("name", my_id[:8])
break
entry.update(
{
"available": True,
"myID": my_id,
"deviceName": my_name,
"version": version.get("version"),
"numFolders": len(config.get("folders", [])),
"numDevices": len(config.get("devices", [])),
}
)
except Exception as exc:
entry.update({"available": False, "error": str(exc)})
results.append(entry)
return json.dumps(results, indent=2)
@mcp.tool(
name="syncthing_list_folders",
annotations={
"title": "List All Folders",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_list_folders(params: EmptyInput) -> str:
"""List all configured Syncthing folders with their labels, paths, type, and shared devices.
Returns:
str: JSON array of folders with id, label, path, type, paused, and list of shared device names/IDs.
"""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
folders = config.get("folders", [])
devices = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", [])
}
result = []
for f in folders:
shared = []
for d in f.get("devices", []):
did = d.get("deviceID", "")
shared.append({"deviceID": did, "name": devices.get(did, did[:8])})
result.append(
{
"id": f["id"],
"label": f.get("label", f["id"]),
"path": f.get("path", ""),
"type": f.get("type", "sendreceive"),
"paused": f.get("paused", False),
"sharedWith": shared,
"numDevices": len(shared),
}
)
return json.dumps(result, indent=2)
except Exception as e:
return handle_error_global(e)
+450
View File
@@ -0,0 +1,450 @@
"""System status, health, errors, log, restart, and upgrade tools."""
import json
from typing import Any
import httpx
from syncthing_mcp.models import EmptyInput
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp
@mcp.tool(
name="syncthing_system_status",
annotations={
"title": "System Status",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_system_status(params: EmptyInput) -> str:
"""Get Syncthing system status including this device's ID, name, uptime, and version.
Returns:
str: JSON with myID, device name, uptime, version, and connection stats.
"""
try:
client = get_instance(params.instance)
status = await client._get("/rest/system/status")
version = await client._get("/rest/system/version")
config = await client._get("/rest/config")
my_id = status.get("myID", "")
my_name = my_id[:8]
for dev in config.get("devices", []):
if dev.get("deviceID") == my_id:
my_name = dev.get("name", my_id[:8])
break
return json.dumps(
{
"instance": client.name,
"myID": my_id,
"deviceName": my_name,
"uptime": status.get("uptime"),
"version": version.get("version"),
"os": version.get("os"),
"arch": version.get("arch"),
"numFolders": len(config.get("folders", [])),
"numDevices": len(config.get("devices", [])),
},
indent=2,
)
except Exception as e:
if isinstance(e, ValueError):
return handle_error_global(e)
try:
return get_instance(None).handle_error(e)
except Exception:
return handle_error_global(e)
@mcp.tool(
name="syncthing_system_errors",
annotations={
"title": "System Errors & Warnings",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_system_errors(params: EmptyInput) -> str:
"""Get recent system errors and warnings from Syncthing.
Returns:
str: JSON with error list, each containing 'when' timestamp and 'message'.
"""
try:
client = get_instance(params.instance)
result = await client._get("/rest/system/error")
errors = result.get("errors", []) or []
return json.dumps(
{
"instance": client.name,
"errorCount": len(errors),
"errors": errors,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_clear_errors",
annotations={
"title": "Clear System Errors",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_clear_errors(params: EmptyInput) -> str:
"""Clear the system error log.
Returns:
str: Confirmation message.
"""
try:
client = get_instance(params.instance)
await client._post("/rest/system/error/clear")
return json.dumps(
{
"status": "cleared",
"instance": client.name,
"message": "System error log has been cleared.",
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_system_log",
annotations={
"title": "System Log",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_system_log(params: EmptyInput) -> str:
"""Get recent system log entries from Syncthing.
Returns:
str: JSON with log messages, each containing 'when' timestamp, 'message',
and 'level'.
"""
try:
client = get_instance(params.instance)
result = await client._get("/rest/system/log")
messages = result.get("messages", []) or []
return json.dumps(
{
"instance": client.name,
"messageCount": len(messages),
"messages": messages,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_recent_changes",
annotations={
"title": "Recent File Changes",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_recent_changes(params: EmptyInput) -> str:
"""Get recent file change events (local and remote) across all folders.
Uses a non-blocking poll of the Syncthing event stream with limit=50.
Returns:
str: JSON with recent LocalChangeDetected and RemoteChangeDetected events.
"""
try:
client = get_instance(params.instance)
events = await client._get(
"/rest/events",
params={
"events": "LocalChangeDetected,RemoteChangeDetected",
"limit": "50",
"timeout": "0",
},
)
if not isinstance(events, list):
events = []
return json.dumps(
{
"instance": client.name,
"eventCount": len(events),
"events": events,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_restart_required",
annotations={
"title": "Check if Restart Required",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_restart_required(params: EmptyInput) -> str:
"""Check if Syncthing requires a restart for configuration changes to take effect.
Returns:
str: JSON with restartRequired boolean.
"""
try:
client = get_instance(params.instance)
result = await client._get("/rest/config/restart-required")
return json.dumps(
{
"instance": client.name,
"restartRequired": result.get("requiresRestart", False),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_restart",
annotations={
"title": "Restart Syncthing",
"readOnlyHint": False,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_restart(params: EmptyInput) -> str:
"""Restart the Syncthing service to apply pending configuration changes.
WARNING: This temporarily stops synchronization on all folders for this instance.
Returns:
str: Confirmation message.
"""
try:
client = get_instance(params.instance)
try:
await client._post("/rest/system/restart")
except (httpx.ConnectError, httpx.RemoteProtocolError):
pass # Expected — Syncthing closes the connection as it restarts
return json.dumps(
{
"status": "restart_initiated",
"instance": client.name,
"message": (
f"Syncthing on '{client.name}' is restarting. "
"Connection may be lost briefly. Sync resumes automatically."
),
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_check_upgrade",
annotations={
"title": "Check for Upgrade",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_check_upgrade(params: EmptyInput) -> str:
"""Check if a newer version of Syncthing is available.
Returns:
str: JSON with running version, latest version, and whether an upgrade
is available.
"""
try:
client = get_instance(params.instance)
version = await client._get("/rest/system/version")
try:
upgrade = await client._get("/rest/system/upgrade")
return json.dumps(
{
"instance": client.name,
"running": version.get("version"),
"latest": upgrade.get("latest"),
"newer": upgrade.get("newer", False),
"majorNewer": upgrade.get("majorNewer", False),
},
indent=2,
)
except httpx.HTTPStatusError as ue:
if ue.response.status_code == 501:
return json.dumps(
{
"instance": client.name,
"running": version.get("version"),
"message": "Upgrade check not available (disabled or unsupported).",
},
indent=2,
)
raise
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_health_summary",
annotations={
"title": "Health Summary",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_health_summary(params: EmptyInput) -> str:
"""Generate a single-call health overview: system status, folder states,
device connectivity, errors, and pending items.
Designed for quick triage — aggregates data from multiple endpoints.
Returns:
str: JSON with overall status ('good', 'warning', 'error'), summary
counts, alert list, and per-folder health.
"""
try:
client = get_instance(params.instance)
sys_status = await client._get("/rest/system/status")
config = await client._get("/rest/config")
sys_errors = await client._get("/rest/system/error")
connections = await client._get("/rest/system/connections")
try:
pending_devices = await client._get("/rest/cluster/pending/devices")
except Exception:
pending_devices = {}
try:
pending_folders = await client._get("/rest/cluster/pending/folders")
except Exception:
pending_folders = {}
folders = config.get("folders", [])
conn_data = connections.get("connections", {})
online_count = sum(1 for c in conn_data.values() if c.get("connected"))
total_remote = len(conn_data)
folder_health = []
paused_count = 0
syncing_count = 0
error_folders = 0
for f_cfg in folders:
fid = f_cfg["id"]
entry: dict[str, Any] = {
"id": fid,
"label": f_cfg.get("label", fid),
"paused": f_cfg.get("paused", False),
}
if f_cfg.get("paused", False):
paused_count += 1
entry["state"] = "paused"
else:
try:
fstatus = await client._get(
"/rest/db/status", params={"folder": fid}
)
state = fstatus.get("state", "unknown")
entry["state"] = state
entry["needBytes"] = fstatus.get("needBytes", 0)
entry["needSize"] = format_bytes(fstatus.get("needBytes", 0))
if state in ("syncing", "sync-preparing"):
syncing_count += 1
elif state == "error":
error_folders += 1
except Exception:
entry["state"] = "unreachable"
error_folders += 1
folder_health.append(entry)
alerts: list[str] = []
error_list = sys_errors.get("errors", []) or []
if error_list:
alerts.append(f"{len(error_list)} system error(s)")
if error_folders > 0:
alerts.append(f"{error_folders} folder(s) in error state")
offline_count = total_remote - online_count
if offline_count > 0:
alerts.append(f"{offline_count} device(s) offline")
if paused_count > 0:
alerts.append(f"{paused_count} folder(s) paused")
if syncing_count > 0:
alerts.append(f"{syncing_count} folder(s) currently syncing")
num_pending_dev = len(pending_devices) if isinstance(pending_devices, dict) else 0
num_pending_fld = len(pending_folders) if isinstance(pending_folders, dict) else 0
if num_pending_dev > 0:
alerts.append(f"{num_pending_dev} pending device request(s)")
if num_pending_fld > 0:
alerts.append(f"{num_pending_fld} pending folder offer(s)")
if error_folders > 0 or len(error_list) > 0:
overall = "error"
elif alerts:
overall = "warning"
else:
overall = "good"
return json.dumps(
{
"instance": client.name,
"status": overall,
"uptime": sys_status.get("uptime"),
"summary": {
"totalFolders": len(folders),
"foldersIdle": sum(
1 for f in folder_health if f.get("state") == "idle"
),
"foldersSyncing": syncing_count,
"foldersPaused": paused_count,
"foldersError": error_folders,
"totalDevices": len(config.get("devices", [])),
"devicesOnline": online_count,
"devicesOffline": offline_count,
"systemErrors": len(error_list),
"pendingDevices": num_pending_dev,
"pendingFolders": num_pending_fld,
},
"alerts": alerts,
"folders": folder_health,
},
indent=2,
)
except Exception as e:
return handle_error_global(e)
-1879
View File
File diff suppressed because it is too large. Load diff
View File
Whitespace-only changes.
+179
View File
@@ -0,0 +1,179 @@
"""Shared fixtures for Syncthing MCP tests."""
import json
import os
from unittest.mock import patch
import pytest
import respx
from httpx import Response
from syncthing_mcp.client import SyncthingClient
# ---------------------------------------------------------------------------
# Common Syncthing API response fixtures
# ---------------------------------------------------------------------------
DEVICE_ID_LOCAL = "AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA"
DEVICE_ID_REMOTE = "BBBBBBB-BBBBBBB-BBBBBBB-BBBBBBB-BBBBBBB-BBBBBBB-BBBBBBB-BBBBBBB"
DEVICE_ID_REMOTE2 = "CCCCCCC-CCCCCCC-CCCCCCC-CCCCCCC-CCCCCCC-CCCCCCC-CCCCCCC-CCCCCCC"
FOLDER_ID = "test-folder"
API_KEY = "test-api-key-12345"
BASE_URL = "http://localhost:8384"
def make_config(
*,
folders: list | None = None,
devices: list | None = None,
) -> dict:
"""Build a minimal Syncthing config response."""
if devices is None:
devices = [
{"deviceID": DEVICE_ID_LOCAL, "name": "local-dev"},
{"deviceID": DEVICE_ID_REMOTE, "name": "remote-dev"},
]
if folders is None:
folders = [
{
"id": FOLDER_ID,
"label": "Test Folder",
"path": "/data/test",
"type": "sendreceive",
"paused": False,
"devices": [
{"deviceID": DEVICE_ID_LOCAL},
{"deviceID": DEVICE_ID_REMOTE},
],
}
]
return {"folders": folders, "devices": devices}
def make_system_status(my_id: str = DEVICE_ID_LOCAL) -> dict:
return {"myID": my_id, "uptime": 3600}
def make_version() -> dict:
return {"version": "v1.28.0", "os": "linux", "arch": "amd64"}
def make_connections(connected: dict | None = None) -> dict:
if connected is None:
connected = {
DEVICE_ID_LOCAL: {"connected": True, "paused": False, "address": "127.0.0.1:22000",
"type": "tcp-client", "crypto": "TLS1.3", "inBytesTotal": 1024, "outBytesTotal": 2048},
DEVICE_ID_REMOTE: {"connected": True, "paused": False, "address": "192.168.1.2:22000",
"type": "tcp-client", "crypto": "TLS1.3", "inBytesTotal": 4096, "outBytesTotal": 8192},
}
return {"connections": connected}
def make_db_status(*, state: str = "idle", local_bytes: int = 1000000, global_bytes: int = 1000000) -> dict:
return {
"state": state,
"stateChanged": "2025-01-01T00:00:00Z",
"globalFiles": 100,
"globalBytes": global_bytes,
"localFiles": 100,
"localBytes": local_bytes,
"needFiles": 0,
"needBytes": 0,
"inSyncFiles": 100,
"inSyncBytes": local_bytes,
"globalDeleted": 5,
"localDeleted": 5,
"ignorePatterns": True,
}
def make_completion(pct: float = 100.0, remote_state: str = "valid") -> dict:
return {
"completion": pct,
"globalBytes": 1000000,
"needBytes": int(1000000 * (1 - pct / 100)),
"needItems": 0 if pct == 100 else 5,
"needDeletes": 0,
"remoteState": remote_state,
}
def make_stats_device() -> dict:
return {
DEVICE_ID_LOCAL: {"lastSeen": "2025-01-01T12:00:00Z"},
DEVICE_ID_REMOTE: {"lastSeen": "2025-01-01T12:00:00Z"},
}
def make_stats_folder() -> dict:
return {
FOLDER_ID: {
"lastScan": "2025-01-01T12:00:00Z",
"lastFile": {"filename": "test.txt", "at": "2025-01-01T11:00:00Z"},
}
}
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def client():
"""A SyncthingClient for testing."""
return SyncthingClient("test", BASE_URL, API_KEY)
@pytest.fixture
def single_instance_env(monkeypatch):
"""Set env vars for single-instance mode."""
monkeypatch.setenv("SYNCTHING_API_KEY", API_KEY)
monkeypatch.setenv("SYNCTHING_URL", BASE_URL)
monkeypatch.delenv("SYNCTHING_INSTANCES", raising=False)
@pytest.fixture
def multi_instance_env(monkeypatch):
"""Set env vars for multi-instance mode."""
instances = {
"alpha": {"url": "http://alpha.local:8384", "api_key": "key-alpha"},
"beta": {"url": "http://beta.local:8384", "api_key": "key-beta"},
}
monkeypatch.setenv("SYNCTHING_INSTANCES", json.dumps(instances))
monkeypatch.delenv("SYNCTHING_API_KEY", raising=False)
monkeypatch.delenv("SYNCTHING_URL", raising=False)
@pytest.fixture
def mock_api():
"""Activate respx mock for the default Syncthing base URL.
Pre-configures common routes so tools can call multiple endpoints.
Returns the respx mock router for further customisation.
"""
with respx.mock(base_url=BASE_URL, assert_all_called=False) as router:
# Pre-configure common endpoints
router.get("/rest/system/status").respond(json=make_system_status())
router.get("/rest/system/version").respond(json=make_version())
router.get("/rest/config").respond(json=make_config())
router.get("/rest/system/connections").respond(json=make_connections())
router.get("/rest/stats/device").respond(json=make_stats_device())
router.get("/rest/stats/folder").respond(json=make_stats_folder())
router.get("/rest/system/error").respond(json={"errors": []})
router.get("/rest/system/log").respond(json={"messages": []})
router.get("/rest/config/restart-required").respond(json={"requiresRestart": False})
router.get("/rest/cluster/pending/devices").respond(json={})
router.get("/rest/cluster/pending/folders").respond(json={})
yield router
@pytest.fixture
def _setup_single_instance(single_instance_env):
"""Reload the registry with single-instance env, then restore after test."""
from syncthing_mcp import registry
registry.reload_instances()
yield
registry.reload_instances()
+129
View File
@@ -0,0 +1,129 @@
"""Tests for SyncthingClient HTTP methods and error handling."""
import httpx
import pytest
import respx
from httpx import Response
from syncthing_mcp.client import SyncthingClient
BASE_URL = "http://localhost:8384"
API_KEY = "test-key"
@pytest.fixture
def client():
return SyncthingClient("test", BASE_URL, API_KEY)
class TestGet:
async def test_get_json(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.get("/rest/system/status").respond(json={"myID": "abc123"})
result = await client._get("/rest/system/status")
assert result["myID"] == "abc123"
async def test_get_with_params(self, client):
with respx.mock(base_url=BASE_URL) as router:
route = router.get("/rest/db/status").respond(json={"state": "idle"})
result = await client._get("/rest/db/status", params={"folder": "f1"})
assert result["state"] == "idle"
assert route.calls[0].request.url.params["folder"] == "f1"
async def test_get_401(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.get("/rest/system/status").respond(status_code=401)
with pytest.raises(httpx.HTTPStatusError):
await client._get("/rest/system/status")
class TestPost:
async def test_post_json_response(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.post("/rest/db/scan").respond(json={"ok": True}, headers={"content-type": "application/json"})
result = await client._post("/rest/db/scan", params={"folder": "f1"})
assert result == {"ok": True}
async def test_post_empty_response(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.post("/rest/system/restart").respond(status_code=200, content=b"")
result = await client._post("/rest/system/restart")
assert result == {"status": "ok"}
class TestPatch:
async def test_patch(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.patch("/rest/config/folders/f1").respond(json={"id": "f1"}, headers={"content-type": "application/json"})
result = await client._patch("/rest/config/folders/f1", body={"paused": True})
assert result["id"] == "f1"
class TestPut:
async def test_put(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.put("/rest/config/defaults/ignores").respond(json={"lines": []}, headers={"content-type": "application/json"})
result = await client._put("/rest/config/defaults/ignores", body={"lines": ["*.tmp"]})
assert result == {"lines": []}
class TestDelete:
async def test_delete(self, client):
with respx.mock(base_url=BASE_URL) as router:
router.delete("/rest/cluster/pending/devices").respond(status_code=200, content=b"")
result = await client._delete("/rest/cluster/pending/devices", params={"device": "ABCDEF"})
assert result == {"status": "ok"}
class TestHandleError:
def test_401(self, client):
req = httpx.Request("GET", f"{BASE_URL}/rest/test")
resp = httpx.Response(401, request=req)
err = httpx.HTTPStatusError("401", request=req, response=resp)
msg = client.handle_error(err)
assert "401" in msg
assert "Unauthorized" in msg
def test_403(self, client):
req = httpx.Request("GET", f"{BASE_URL}/rest/test")
resp = httpx.Response(403, request=req)
err = httpx.HTTPStatusError("403", request=req, response=resp)
msg = client.handle_error(err)
assert "403" in msg
assert "Forbidden" in msg
def test_404(self, client):
req = httpx.Request("GET", f"{BASE_URL}/rest/test")
resp = httpx.Response(404, request=req, text="not found")
err = httpx.HTTPStatusError("404", request=req, response=resp)
msg = client.handle_error(err)
assert "404" in msg
def test_connect_error(self, client):
err = httpx.ConnectError("Connection refused")
msg = client.handle_error(err)
assert "Cannot connect" in msg
assert BASE_URL in msg
def test_timeout(self, client):
err = httpx.ReadTimeout("timed out")
msg = client.handle_error(err)
assert "timed out" in msg.lower() or "Request timed out" in msg
def test_generic_error(self, client):
err = RuntimeError("something broke")
msg = client.handle_error(err)
assert "RuntimeError" in msg
assert "something broke" in msg
def test_default_instance_no_prefix(self):
c = SyncthingClient("default", BASE_URL, API_KEY)
err = RuntimeError("test")
msg = c.handle_error(err)
assert not msg.startswith("[default]")
def test_named_instance_has_prefix(self):
c = SyncthingClient("mynas", BASE_URL, API_KEY)
err = RuntimeError("test")
msg = c.handle_error(err)
assert msg.startswith("[mynas]")
+111
View File
@@ -0,0 +1,111 @@
"""Tests for Pydantic input model validation."""
import pytest
from pydantic import ValidationError
from syncthing_mcp.models import (
BrowseFolderInput,
DeviceInput,
EmptyInput,
FileInfoInput,
FolderInput,
FolderNeedInput,
PauseFolderInput,
SetIgnoresInput,
)
class TestEmptyInput:
def test_no_args(self):
m = EmptyInput()
assert m.instance is None
def test_with_instance(self):
m = EmptyInput(instance="mynas")
assert m.instance == "mynas"
def test_extra_field_rejected(self):
with pytest.raises(ValidationError):
EmptyInput(instance="a", extra="bad")
class TestFolderInput:
def test_valid(self):
m = FolderInput(folder_id="abc-123")
assert m.folder_id == "abc-123"
def test_empty_folder_id(self):
with pytest.raises(ValidationError):
FolderInput(folder_id="")
def test_whitespace_stripped(self):
m = FolderInput(folder_id=" abc ")
assert m.folder_id == "abc"
class TestDeviceInput:
def test_valid(self):
m = DeviceInput(device_id="ABCDEF-123456")
assert m.device_id == "ABCDEF-123456"
def test_empty_device_id(self):
with pytest.raises(ValidationError):
DeviceInput(device_id="")
class TestPauseFolderInput:
def test_valid(self):
m = PauseFolderInput(folder_id="f1")
assert m.folder_id == "f1"
class TestSetIgnoresInput:
def test_valid(self):
m = SetIgnoresInput(folder_id="f1", patterns=["*.tmp", ".DS_Store"])
assert len(m.patterns) == 2
class TestBrowseFolderInput:
def test_defaults(self):
m = BrowseFolderInput(folder_id="f1")
assert m.prefix is None
assert m.levels is None
def test_with_prefix(self):
m = BrowseFolderInput(folder_id="f1", prefix="docs/reports", levels=2)
assert m.prefix == "docs/reports"
assert m.levels == 2
def test_negative_levels(self):
with pytest.raises(ValidationError):
BrowseFolderInput(folder_id="f1", levels=-1)
class TestFileInfoInput:
def test_valid(self):
m = FileInfoInput(folder_id="f1", file_path="docs/readme.md")
assert m.file_path == "docs/readme.md"
def test_empty_file_path(self):
with pytest.raises(ValidationError):
FileInfoInput(folder_id="f1", file_path="")
class TestFolderNeedInput:
def test_defaults(self):
m = FolderNeedInput(folder_id="f1")
assert m.page == 1
assert m.per_page == 50
def test_custom_pagination(self):
m = FolderNeedInput(folder_id="f1", page=3, per_page=100)
assert m.page == 3
assert m.per_page == 100
def test_page_must_be_positive(self):
with pytest.raises(ValidationError):
FolderNeedInput(folder_id="f1", page=0)
def test_per_page_max(self):
with pytest.raises(ValidationError):
FolderNeedInput(folder_id="f1", per_page=501)
+119
View File
@@ -0,0 +1,119 @@
"""Tests for instance registry loading and resolution."""
import json
import os
import pytest
from syncthing_mcp.client import SyncthingClient
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
load_instances,
reload_instances,
)
class TestFormatBytes:
def test_zero(self):
assert format_bytes(0) == "0.0 B"
def test_bytes(self):
assert format_bytes(512) == "512.0 B"
def test_kilobytes(self):
assert format_bytes(2048) == "2.0 KB"
def test_megabytes(self):
assert format_bytes(5 * 1024 * 1024) == "5.0 MB"
def test_gigabytes(self):
assert format_bytes(3 * 1024**3) == "3.0 GB"
def test_terabytes(self):
assert format_bytes(2 * 1024**4) == "2.0 TB"
class TestLoadInstances:
def test_single_instance_defaults(self, monkeypatch):
monkeypatch.delenv("SYNCTHING_INSTANCES", raising=False)
monkeypatch.setenv("SYNCTHING_API_KEY", "mykey")
monkeypatch.delenv("SYNCTHING_URL", raising=False)
instances = load_instances()
assert "default" in instances
assert instances["default"].url == "http://localhost:8384"
assert instances["default"].api_key == "mykey"
def test_single_instance_custom_url(self, monkeypatch):
monkeypatch.delenv("SYNCTHING_INSTANCES", raising=False)
monkeypatch.setenv("SYNCTHING_API_KEY", "mykey")
monkeypatch.setenv("SYNCTHING_URL", "http://nas.local:8384")
instances = load_instances()
assert instances["default"].url == "http://nas.local:8384"
def test_multi_instance(self, monkeypatch):
cfg = {
"alpha": {"url": "http://a:8384", "api_key": "ka"},
"beta": {"url": "http://b:8384", "api_key": "kb"},
}
monkeypatch.setenv("SYNCTHING_INSTANCES", json.dumps(cfg))
instances = load_instances()
assert len(instances) == 2
assert instances["alpha"].url == "http://a:8384"
assert instances["beta"].api_key == "kb"
def test_invalid_json(self, monkeypatch):
monkeypatch.setenv("SYNCTHING_INSTANCES", "{bad json")
with pytest.raises(ValueError, match="Invalid SYNCTHING_INSTANCES JSON"):
load_instances()
def test_empty_object(self, monkeypatch):
monkeypatch.setenv("SYNCTHING_INSTANCES", "{}")
with pytest.raises(ValueError, match="non-empty"):
load_instances()
def test_non_dict_entry(self, monkeypatch):
monkeypatch.setenv("SYNCTHING_INSTANCES", json.dumps({"a": "not a dict"}))
with pytest.raises(ValueError, match="must be a JSON object"):
load_instances()
def test_url_trailing_slash_stripped(self, monkeypatch):
monkeypatch.delenv("SYNCTHING_INSTANCES", raising=False)
monkeypatch.setenv("SYNCTHING_API_KEY", "k")
monkeypatch.setenv("SYNCTHING_URL", "http://localhost:8384/")
instances = load_instances()
assert instances["default"].url == "http://localhost:8384"
class TestGetInstance:
def test_auto_select_single(self, monkeypatch, single_instance_env):
reload_instances()
inst = get_instance(None)
assert inst.name == "default"
def test_explicit_name(self, monkeypatch, multi_instance_env):
reload_instances()
inst = get_instance("alpha")
assert inst.name == "alpha"
def test_missing_name(self, monkeypatch, multi_instance_env):
reload_instances()
with pytest.raises(ValueError, match="not found"):
get_instance("nonexistent")
def test_ambiguous_without_name(self, monkeypatch, multi_instance_env):
reload_instances()
with pytest.raises(ValueError, match="Multiple instances"):
get_instance(None)
class TestHandleErrorGlobal:
def test_value_error(self):
msg = handle_error_global(ValueError("bad input"))
assert msg == "Error: bad input"
def test_generic_error(self):
msg = handle_error_global(RuntimeError("boom"))
assert "RuntimeError" in msg
assert "boom" in msg
+166
View File
@@ -0,0 +1,166 @@
"""Tests for config mutation tools (pending, accept/reject, ignores)."""
import json
import pytest
from syncthing_mcp.models import (
AcceptDeviceInput,
AcceptFolderInput,
DeviceInput,
EmptyInput,
FolderInput,
RejectFolderInput,
SetDefaultIgnoresInput,
SetIgnoresInput,
)
from syncthing_mcp.registry import reload_instances
from tests.conftest import (
BASE_URL,
DEVICE_ID_LOCAL,
DEVICE_ID_REMOTE,
DEVICE_ID_REMOTE2,
FOLDER_ID,
make_system_status,
)
@pytest.fixture(autouse=True)
def _setup(single_instance_env):
reload_instances()
yield
reload_instances()
class TestPendingDevices:
async def test_empty(self, mock_api):
from syncthing_mcp.tools.config import syncthing_pending_devices
result = json.loads(await syncthing_pending_devices(EmptyInput()))
assert result["pendingDevices"] == {}
class TestPendingFolders:
async def test_empty(self, mock_api):
from syncthing_mcp.tools.config import syncthing_pending_folders
result = json.loads(await syncthing_pending_folders(EmptyInput()))
assert result["pendingFolders"] == {}
class TestAcceptDevice:
async def test_accept(self, mock_api):
from syncthing_mcp.tools.config import syncthing_accept_device
mock_api.get("/rest/cluster/pending/devices").respond(json={
DEVICE_ID_REMOTE2: {"name": "new-device", "address": "10.0.0.5"}
})
mock_api.get("/rest/config/defaults/device").respond(json={
"addresses": ["dynamic"],
})
mock_api.post("/rest/config/devices").respond(status_code=200, content=b"")
result = json.loads(await syncthing_accept_device(
AcceptDeviceInput(device_id=DEVICE_ID_REMOTE2)
))
assert result["status"] == "accepted"
assert result["name"] == "new-device"
class TestRejectDevice:
async def test_reject(self, mock_api):
from syncthing_mcp.tools.config import syncthing_reject_device
mock_api.delete("/rest/cluster/pending/devices").respond(status_code=200, content=b"")
result = json.loads(await syncthing_reject_device(
DeviceInput(device_id=DEVICE_ID_REMOTE2)
))
assert result["status"] == "rejected"
class TestAcceptFolder:
async def test_accept(self, mock_api):
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": "/home/user/Sync",
"type": "sendreceive",
})
mock_api.post("/rest/config/folders").respond(status_code=200, content=b"")
result = json.loads(await syncthing_accept_folder(
AcceptFolderInput(folder_id="new-folder")
))
assert result["status"] == "accepted"
assert result["label"] == "Shared Docs"
async def test_not_pending(self, mock_api):
from syncthing_mcp.tools.config import syncthing_accept_folder
result = json.loads(await syncthing_accept_folder(
AcceptFolderInput(folder_id="nonexistent")
))
assert "error" in result
class TestRejectFolder:
async def test_reject(self, mock_api):
from syncthing_mcp.tools.config import syncthing_reject_folder
mock_api.delete("/rest/cluster/pending/folders").respond(status_code=200, content=b"")
result = json.loads(await syncthing_reject_folder(
RejectFolderInput(folder_id="some-folder")
))
assert result["status"] == "rejected"
class TestGetIgnores:
async def test_get(self, mock_api):
from syncthing_mcp.tools.config import syncthing_get_ignores
mock_api.get("/rest/db/ignores").respond(json={
"ignore": ["*.tmp", ".DS_Store"],
"expanded": ["*.tmp", ".DS_Store"],
})
result = json.loads(await syncthing_get_ignores(FolderInput(folder_id=FOLDER_ID)))
assert len(result["patterns"]) == 2
class TestSetIgnores:
async def test_set(self, mock_api):
from syncthing_mcp.tools.config import syncthing_set_ignores
mock_api.post("/rest/db/ignores").respond(status_code=200, content=b"")
result = json.loads(await syncthing_set_ignores(
SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"])
))
assert result["status"] == "updated"
assert result["patternCount"] == 2
class TestGetDefaultIgnores:
async def test_get(self, mock_api):
from syncthing_mcp.tools.config import syncthing_get_default_ignores
mock_api.get("/rest/config/defaults/ignores").respond(json={"lines": [".DS_Store"]})
result = json.loads(await syncthing_get_default_ignores(EmptyInput()))
assert result["lines"] == [".DS_Store"]
class TestSetDefaultIgnores:
async def test_set(self, mock_api):
from syncthing_mcp.tools.config import syncthing_set_default_ignores
mock_api.put("/rest/config/defaults/ignores").respond(
json={"lines": ["Thumbs.db"]},
headers={"content-type": "application/json"},
)
result = json.loads(await syncthing_set_default_ignores(
SetDefaultIgnoresInput(lines=["Thumbs.db"])
))
assert result["status"] == "updated"
+53
View File
@@ -0,0 +1,53 @@
"""Tests for device tools (list, completion, connections)."""
import json
import pytest
from syncthing_mcp.models import DeviceInput, EmptyInput
from syncthing_mcp.registry import reload_instances
from tests.conftest import (
BASE_URL,
DEVICE_ID_LOCAL,
DEVICE_ID_REMOTE,
make_completion,
)
@pytest.fixture(autouse=True)
def _setup(single_instance_env):
reload_instances()
yield
reload_instances()
class TestListDevices:
async def test_returns_devices(self, mock_api):
from syncthing_mcp.tools.devices import syncthing_list_devices
result = json.loads(await syncthing_list_devices(EmptyInput()))
assert len(result) == 2
names = {d["name"] for d in result}
assert "local-dev" in names
assert "remote-dev" in names
class TestDeviceCompletion:
async def test_fully_synced(self, mock_api):
from syncthing_mcp.tools.devices import syncthing_device_completion
mock_api.get("/rest/db/completion").respond(json=make_completion(100.0))
result = json.loads(await syncthing_device_completion(
DeviceInput(device_id=DEVICE_ID_REMOTE)
))
assert result["completion"] == 100.0
assert result["needBytes"] == 0
class TestConnections:
async def test_returns_connections(self, mock_api):
from syncthing_mcp.tools.devices import syncthing_connections
result = json.loads(await syncthing_connections(EmptyInput()))
assert len(result) == 2
assert any(c["connected"] for c in result)
+206
View File
@@ -0,0 +1,206 @@
"""Tests for folder tools (status, completion, replication, operations, new tools)."""
import json
import pytest
import respx
from syncthing_mcp.models import (
BrowseFolderInput,
EmptyInput,
FileInfoInput,
FolderInput,
FolderNeedInput,
PauseFolderInput,
)
from syncthing_mcp.registry import reload_instances
from tests.conftest import (
BASE_URL,
DEVICE_ID_LOCAL,
DEVICE_ID_REMOTE,
FOLDER_ID,
make_completion,
make_config,
make_connections,
make_db_status,
make_stats_folder,
make_system_status,
)
@pytest.fixture(autouse=True)
def _setup(single_instance_env):
reload_instances()
yield
reload_instances()
class TestFolderStatus:
async def test_returns_status(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_status
mock_api.get("/rest/db/status").respond(json=make_db_status())
result = json.loads(await syncthing_folder_status(FolderInput(folder_id=FOLDER_ID)))
assert result["folder"] == FOLDER_ID
assert result["state"] == "idle"
assert result["globalSize"] is not None
class TestFolderCompletion:
async def test_fully_replicated(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_completion
mock_api.get("/rest/db/completion").respond(json=make_completion(100.0))
result = json.loads(await syncthing_folder_completion(FolderInput(folder_id=FOLDER_ID)))
assert result["fullyReplicatedOn"] == 1
assert result["devices"][0]["completion"] == 100.0
async def test_partially_replicated(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_completion
mock_api.get("/rest/db/completion").respond(json=make_completion(75.0, "unknown"))
result = json.loads(await syncthing_folder_completion(FolderInput(folder_id=FOLDER_ID)))
assert result["fullyReplicatedOn"] == 0
async def test_folder_not_found(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_completion
result = json.loads(await syncthing_folder_completion(FolderInput(folder_id="nonexistent")))
assert "error" in result
class TestReplicationReport:
async def test_safe_to_remove(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_replication_report
mock_api.get("/rest/db/status").respond(json=make_db_status())
mock_api.get("/rest/db/completion").respond(json=make_completion(100.0))
result = json.loads(await syncthing_replication_report(EmptyInput()))
assert result["summary"]["safeToRemoveCount"] == 1
assert result["folders"][0]["safeToRemove"] is True
async def test_not_safe_when_incomplete(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_replication_report
mock_api.get("/rest/db/status").respond(json=make_db_status())
mock_api.get("/rest/db/completion").respond(json=make_completion(50.0))
result = json.loads(await syncthing_replication_report(EmptyInput()))
assert result["summary"]["safeToRemoveCount"] == 0
class TestPauseFolder:
async def test_pause(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_pause_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(
json={"id": FOLDER_ID, "paused": False}
)
mock_api.patch(f"/rest/config/folders/{FOLDER_ID}").respond(
json={"id": FOLDER_ID, "paused": True},
headers={"content-type": "application/json"},
)
result = json.loads(await syncthing_pause_folder(PauseFolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "paused"
class TestResumeFolder:
async def test_resume(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_resume_folder
mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond(
json={"id": FOLDER_ID, "type": "sendreceive", "paused": True}
)
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)))
assert result["status"] == "resumed"
assert result["folderType"] == "sendreceive"
class TestScanFolder:
async def test_scan(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_scan_folder
mock_api.post("/rest/db/scan").respond(status_code=200, content=b"")
result = json.loads(await syncthing_scan_folder(FolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "scan_requested"
class TestFolderErrors:
async def test_no_errors(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_errors
mock_api.get("/rest/folder/errors").respond(json={"errors": None, "page": 1})
result = json.loads(await syncthing_folder_errors(FolderInput(folder_id=FOLDER_ID)))
assert result["errorCount"] == 0
class TestBrowseFolder:
async def test_browse_root(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_browse_folder
mock_api.get("/rest/db/browse").respond(json=[
{"name": "docs", "type": "directory"},
{"name": "readme.txt", "type": "file"},
])
result = json.loads(await syncthing_browse_folder(BrowseFolderInput(folder_id=FOLDER_ID)))
assert result["folder"] == FOLDER_ID
assert len(result["entries"]) == 2
async def test_browse_with_prefix(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_browse_folder
route = mock_api.get("/rest/db/browse").respond(json=[])
result = json.loads(await syncthing_browse_folder(
BrowseFolderInput(folder_id=FOLDER_ID, prefix="docs", levels=2)
))
assert result["prefix"] == "docs"
class TestFileInfo:
async def test_file_info(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_file_info
mock_api.get("/rest/db/file").respond(json={
"availability": [{"id": DEVICE_ID_REMOTE}],
"global": {"name": "test.txt", "size": 1024, "modified": "2025-01-01T00:00:00Z"},
"local": {"name": "test.txt", "size": 1024},
})
result = json.loads(await syncthing_file_info(
FileInfoInput(folder_id=FOLDER_ID, file_path="test.txt")
))
assert result["file"] == "test.txt"
assert result["global"]["sizeFormatted"] == "1.0 KB"
class TestFolderNeed:
async def test_need_empty(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_need
mock_api.get("/rest/db/need").respond(json={
"page": 1, "perpage": 50,
"progress": [], "queued": [], "rest": [],
})
result = json.loads(await syncthing_folder_need(FolderNeedInput(folder_id=FOLDER_ID)))
assert result["progress"] == []
assert result["queued"] == []
class TestOverrideFolder:
async def test_override(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_override_folder
mock_api.post("/rest/db/override").respond(status_code=200, content=b"")
result = json.loads(await syncthing_override_folder(FolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "override_requested"
class TestRevertFolder:
async def test_revert(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_revert_folder
mock_api.post("/rest/db/revert").respond(status_code=200, content=b"")
result = json.loads(await syncthing_revert_folder(FolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "revert_requested"
+142
View File
@@ -0,0 +1,142 @@
"""Tests for system tools (status, health, errors, log, restart, upgrade)."""
import json
import pytest
import respx
from httpx import Response
from syncthing_mcp.models import EmptyInput
from syncthing_mcp.registry import reload_instances
from tests.conftest import (
BASE_URL,
DEVICE_ID_LOCAL,
FOLDER_ID,
make_completion,
make_config,
make_connections,
make_db_status,
make_system_status,
make_version,
)
@pytest.fixture(autouse=True)
def _setup(single_instance_env):
reload_instances()
yield
reload_instances()
class TestSystemStatus:
async def test_returns_status(self, mock_api):
from syncthing_mcp.tools.system import syncthing_system_status
result = json.loads(await syncthing_system_status(EmptyInput()))
assert result["myID"] == DEVICE_ID_LOCAL
assert result["deviceName"] == "local-dev"
assert result["version"] == "v1.28.0"
assert result["instance"] == "default"
class TestSystemErrors:
async def test_no_errors(self, mock_api):
from syncthing_mcp.tools.system import syncthing_system_errors
result = json.loads(await syncthing_system_errors(EmptyInput()))
assert result["errorCount"] == 0
async def test_with_errors(self, mock_api):
from syncthing_mcp.tools.system import syncthing_system_errors
mock_api.get("/rest/system/error").respond(
json={"errors": [{"when": "2025-01-01", "message": "disk full"}]}
)
result = json.loads(await syncthing_system_errors(EmptyInput()))
assert result["errorCount"] == 1
class TestClearErrors:
async def test_clear(self, mock_api):
from syncthing_mcp.tools.system import syncthing_clear_errors
mock_api.post("/rest/system/error/clear").respond(status_code=200, content=b"")
result = json.loads(await syncthing_clear_errors(EmptyInput()))
assert result["status"] == "cleared"
class TestSystemLog:
async def test_returns_log(self, mock_api):
from syncthing_mcp.tools.system import syncthing_system_log
result = json.loads(await syncthing_system_log(EmptyInput()))
assert result["messageCount"] == 0
class TestRecentChanges:
async def test_returns_events(self, mock_api):
from syncthing_mcp.tools.system import syncthing_recent_changes
mock_api.get("/rest/events").respond(json=[
{"id": 1, "type": "LocalChangeDetected", "data": {"path": "file.txt"}}
])
result = json.loads(await syncthing_recent_changes(EmptyInput()))
assert result["eventCount"] == 1
class TestRestartRequired:
async def test_not_required(self, mock_api):
from syncthing_mcp.tools.system import syncthing_restart_required
result = json.loads(await syncthing_restart_required(EmptyInput()))
assert result["restartRequired"] is False
class TestRestart:
async def test_restart(self, mock_api):
from syncthing_mcp.tools.system import syncthing_restart
mock_api.post("/rest/system/restart").respond(status_code=200, content=b"")
result = json.loads(await syncthing_restart(EmptyInput()))
assert result["status"] == "restart_initiated"
class TestCheckUpgrade:
async def test_upgrade_available(self, mock_api):
from syncthing_mcp.tools.system import syncthing_check_upgrade
mock_api.get("/rest/system/upgrade").respond(json={
"latest": "v1.29.0", "newer": True, "majorNewer": False
})
result = json.loads(await syncthing_check_upgrade(EmptyInput()))
assert result["newer"] is True
assert result["latest"] == "v1.29.0"
assert result["running"] == "v1.28.0"
async def test_upgrade_disabled(self, mock_api):
from syncthing_mcp.tools.system import syncthing_check_upgrade
mock_api.get("/rest/system/upgrade").respond(status_code=501)
result = json.loads(await syncthing_check_upgrade(EmptyInput()))
assert "not available" in result["message"]
class TestHealthSummary:
async def test_all_good(self, mock_api):
from syncthing_mcp.tools.system import syncthing_health_summary
mock_api.get("/rest/db/status").respond(json=make_db_status())
result = json.loads(await syncthing_health_summary(EmptyInput()))
assert result["status"] == "good"
assert result["summary"]["foldersIdle"] == 1
async def test_error_state(self, mock_api):
from syncthing_mcp.tools.system import syncthing_health_summary
mock_api.get("/rest/system/error").respond(
json={"errors": [{"when": "now", "message": "bad"}]}
)
mock_api.get("/rest/db/status").respond(json=make_db_status())
result = json.loads(await syncthing_health_summary(EmptyInput()))
assert result["status"] == "error"
assert any("system error" in a for a in result["alerts"])