Token-efficient output, SKILL.md, Cloudflare Tunnel, new tools (v0.3.0)

Major improvements following best-in-class MCP patterns:

- Token efficiency: new formatters.py with compact JSON (no indent),
  short device IDs, character-limit truncation; all read tools gain
  concise=true (default) / concise=false toggle via ReadParams base
- Models: ReadParams/WriteParams hierarchy replaces flat models;
  backward-compatible aliases preserved for tests
- New tools: syncthing_remote_need (debug remote sync gaps),
  syncthing_device_stats (per-device statistics)
- SKILL.md: LLM skill guide with token rules, quick-start table,
  workflows, tool reference, and troubleshooting
- Cloudflare Tunnel: docker-compose.tunnel.yml for zero-trust HTTP
  deployment alongside existing Traefik/ACME support
- Fix duplicate dependencies in pyproject.toml; bump to v0.3.0

https://claude.ai/code/session_018efEinU8ypT2jHeex6o9PC
This commit is contained in:
Claude committed 2026-02-17 03:44:48 +00:00
1 parent 39d6994738
commit 41f1018477
18 files changed
+1194 -987

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
"""Syncthing MCP Server — manage Syncthing instances via MCP tools."""
__version__ = "0.2.0"
__version__ = "0.3.0"
+265
View File
@@ -0,0 +1,265 @@
"""Token-efficient formatters for Syncthing API responses.
Design principles (following best-in-class MCP patterns):
- Default output is compact JSON (no indentation, no spaces after separators)
- Device IDs are truncated to short form unless full detail is requested
- Redundant fields (both raw bytes AND human-readable size) are collapsed
- Large responses are truncated with guidance to use pagination/filters
- Summary modes return counts only, skipping per-item detail
"""
import json
import random
from typing import Any
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
CHARACTER_LIMIT = 25_000
SHORT_ID_LEN = 7
# ---------------------------------------------------------------------------
# Core helpers
# ---------------------------------------------------------------------------
def fmt(data: Any, *, concise: bool = True) -> str:
"""Serialize to JSON. Compact by default for token efficiency."""
if concise:
return json.dumps(data, separators=(",", ":"))
return json.dumps(data, indent=2)
def short_id(device_id: str) -> str:
"""Truncate a Syncthing device ID to its first block."""
return device_id[:SHORT_ID_LEN] if device_id else ""
def format_bytes(n: int | float) -> 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 truncate(text: str, limit: int = CHARACTER_LIMIT) -> str:
"""Truncate text that exceeds the character limit, with guidance."""
if len(text) <= limit:
return text
cut = text[:limit]
last_nl = cut.rfind("\n")
if last_nl > limit * 0.8:
cut = cut[:last_nl]
return (
cut
+ f"\n... truncated ({len(text):,} chars, limit {limit:,})."
" Use pagination or filters to narrow results."
)
def sample(items: list, size: int = 5) -> list:
"""Return a random sample from a list without replacement."""
if len(items) <= size:
return items
return random.sample(items, size)
# ---------------------------------------------------------------------------
# Entity formatters — concise mode strips to essential fields only
# ---------------------------------------------------------------------------
def format_folder(cfg: dict, *, concise: bool = True) -> dict:
"""Format a folder config entry."""
if concise:
return {
"id": cfg["id"],
"label": cfg.get("label", cfg["id"]),
"type": cfg.get("type", "sendreceive"),
"paused": cfg.get("paused", False),
"devices": len(cfg.get("devices", [])),
}
devices = []
for d in cfg.get("devices", []):
did = d.get("deviceID", "")
devices.append(did)
return {
"id": cfg["id"],
"label": cfg.get("label", cfg["id"]),
"path": cfg.get("path", ""),
"type": cfg.get("type", "sendreceive"),
"paused": cfg.get("paused", False),
"devices": devices,
}
def format_device(
dev: dict,
conn: dict | None = None,
stat: dict | None = None,
*,
concise: bool = True,
) -> dict:
"""Format a device config + connection entry."""
did = dev["deviceID"]
conn = conn or {}
stat = stat or {}
if concise:
return {
"id": short_id(did),
"name": dev.get("name", short_id(did)),
"connected": conn.get("connected", False),
"address": conn.get("address", ""),
}
return {
"deviceID": did,
"name": dev.get("name", short_id(did)),
"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),
"lastSeen": stat.get("lastSeen", ""),
}
def format_folder_status(status: dict, *, concise: bool = True) -> dict:
"""Format a /rest/db/status response."""
if concise:
return {
"state": status.get("state"),
"globalFiles": status.get("globalFiles"),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"localFiles": status.get("localFiles"),
"localSize": format_bytes(status.get("localBytes", 0)),
"needFiles": status.get("needFiles"),
"needSize": format_bytes(status.get("needBytes", 0)),
}
return {
"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"),
}
def format_completion(
comp: dict,
device_name: str = "",
*,
connected: bool = False,
concise: bool = True,
) -> dict:
"""Format a /rest/db/completion response for a single device."""
if concise:
return {
"device": device_name or short_id(comp.get("deviceID", "")),
"connected": connected,
"completion": round(comp.get("completion", 0), 2),
"needSize": format_bytes(comp.get("needBytes", 0)),
"remoteState": comp.get("remoteState", "unknown"),
}
return {
"device": device_name,
"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"),
}
def format_connection(did: str, conn: dict, name: str = "", *, concise: bool = True) -> dict:
"""Format a single connection entry."""
if concise:
return {
"device": name or short_id(did),
"connected": conn.get("connected", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
}
return {
"deviceID": did,
"deviceName": name or short_id(did),
"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),
}
# ---------------------------------------------------------------------------
# Replication helpers
# ---------------------------------------------------------------------------
def format_replication_entry(
folder_cfg: dict,
status: dict,
device_completions: list[dict],
*,
concise: bool = True,
) -> dict:
"""Format a single folder's replication data for the replication report."""
fid = folder_cfg["id"]
label = folder_cfg.get("label", fid)
local_bytes = status.get("localBytes", 0)
state = status.get("state", "unknown")
paused = folder_cfg.get("paused", False)
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 concise:
return {
"id": fid,
"label": label,
"safe": safe,
"local": format_bytes(local_bytes),
"state": state,
"replicated": len(fully_replicated),
"totalDevices": len(device_completions),
}
return {
"id": 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),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"safeToRemove": safe,
"fullyReplicatedOn": len(fully_replicated),
"totalRemoteDevices": len(device_completions),
"devices": device_completions,
}
+85 -27
View File
@@ -3,47 +3,90 @@
from pydantic import BaseModel, ConfigDict, Field
class EmptyInput(BaseModel):
# ---------------------------------------------------------------------------
# Read-oriented base models (include concise toggle for token efficiency)
# ---------------------------------------------------------------------------
class ReadParams(BaseModel):
"""Base for read-only tools — includes output-format flag."""
model_config = ConfigDict(extra="forbid")
instance: str | None = Field(
None, description="Instance name. Omit if only one instance is configured."
)
concise: bool = Field(
True,
description="Compact output (default). Set false for full details.",
)
class FolderInput(BaseModel):
class FolderReadParams(ReadParams):
"""Read tool that targets a single folder."""
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):
class DeviceReadParams(ReadParams):
"""Read tool that targets a single device."""
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):
class FolderDeviceReadParams(ReadParams):
"""Read tool targeting a folder + device pair."""
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):
# ---------------------------------------------------------------------------
# Write-oriented models (no concise flag — output is always minimal)
# ---------------------------------------------------------------------------
class WriteParams(BaseModel):
"""Base for write/mutating tools."""
model_config = ConfigDict(extra="forbid")
instance: str | None = Field(
None, description="Instance name. Omit if only one instance is configured."
)
class FolderWriteParams(WriteParams):
"""Write tool that targets a single folder."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Syncthing folder ID to pause/resume", min_length=1
..., description="Syncthing folder ID", min_length=1
)
instance: str | None = Field(None, description="Instance name")
class AcceptDeviceInput(BaseModel):
class DeviceWriteParams(WriteParams):
"""Write tool that targets a single device."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(
..., description="Syncthing device ID", min_length=1
)
# ---------------------------------------------------------------------------
# Specialised input models
# ---------------------------------------------------------------------------
class AcceptDeviceInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field(
..., description="Device ID to accept (from pending list)", min_length=1
@@ -52,10 +95,9 @@ class AcceptDeviceInput(BaseModel):
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):
class AcceptFolderInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Folder ID to accept (from pending list)", min_length=1
@@ -64,10 +106,9 @@ class AcceptFolderInput(BaseModel):
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):
class RejectFolderInput(WriteParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(
..., description="Folder ID to reject", min_length=1
@@ -76,32 +117,31 @@ class RejectFolderInput(BaseModel):
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):
class SetIgnoresInput(WriteParams):
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):
class SetDefaultIgnoresInput(WriteParams):
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 ---
# ---------------------------------------------------------------------------
# File-level query models
# ---------------------------------------------------------------------------
class BrowseFolderInput(BaseModel):
class BrowseFolderInput(ReadParams):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
prefix: str | None = Field(
@@ -113,21 +153,39 @@ class BrowseFolderInput(BaseModel):
description="How many directory levels deep to return (default: 1).",
ge=0,
)
instance: str | None = Field(None, description="Instance name")
class FileInfoInput(BaseModel):
class FileInfoInput(ReadParams):
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):
class FolderNeedInput(ReadParams):
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")
class RemoteNeedInput(ReadParams):
"""Query files a remote device still needs for a folder."""
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="Remote device 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)
# ---------------------------------------------------------------------------
# Backward-compatible aliases (referenced by existing tests)
# ---------------------------------------------------------------------------
EmptyInput = ReadParams
FolderInput = FolderReadParams
DeviceInput = DeviceReadParams
PauseFolderInput = FolderWriteParams
FolderDeviceInput = FolderDeviceReadParams
+4 -6
View File
@@ -7,12 +7,10 @@ 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"
"""Human-readable byte size. Delegates to formatters.format_bytes."""
from syncthing_mcp.formatters import format_bytes as _fb
return _fb(n)
def load_instances() -> dict[str, SyncthingClient]:
+71 -184
View File
@@ -1,16 +1,16 @@
"""Config mutation tools: pending devices/folders, ignores, accept/reject."""
import json
from syncthing_mcp.formatters import fmt, truncate
from syncthing_mcp.models import (
AcceptDeviceInput,
AcceptFolderInput,
DeviceInput,
EmptyInput,
FolderInput,
DeviceWriteParams,
FolderReadParams,
ReadParams,
RejectFolderInput,
SetDefaultIgnoresInput,
SetIgnoresInput,
WriteParams,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
@@ -31,18 +31,14 @@ from syncthing_mcp.server import mcp
"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.
"""
async def syncthing_pending_devices(params: ReadParams) -> str:
"""Remote devices that tried to connect but are not yet configured."""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices")
return json.dumps(
return fmt(
{"instance": client.name, "pendingDevices": pending},
indent=2,
concise=params.concise,
)
except Exception as e:
return handle_error_global(e)
@@ -58,18 +54,14 @@ async def syncthing_pending_devices(params: EmptyInput) -> str:
"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.
"""
async def syncthing_pending_folders(params: ReadParams) -> str:
"""Folders that remote devices have offered to share but are not yet accepted."""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/folders")
return json.dumps(
return fmt(
{"instance": client.name, "pendingFolders": pending},
indent=2,
concise=params.concise,
)
except Exception as e:
return handle_error_global(e)
@@ -86,17 +78,7 @@ async def syncthing_pending_folders(params: EmptyInput) -> str:
},
)
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.
"""
"""Accept a pending device by adding it to the Syncthing configuration."""
try:
client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices")
@@ -109,16 +91,12 @@ async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
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,
)
return fmt({
"status": "accepted",
"deviceID": params.device_id[:8],
"name": name,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -133,33 +111,19 @@ async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
"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.
"""
async def syncthing_reject_device(params: DeviceWriteParams) -> str:
"""Dismiss a pending device connection request."""
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,
)
return fmt({
"status": "rejected",
"deviceID": params.device_id[:8],
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -175,25 +139,13 @@ async def syncthing_reject_device(params: DeviceInput) -> str:
},
)
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.
"""
"""Accept a pending folder share offer. Uses default folder config as template."""
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."}
)
return fmt({"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)
@@ -210,21 +162,13 @@ async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
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,
)
return fmt({
"status": "accepted",
"folder": params.folder_id,
"label": label,
"path": new_folder.get("path", "(default)"),
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -240,31 +184,18 @@ async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
},
)
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.
"""
"""Dismiss a pending folder share offer."""
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,
)
return fmt({
"status": "rejected",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -284,29 +215,21 @@ async def syncthing_reject_folder(params: RejectFolderInput) -> str:
"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.
"""
async def syncthing_get_ignores(params: FolderReadParams) -> str:
"""Get the .stignore patterns for a folder."""
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,
)
data = {
"folder": params.folder_id,
"instance": client.name,
"patterns": result.get("ignore", []) or [],
}
if not params.concise:
data["expanded"] = result.get("expanded", []) or []
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -322,17 +245,7 @@ async def syncthing_get_ignores(params: FolderInput) -> str:
},
)
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.
"""
"""Set .stignore patterns for a folder. Replaces all existing patterns."""
try:
client = get_instance(params.instance)
await client._post(
@@ -340,17 +253,12 @@ async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
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,
)
return fmt({
"status": "updated",
"folder": params.folder_id,
"instance": client.name,
"count": len(params.patterns),
})
except Exception as e:
return handle_error_global(e)
@@ -365,22 +273,15 @@ async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
"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.
"""
async def syncthing_get_default_ignores(params: ReadParams) -> str:
"""Default ignore patterns applied to newly created folders."""
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,
)
return fmt({
"instance": client.name,
"lines": result.get("lines", []) or [],
}, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -396,31 +297,17 @@ async def syncthing_get_default_ignores(params: EmptyInput) -> str:
},
)
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.
"""
"""Set the default ignore patterns for newly created folders."""
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,
)
return fmt({
"status": "updated",
"instance": client.name,
"count": len(params.lines),
})
except Exception as e:
return handle_error_global(e)
+74 -76
View File
@@ -1,13 +1,10 @@
"""Device completion and connection tools."""
"""Device listing, completion, connection, and stats tools."""
import json
from typing import Any
from syncthing_mcp.models import DeviceInput, EmptyInput
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
)
from syncthing_mcp.formatters import fmt, format_bytes, format_connection, format_device, truncate
from syncthing_mcp.models import DeviceReadParams, ReadParams
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
@@ -21,36 +18,24 @@ from syncthing_mcp.server import mcp
"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.
"""
async def syncthing_list_devices(params: ReadParams) -> str:
"""All configured devices with connection status and last seen time."""
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),
}
result = [
format_device(
dev,
conn_data.get(dev["deviceID"]),
stats.get(dev["deviceID"]),
concise=params.concise,
)
return json.dumps(result, indent=2)
for dev in config.get("devices", [])
]
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -65,34 +50,26 @@ async def syncthing_list_devices(params: EmptyInput) -> str:
"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.
"""
async def syncthing_device_completion(params: DeviceReadParams) -> str:
"""Aggregated sync completion for a remote device across all shared folders."""
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,
)
data: dict[str, Any] = {
"device": params.device_id[:8] if params.concise else params.device_id,
"instance": client.name,
"completion": round(comp.get("completion", 0), 2),
"needSize": format_bytes(comp.get("needBytes", 0)),
"remoteState": comp.get("remoteState", "unknown"),
}
if not params.concise:
data["globalBytes"] = comp.get("globalBytes", 0)
data["globalSize"] = format_bytes(comp.get("globalBytes", 0))
data["needBytes"] = comp.get("needBytes", 0)
data["needItems"] = comp.get("needItems", 0)
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -107,13 +84,8 @@ async def syncthing_device_completion(params: DeviceInput) -> str:
"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.
"""
async def syncthing_connections(params: ReadParams) -> str:
"""Current connection details for all devices."""
try:
client = get_instance(params.instance)
connections = await client._get("/rest/system/connections")
@@ -122,21 +94,47 @@ async def syncthing_connections(params: EmptyInput) -> str:
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),
}
result = [
format_connection(
did, conn, devices_map.get(did, did[:8]), concise=params.concise,
)
return json.dumps(result, indent=2)
for did, conn in connections.get("connections", {}).items()
]
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_device_stats",
annotations={
"title": "Device Statistics",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_device_stats(params: ReadParams) -> str:
"""Per-device statistics: last seen time and connection duration."""
try:
client = get_instance(params.instance)
stats = await client._get("/rest/stats/device")
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, stat in stats.items():
entry: dict[str, Any] = {
"device": devices_map.get(did, did[:8]),
"lastSeen": stat.get("lastSeen", ""),
}
if not params.concise:
entry["deviceID"] = did
entry["lastConnectionDurationS"] = stat.get("lastConnectionDurationS", 0)
result.append(entry)
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
+209 -390
View File
@@ -1,21 +1,25 @@
"""Folder status, completion, replication, operations, and file-level query tools."""
import json
from typing import Any
from syncthing_mcp.formatters import (
fmt,
format_bytes,
format_completion,
format_folder_status,
format_replication_entry,
truncate,
)
from syncthing_mcp.models import (
BrowseFolderInput,
FileInfoInput,
FolderInput,
FolderNeedInput,
PauseFolderInput,
EmptyInput,
)
from syncthing_mcp.registry import (
format_bytes,
get_instance,
handle_error_global,
FolderReadParams,
FolderWriteParams,
ReadParams,
RemoteNeedInput,
)
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
@@ -34,48 +38,23 @@ from syncthing_mcp.server import mcp
"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.
"""
async def syncthing_folder_status(params: FolderReadParams) -> str:
"""Detailed status for a folder — file counts, bytes, sync state.
Note: expensive call on the Syncthing side. Use sparingly."""
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,
)
data: dict[str, Any] = {
"folder": params.folder_id,
"instance": client.name,
**format_folder_status(status, concise=params.concise),
}
if not params.concise:
data["lastScan"] = folder_stats.get("lastScan", "")
data["lastFile"] = folder_stats.get("lastFile", {})
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -90,19 +69,9 @@ async def syncthing_folder_status(params: FolderInput) -> str:
"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.
"""
async def syncthing_folder_completion(params: FolderReadParams) -> str:
"""Per-device replication completion % for a folder. Key tool for
determining if a folder is fully replicated before local removal."""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
@@ -117,7 +86,7 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
folder_cfg = f
break
if not folder_cfg:
return json.dumps({"error": f"Folder '{params.folder_id}' not found in config."})
return fmt({"error": f"Folder '{params.folder_id}' not found in config."})
devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
@@ -128,54 +97,38 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
did = dev.get("deviceID", "")
if did == my_id:
continue
connected = conn_data.get(did, {}).get("connected", False)
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"),
}
)
completions.append(format_completion(
comp,
devices_map.get(did, did[:8]),
connected=connected,
concise=params.concise,
))
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.",
}
)
completions.append({
"device": devices_map.get(did, did[:8]),
"connected": False,
"completion": None,
"error": "unreachable",
})
fully_replicated_count = sum(
1
for c in completions
fully = 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,
)
return fmt({
"folder": params.folder_id,
"label": folder_cfg.get("label", params.folder_id),
"instance": client.name,
"remoteDevices": len(completions),
"fullyReplicated": fully,
"devices": completions,
}, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -190,22 +143,9 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
"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.
"""
async def syncthing_replication_report(params: ReadParams) -> str:
"""Replication analysis for ALL folders. Shows safe-to-remove flag and
reclaimable space. Primary tool for disk-space cleanup decisions."""
try:
client = get_instance(params.instance)
config = await client._get("/rest/config")
@@ -224,19 +164,12 @@ async def syncthing_replication_report(params: EmptyInput) -> str:
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."})
report.append({"id": fid, "label": folder_cfg.get("label", fid), "error": "unreachable"})
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
]
@@ -249,72 +182,42 @@ async def syncthing_replication_report(params: EmptyInput) -> str:
"/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),
}
)
device_completions.append(format_completion(
comp,
devices_map.get(did, did[:8]),
connected=connected,
concise=params.concise,
))
except Exception:
device_completions.append(
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": connected,
"completion": None,
"remoteState": "unknown",
}
)
device_completions.append({
"device": 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,
}
entry = format_replication_entry(
folder_cfg, fstatus, device_completions, concise=params.concise,
)
safe = entry.get("safe") if params.concise else entry.get("safeToRemove")
if safe:
total_reclaimable += fstatus.get("localBytes", 0)
report.append(entry)
report.sort(key=lambda x: (-int(x.get("safeToRemove", False)), -x.get("localBytes", 0)))
report.sort(key=lambda x: (
-int(x.get("safe", x.get("safeToRemove", False)) or False),
-x.get("localBytes", 0) if "localBytes" in x else 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,
return fmt({
"instance": client.name,
"summary": {
"total": len(report),
"safe": sum(1 for r in report if r.get("safe") or r.get("safeToRemove")),
"reclaimable": format_bytes(total_reclaimable),
},
indent=2,
)
"folders": report,
}, concise=params.concise)
except Exception as e:
return handle_error_global(e)
@@ -334,36 +237,19 @@ async def syncthing_replication_report(params: EmptyInput) -> str:
"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.
"""
async def syncthing_pause_folder(params: FolderWriteParams) -> str:
"""Pause syncing for a folder. Does NOT delete data — only stops sync
so you can safely remove the local copy without propagating deletions."""
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,
)
return fmt({
"status": "paused",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -378,40 +264,22 @@ async def syncthing_pause_folder(params: PauseFolderInput) -> str:
"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.
"""
async def syncthing_resume_folder(params: FolderWriteParams) -> str:
"""Resume syncing for a paused folder. WARNING: if local data was deleted
while paused, behaviour depends on folder type (sendreceive may propagate
deletions; receiveonly will re-download)."""
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,
)
return fmt({
"status": "resumed",
"folder": params.folder_id,
"type": folder_type,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -426,29 +294,16 @@ async def syncthing_resume_folder(params: PauseFolderInput) -> str:
"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.
"""
async def syncthing_scan_folder(params: FolderWriteParams) -> str:
"""Trigger an immediate rescan of a folder to refresh its status."""
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,
)
return fmt({
"status": "scan_requested",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -463,36 +318,26 @@ async def syncthing_scan_folder(params: FolderInput) -> str:
"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.
"""
async def syncthing_folder_errors(params: FolderReadParams) -> str:
"""Current sync errors for a specific folder."""
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,
)
error_list = errors.get("errors", []) or []
return truncate(fmt({
"folder": params.folder_id,
"instance": client.name,
"count": len(error_list),
"errors": error_list,
}, concise=params.concise))
except Exception as e:
return handle_error_global(e)
# =====================================================================
# New: File-level queries
# File-level queries
# =====================================================================
@@ -507,18 +352,7 @@ async def syncthing_folder_errors(params: FolderInput) -> str:
},
)
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.
"""
"""Browse folder contents at a path prefix (directory listing from DB)."""
try:
client = get_instance(params.instance)
query: dict[str, str] = {"folder": params.folder_id}
@@ -527,15 +361,12 @@ async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
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,
)
return truncate(fmt({
"folder": params.folder_id,
"instance": client.name,
"prefix": params.prefix or "",
"entries": result,
}, concise=params.concise))
except Exception as e:
return handle_error_global(e)
@@ -551,40 +382,37 @@ async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
},
)
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.
"""
"""Detailed info about a file — versions, availability, modification time."""
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
if params.concise:
g = result.get("global", {})
l = result.get("local", {})
return fmt({
"folder": params.folder_id,
"file": params.file_path,
"instance": client.name,
"globalSize": format_bytes(g.get("size", 0)) if g else None,
"localSize": format_bytes(l.get("size", 0)) if l else None,
"availability": result.get("availability"),
})
# Detailed mode — 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,
)
return fmt({
"folder": params.folder_id,
"file": params.file_path,
"instance": client.name,
"availability": result.get("availability"),
"global": result.get("global"),
"local": result.get("local"),
}, concise=False)
except Exception as e:
return handle_error_global(e)
@@ -600,16 +428,7 @@ async def syncthing_file_info(params: FileInfoInput) -> str:
},
)
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.
"""
"""Files this folder still needs — items that are out of sync locally."""
try:
client = get_instance(params.instance)
result = await client._get(
@@ -620,24 +439,59 @@ async def syncthing_folder_need(params: FolderNeedInput) -> str:
"perpage": str(params.per_page),
},
)
return json.dumps(
{
return truncate(fmt({
"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", []),
}, concise=params.concise))
except Exception as e:
return handle_error_global(e)
@mcp.tool(
name="syncthing_remote_need",
annotations={
"title": "Remote Need (What a Device Needs from Us)",
"readOnlyHint": True,
"destructiveHint": False,
"idempotentHint": True,
"openWorldHint": False,
},
)
async def syncthing_remote_need(params: RemoteNeedInput) -> str:
"""Files a remote device still needs from us for a specific folder.
Useful for debugging why sync to a device is incomplete."""
try:
client = get_instance(params.instance)
result = await client._get(
"/rest/db/remoteneed",
params={
"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", []),
"device": params.device_id,
"page": str(params.page),
"perpage": str(params.per_page),
},
indent=2,
)
return truncate(fmt({
"folder": params.folder_id,
"device": params.device_id[:8],
"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", []),
}, concise=params.concise))
except Exception as e:
return handle_error_global(e)
# =====================================================================
# New: Conflict resolution
# Conflict resolution
# =====================================================================
@@ -651,34 +505,16 @@ async def syncthing_folder_need(params: FolderNeedInput) -> str:
"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.
"""
async def syncthing_override_folder(params: FolderWriteParams) -> str:
"""Override remote changes on a send-only folder (make local authoritative)."""
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,
)
return fmt({
"status": "override_requested",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
@@ -693,32 +529,15 @@ async def syncthing_override_folder(params: FolderInput) -> str:
"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.
"""
async def syncthing_revert_folder(params: FolderWriteParams) -> str:
"""Revert local changes on a receive-only folder (pull remote state)."""
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,
)
return fmt({
"status": "revert_requested",
"folder": params.folder_id,
"instance": client.name,
})
except Exception as e:
return handle_error_global(e)
+32 -42
View File
@@ -1,11 +1,10 @@
"""Tools for instance management and listing folders (config-level)."""
import json
from typing import Any
from syncthing_mcp.models import EmptyInput
from syncthing_mcp.formatters import fmt, format_folder
from syncthing_mcp.models import ReadParams
from syncthing_mcp.registry import (
format_bytes,
get_all_instances,
get_instance,
handle_error_global,
@@ -23,12 +22,8 @@ from syncthing_mcp.server import mcp
"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.
"""
async def syncthing_list_instances(params: ReadParams) -> str:
"""List all configured Syncthing instances and probe their availability."""
results = []
for name, client in get_all_instances().items():
entry: dict[str, Any] = {"name": name, "url": client.url}
@@ -42,20 +37,19 @@ async def syncthing_list_instances(params: EmptyInput) -> str:
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", [])),
}
)
entry.update({
"available": True,
"deviceName": my_name,
"version": version.get("version"),
"folders": len(config.get("folders", [])),
"devices": len(config.get("devices", [])),
})
if not params.concise:
entry["myID"] = my_id
except Exception as exc:
entry.update({"available": False, "error": str(exc)})
results.append(entry)
return json.dumps(results, indent=2)
return fmt(results, concise=params.concise)
@mcp.tool(
@@ -68,37 +62,33 @@ async def syncthing_list_instances(params: EmptyInput) -> str:
"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.
"""
async def syncthing_list_folders(params: ReadParams) -> str:
"""All configured folders with labels, types, and device counts."""
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(
{
if params.concise:
result = [format_folder(f, concise=True) for f in folders]
else:
devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", [])
}
result = []
for f in folders:
shared = [
{"deviceID": d.get("deviceID", ""), "name": devices_map.get(d.get("deviceID", ""), "")}
for d in f.get("devices", [])
]
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)
})
return fmt(result, concise=params.concise)
except Exception as e:
return handle_error_global(e)
+111 -191
View File
@@ -1,16 +1,12 @@
"""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.formatters import fmt, format_bytes, truncate
from syncthing_mcp.models import ReadParams, WriteParams
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp
@@ -24,12 +20,8 @@ from syncthing_mcp.server import mcp
"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.
"""
async def syncthing_system_status(params: ReadParams) -> str:
"""Device ID, name, uptime, version, and folder/device counts."""
try:
client = get_instance(params.instance)
status = await client._get("/rest/system/status")
@@ -41,20 +33,19 @@ async def syncthing_system_status(params: EmptyInput) -> str:
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,
)
data: dict[str, Any] = {
"instance": client.name,
"myID": my_id[:8] if params.concise else my_id,
"deviceName": my_name,
"uptime": status.get("uptime"),
"version": version.get("version"),
"folders": len(config.get("folders", [])),
"devices": len(config.get("devices", [])),
}
if not params.concise:
data["os"] = version.get("os")
data["arch"] = version.get("arch")
return fmt(data, concise=params.concise)
except Exception as e:
if isinstance(e, ValueError):
return handle_error_global(e)
@@ -74,24 +65,18 @@ async def syncthing_system_status(params: EmptyInput) -> str:
"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'.
"""
async def syncthing_system_errors(params: ReadParams) -> str:
"""Recent system errors and warnings."""
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,
)
data: dict[str, Any] = {
"instance": client.name,
"count": len(errors),
"errors": errors,
}
return truncate(fmt(data, concise=params.concise))
except Exception as e:
return handle_error_global(e)
@@ -106,23 +91,12 @@ async def syncthing_system_errors(params: EmptyInput) -> str:
"openWorldHint": False,
},
)
async def syncthing_clear_errors(params: EmptyInput) -> str:
"""Clear the system error log.
Returns:
str: Confirmation message.
"""
async def syncthing_clear_errors(params: WriteParams) -> str:
"""Clear the system error log."""
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,
)
return fmt({"status": "cleared", "instance": client.name})
except Exception as e:
return handle_error_global(e)
@@ -137,25 +111,18 @@ async def syncthing_clear_errors(params: EmptyInput) -> str:
"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'.
"""
async def syncthing_system_log(params: ReadParams) -> str:
"""Recent system log entries."""
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,
)
data: dict[str, Any] = {
"instance": client.name,
"count": len(messages),
"messages": messages,
}
return truncate(fmt(data, concise=params.concise))
except Exception as e:
return handle_error_global(e)
@@ -170,14 +137,8 @@ async def syncthing_system_log(params: EmptyInput) -> str:
"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.
"""
async def syncthing_recent_changes(params: ReadParams) -> str:
"""Recent file change events (local and remote) across all folders."""
try:
client = get_instance(params.instance)
events = await client._get(
@@ -190,14 +151,22 @@ async def syncthing_recent_changes(params: EmptyInput) -> str:
)
if not isinstance(events, list):
events = []
return json.dumps(
{
"instance": client.name,
"eventCount": len(events),
"events": events,
},
indent=2,
)
if params.concise:
events = [
{
"type": e.get("type", "")[:6], # "Local" or "Remote"
"folder": e.get("data", {}).get("folderID", ""),
"path": e.get("data", {}).get("path", ""),
"action": e.get("data", {}).get("action", ""),
}
for e in events
]
data: dict[str, Any] = {
"instance": client.name,
"count": len(events),
"events": events,
}
return truncate(fmt(data, concise=params.concise))
except Exception as e:
return handle_error_global(e)
@@ -212,22 +181,15 @@ async def syncthing_recent_changes(params: EmptyInput) -> str:
"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.
"""
async def syncthing_restart_required(params: ReadParams) -> str:
"""Check if Syncthing requires a restart for config changes to take effect."""
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,
)
return fmt({
"instance": client.name,
"restartRequired": result.get("requiresRestart", False),
})
except Exception as e:
return handle_error_global(e)
@@ -242,31 +204,19 @@ async def syncthing_restart_required(params: EmptyInput) -> str:
"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.
"""
async def syncthing_restart(params: WriteParams) -> str:
"""Restart the Syncthing service. Temporarily stops all sync activity."""
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,
)
return fmt({
"status": "restart_initiated",
"instance": client.name,
"message": f"Syncthing '{client.name}' is restarting.",
})
except Exception as e:
return handle_error_global(e)
@@ -281,38 +231,26 @@ async def syncthing_restart(params: EmptyInput) -> str:
"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.
"""
async def syncthing_check_upgrade(params: ReadParams) -> str:
"""Check if a newer version of Syncthing 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,
)
return fmt({
"instance": client.name,
"running": version.get("version"),
"latest": upgrade.get("latest"),
"newer": upgrade.get("newer", False),
}, concise=params.concise)
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,
)
return fmt({
"instance": client.name,
"running": version.get("version"),
"upgradeCheck": "unavailable",
})
raise
except Exception as e:
return handle_error_global(e)
@@ -328,16 +266,9 @@ async def syncthing_check_upgrade(params: EmptyInput) -> str:
"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.
"""
async def syncthing_health_summary(params: ReadParams) -> str:
"""Single-call health overview: system status, folder states, device
connectivity, errors, and pending items. Start here for quick triage."""
try:
client = get_instance(params.instance)
@@ -368,31 +299,25 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
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"
folder_health.append({"id": fid, "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))
entry: dict[str, Any] = {"id": fid, "state": state}
if state in ("syncing", "sync-preparing"):
syncing_count += 1
entry["needSize"] = format_bytes(fstatus.get("needBytes", 0))
elif state == "error":
error_folders += 1
folder_health.append(entry)
except Exception:
entry["state"] = "unreachable"
error_folders += 1
folder_health.append(entry)
folder_health.append({"id": fid, "state": "unreachable"})
alerts: list[str] = []
error_list = sys_errors.get("errors", []) or []
@@ -406,13 +331,13 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
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")
alerts.append(f"{syncing_count} folder(s) 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)")
alerts.append(f"{num_pending_dev} pending device(s)")
if num_pending_fld > 0:
alerts.append(f"{num_pending_fld} pending folder offer(s)")
alerts.append(f"{num_pending_fld} pending folder(s)")
if error_folders > 0 or len(error_list) > 0:
overall = "error"
@@ -421,30 +346,25 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
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,
data: dict[str, Any] = {
"instance": client.name,
"status": overall,
"uptime": sys_status.get("uptime"),
"summary": {
"folders": len(folders),
"idle": sum(1 for f in folder_health if f.get("state") == "idle"),
"syncing": syncing_count,
"paused": paused_count,
"errors": error_folders,
"devicesOnline": online_count,
"devicesOffline": offline_count,
"pendingDevices": num_pending_dev,
"pendingFolders": num_pending_fld,
},
indent=2,
)
"alerts": alerts,
}
if not params.concise:
data["folders"] = folder_health
return fmt(data, concise=params.concise)
except Exception as e:
return handle_error_global(e)