From 41f1018477e09b3930177a89f1418ff5d39f424e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Feb 2026 03:44:48 +0000 Subject: [PATCH] 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 --- .env.example | 12 +- README.md | 161 +++++-- SKILL.md | 142 +++++++ docker-compose.tunnel.yml | 44 ++ pyproject.toml | 6 +- src/syncthing_mcp/__init__.py | 2 +- src/syncthing_mcp/formatters.py | 265 ++++++++++++ src/syncthing_mcp/models.py | 112 +++-- src/syncthing_mcp/registry.py | 10 +- src/syncthing_mcp/tools/config.py | 255 ++++-------- src/syncthing_mcp/tools/devices.py | 150 ++++--- src/syncthing_mcp/tools/folders.py | 599 ++++++++++----------------- src/syncthing_mcp/tools/instances.py | 74 ++-- src/syncthing_mcp/tools/system.py | 302 +++++--------- tests/test_tools_config.py | 2 +- tests/test_tools_devices.py | 13 +- tests/test_tools_folders.py | 17 +- tests/test_tools_system.py | 15 +- 18 files changed, 1194 insertions(+), 987 deletions(-) create mode 100644 SKILL.md create mode 100644 docker-compose.tunnel.yml create mode 100644 src/syncthing_mcp/formatters.py diff --git a/.env.example b/.env.example index 4861ce6..76c3934 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,11 @@ -DOMAIN=example.com -MCP_AUTH_TOKEN=CHANGEME +# --- Syncthing instances --- SYNCTHING_INSTANCES={"tn-sb":{"url":"http://tn-sb.gen4.cc:8384","api_key":"CHANGEME"},"tn-mr2":{"url":"http://tn-mr2.gen4.cc:8384","api_key":"CHANGEME"},"p-mba":{"url":"http://p-mba.gen4.cc:8384","api_key":"CHANGEME"},"p-mbp":{"url":"http://p-mbp.gen4.cc:8384","api_key":"CHANGEME"},"mini":{"url":"http://mini.gen4.cc:8384","api_key":"CHANGEME"}} + +# --- MCP HTTP transport (streamable-http) --- +MCP_AUTH_TOKEN=CHANGEME + +# --- Traefik reverse proxy (docker-compose.yml) --- +DOMAIN=example.com + +# --- Cloudflare Tunnel (docker-compose.tunnel.yml) --- +# CLOUDFLARE_TUNNEL_TOKEN=eyJ... diff --git a/README.md b/README.md index 6f7dd5b..ce93f59 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,16 @@ An MCP (Model Context Protocol) server for [Syncthing](https://syncthing.net/) Built to give AI assistants (Claude, etc.) read and control access to Syncthing's REST API, with a focus on **replication awareness**: understanding which folders are fully replicated across devices so you can confidently reclaim local disk space. -## Why +## Key Features -Syncthing syncs folders across devices, but its web UI doesn't make it easy to answer a simple question: *"Which datasets on this machine are safely backed up elsewhere, and how much space would I recover by removing them locally?"* +- **Token-efficient output** — compact JSON by default; `concise=false` for full details +- **Multi-instance** — manage multiple Syncthing nodes from a single server +- **Replication analysis** — safe-to-remove flags and reclaimable space calculation +- **Syncthing v2.x compatible** — tested against v2.0.x REST API +- **HTTP transport** — Streamable HTTP with bearer-token auth, Cloudflare Tunnel support +- **SKILL.md** — LLM skill guide for optimal tool usage -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 (36 total) +## Tools (39 total) ### Instance Management @@ -23,30 +26,31 @@ This MCP server exposes that information as structured tool calls, so you can as | Tool | Description | Mutating | |------|-------------|----------| | `syncthing_system_status` | Device ID, name, uptime, version | No | -| `syncthing_list_folders` | All folders with paths, types, and shared device lists | No | -| `syncthing_list_devices` | All devices with connection status and last seen | No | -| `syncthing_connections` | Active connection details (addresses, crypto, throughput) | No | +| `syncthing_list_folders` | All folders with types and device counts | No | +| `syncthing_list_devices` | All devices with connection status | No | +| `syncthing_connections` | Active connection details | No | +| `syncthing_device_stats` | Per-device statistics (last seen, duration) | No | | `syncthing_system_errors` | Recent system errors and warnings | No | | `syncthing_clear_errors` | Clear the system error log | Yes | -| `syncthing_system_log` | Recent log entries with timestamps and levels | No | +| `syncthing_system_log` | Recent log entries | 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 | +| `syncthing_health_summary` | Single-call health overview with alerts | No | +| `syncthing_check_upgrade` | Check for newer Syncthing version | No | ### Folder Status & Replication | Tool | Description | Mutating | |------|-------------|----------| -| `syncthing_folder_status` | Detailed status for a single folder (files, bytes, sync state) | No | +| `syncthing_folder_status` | Detailed folder metrics (expensive call) | No | | `syncthing_folder_completion` | Per-device completion % for a folder | No | -| `syncthing_replication_report` | Analyses all folders, flags safe-to-remove, calculates reclaimable space | No | +| `syncthing_replication_report` | All folders: safe-to-remove + reclaimable space | No | | `syncthing_folder_errors` | Current sync errors for a folder | No | ### Device Status | Tool | Description | Mutating | |------|-------------|----------| -| `syncthing_device_completion` | Aggregated completion for a device across all shared folders | No | +| `syncthing_device_completion` | Aggregated completion for a device | No | ### Folder Operations @@ -60,16 +64,17 @@ This MCP server exposes that information as structured tool calls, so you can as | 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 | +| `syncthing_browse_folder` | Browse folder contents (directory listing from DB) | No | +| `syncthing_file_info` | Detailed info about a specific file | No | +| `syncthing_folder_need` | Out-of-sync files this folder needs (paginated) | No | +| `syncthing_remote_need` | Files a remote device needs from us (paginated) | 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 | +| `syncthing_override_folder` | Override remote changes (send-only folder) | Yes | +| `syncthing_revert_folder` | Revert local changes (receive-only folder) | Yes | ### Config Mutation: Pending Devices & Folders @@ -77,9 +82,9 @@ This MCP server exposes that information as structured tool calls, so you can as |------|-------------|----------| | `syncthing_pending_devices` | List pending device connection requests | No | | `syncthing_pending_folders` | List pending folder share offers | No | -| `syncthing_accept_device` | Accept a pending device (adds to config with defaults) | Yes | +| `syncthing_accept_device` | Accept a pending device | Yes | | `syncthing_reject_device` | Dismiss a pending device request | Yes | -| `syncthing_accept_folder` | Accept a pending folder offer (uses folder defaults template) | Yes | +| `syncthing_accept_folder` | Accept a pending folder offer | Yes | | `syncthing_reject_folder` | Dismiss a pending folder offer | Yes | ### Config Mutation: Restart & Ignore Patterns @@ -89,9 +94,24 @@ This MCP server exposes that information as structured tool calls, so you can as | `syncthing_restart_required` | Check if config changes require a restart | No | | `syncthing_restart` | Restart the Syncthing service | Yes | | `syncthing_get_ignores` | Get .stignore patterns for a folder | No | -| `syncthing_set_ignores` | Set .stignore patterns for a folder (replaces all) | Yes | -| `syncthing_get_default_ignores` | Get default ignore patterns for new folders | No | -| `syncthing_set_default_ignores` | Set default ignore patterns for new folders | Yes | +| `syncthing_set_ignores` | Set .stignore patterns for a folder | Yes | +| `syncthing_get_default_ignores` | Get default ignore patterns | No | +| `syncthing_set_default_ignores` | Set default ignore patterns | Yes | + +## Token Efficiency + +All read tools default to `concise=true`, producing compact JSON with minimal fields and +short device IDs. Set `concise=false` for full details when debugging. + +| Mode | Output style | Use case | +|------|-------------|----------| +| `concise=true` (default) | Compact JSON, short IDs, essential fields | Normal operation | +| `concise=false` | Pretty JSON, full device IDs, all fields | Debugging, raw data | + +Large responses are automatically truncated at 25,000 characters with guidance to use +pagination or filters. + +See [SKILL.md](SKILL.md) for the complete LLM skill guide. ## Project Structure @@ -99,20 +119,25 @@ This MCP server exposes that information as structured tool calls, so you can as syncthing-mcp/ ├── src/syncthing_mcp/ │ ├── __init__.py # Package version -│ ├── __main__.py # Entry point +│ ├── __main__.py # Entry point (stdio + HTTP transport) +│ ├── auth.py # Bearer token middleware │ ├── client.py # SyncthingClient (HTTP methods + error handling) -│ ├── models.py # Pydantic input models +│ ├── formatters.py # Token-efficient formatting layer +│ ├── models.py # Pydantic input models (ReadParams / WriteParams) │ ├── 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 +│ ├── folders.py # Folder status, completion, replication, file queries +│ ├── devices.py # Device listing, completion, connections, stats │ ├── config.py # Pending accept/reject, ignore patterns │ └── instances.py # Instance listing, folder listing -├── tests/ # 96 tests with respx HTTP mocking +├── tests/ # Tests with respx HTTP mocking +├── SKILL.md # LLM skill guide ├── pyproject.toml -└── README.md +├── Dockerfile +├── docker-compose.yml # Traefik reverse proxy (HTTPS/ACME) +└── docker-compose.tunnel.yml # Cloudflare Tunnel (zero-trust) ``` ## Multi-Instance Support @@ -150,7 +175,7 @@ Every tool accepts an optional `instance` parameter to target a specific node. W ## Safe Removal Workflow -1. Run `syncthing_replication_report` — review which folders show `safeToRemove: true` +1. Run `syncthing_replication_report` — review which folders show `safe: true` 2. Confirm the fully-replicated remote device(s) are the ones you expect 3. `syncthing_pause_folder` — stops Syncthing from propagating local changes 4. Delete the local data outside of Syncthing @@ -158,7 +183,7 @@ Every tool accepts an optional `instance` parameter to target a specific node. W > **Important:** Always pause before deleting. In a `sendreceive` folder, deleting files without pausing will propagate the deletion to all connected devices. -The `safeToRemove` flag requires: at least one remote device at 100% completion with `remoteState: valid`, the folder in `idle` state, and the folder not paused. This is deliberately conservative. +The `safe` flag requires: at least one remote device at 100% completion with `remoteState: valid`, the folder in `idle` state, and the folder not paused. This is deliberately conservative. ## Setup @@ -180,12 +205,8 @@ uv sync Open the Syncthing web UI → Actions → Settings → API Key. -Alternatively, find it in your Syncthing config file under ``. - ### Configure Claude Desktop (single instance) -Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS): - ```json { "mcpServers": { @@ -204,32 +225,80 @@ Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/cla } ``` -### Running Tests +## HTTP Transport + +### Streamable HTTP (direct) + +```bash +MCP_TRANSPORT=streamable-http MCP_AUTH_TOKEN=secret MCP_PORT=8000 syncthing-mcp +``` + +### Docker + Traefik (HTTPS with ACME/Let's Encrypt) + +```bash +cp .env.example .env # edit API keys and DOMAIN +docker compose up -d +``` + +This deploys behind Traefik with automatic Let's Encrypt TLS certificates. +The MCP endpoint is available at `https://syncthing-mcp./mcp`. + +### Docker + Cloudflare Tunnel (zero-trust, no open ports) + +```bash +cp .env.example .env # edit API keys and CLOUDFLARE_TUNNEL_TOKEN +docker compose -f docker-compose.tunnel.yml up -d +``` + +Create a tunnel at [Cloudflare Zero Trust](https://one.dash.cloudflare.com) → Networks → Tunnels. +Point the tunnel's public hostname to `http://syncthing-mcp:8000`. +Bearer token auth (`MCP_AUTH_TOKEN`) secures the endpoint; `/health` is unauthenticated for probes. + +### Claude Code (remote HTTP) + +```json +{ + "mcpServers": { + "syncthing": { + "type": "streamable-http", + "url": "https://syncthing-mcp.example.com/mcp", + "headers": { + "Authorization": "Bearer YOUR_MCP_AUTH_TOKEN" + } + } + } +} +``` + +## Running Tests ```bash uv sync uv run pytest -v ``` -### Environment Variables +## Environment Variables | Variable | Required | Default | Description | |----------|----------|---------|-------------| | `SYNCTHING_API_KEY` | Yes* | — | API key (single-instance mode) | | `SYNCTHING_URL` | No | `http://localhost:8384` | Base URL (single-instance mode) | -| `SYNCTHING_INSTANCES` | No | — | JSON object for multi-instance mode (overrides the above) | +| `SYNCTHING_INSTANCES` | No | — | JSON object for multi-instance mode | +| `MCP_TRANSPORT` | No | `stdio` | Transport: `stdio` or `streamable-http` | +| `MCP_HOST` | No | `0.0.0.0` | HTTP listen host | +| `MCP_PORT` | No | `8000` | HTTP listen port | +| `MCP_AUTH_TOKEN` | No | — | Bearer token for HTTP transport | +| `DOMAIN` | No | — | FQDN for Traefik TLS (docker-compose.yml) | +| `CLOUDFLARE_TUNNEL_TOKEN` | No | — | Tunnel token (docker-compose.tunnel.yml) | \* Required unless `SYNCTHING_INSTANCES` is set. ## 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. -- The replication report makes one `/rest/db/completion` call per remote device per folder. On setups with many folders and devices, this can generate significant API traffic. -- `syncthing_health_summary` calls `/rest/db/status` for each folder — equivalent cost to the replication report. - -## Contributing - -Issues and PRs welcome. +- `syncthing_folder_status` and `syncthing_replication_report` call Syncthing's `/rest/db/status` endpoint, which is expensive (high CPU/RAM on the Syncthing side). Use judiciously on low-power hardware. +- The replication report makes one `/rest/db/completion` call per remote device per folder. +- `syncthing_health_summary` calls `/rest/db/status` for each folder — equivalent cost. +- Syncthing v2.x uses SQLite (replacing LevelDB). First launch after v1→v2 migration can be lengthy. ## License diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..b3312f7 --- /dev/null +++ b/SKILL.md @@ -0,0 +1,142 @@ +--- +name: syncthing +triggers: + - syncthing + - sync + - replication + - file sync + - folders + - devices + - disk space + - safe to remove + - backup status + - sync status +--- + +# Syncthing MCP — Skill Guide + +MCP server for managing Syncthing instances. Multi-instance aware. Focus on +replication analysis and safe disk-space reclamation. + +## Token Efficiency Rules (MANDATORY) + +1. All read tools default to `concise=true` — compact JSON, short device IDs, minimal fields +2. **Start with `syncthing_health_summary`** — single-call overview, avoids multiple queries +3. Use `syncthing_list_folders` before `syncthing_folder_status` to discover folder IDs +4. Use `syncthing_replication_report` for safe-removal analysis (aggregates all folders) +5. Only set `concise=false` when debugging or when the user needs raw details +6. Avoid `syncthing_folder_status` in loops — it is expensive on the Syncthing side + +## Quick Start + +| Goal | Tool | Notes | +|------|------|-------| +| Overview / triage | `syncthing_health_summary` | Start here. Status, alerts, counts | +| List folders | `syncthing_list_folders` | Folder IDs, types, device counts | +| List devices | `syncthing_list_devices` | Connection status, addresses | +| Safe to delete? | `syncthing_replication_report` | Per-folder safe flag + reclaimable space | +| Folder deep-dive | `syncthing_folder_status` | Expensive — use sparingly | +| Per-device sync | `syncthing_folder_completion` | Completion % per remote device | +| Accept a device | `syncthing_pending_devices` → `syncthing_accept_device` | Two-step | +| Accept a folder | `syncthing_pending_folders` → `syncthing_accept_folder` | Two-step | +| Debug sync issue | `syncthing_folder_errors` + `syncthing_remote_need` | What's stuck and why | +| Check instances | `syncthing_list_instances` | Multi-instance: probe all nodes | + +## Workflows + +### Daily Health Check +1. `syncthing_health_summary` — review status and alerts +2. If alerts mention pending items → `syncthing_pending_devices` / `syncthing_pending_folders` +3. If alerts mention errors → `syncthing_system_errors` or `syncthing_folder_errors` + +### Disk Space Reclamation +1. `syncthing_replication_report` — identify folders with `safe=true` +2. Confirm reclaimable space in `summary.reclaimable` +3. For each folder to remove: `syncthing_pause_folder` → delete local data outside Syncthing +4. Optionally remove the folder from config via Syncthing web UI + +### Debugging Incomplete Sync +1. `syncthing_folder_completion` — which device is behind? +2. `syncthing_remote_need` — what files does the remote device need? +3. `syncthing_folder_errors` — any file-level errors blocking sync? +4. `syncthing_connections` — is the device actually connected? + +### Accepting New Devices/Folders +1. `syncthing_pending_devices` — review pending requests +2. `syncthing_accept_device` with optional `name` parameter +3. `syncthing_pending_folders` — review offered folders +4. `syncthing_accept_folder` with optional `path` parameter +5. `syncthing_restart_required` — check if restart needed after config changes + +### Setting Up Ignore Patterns +1. `syncthing_get_ignores` — review current patterns +2. `syncthing_set_ignores` — replace patterns (common: `*.tmp`, `.DS_Store`, `Thumbs.db`) +3. `syncthing_get_default_ignores` / `syncthing_set_default_ignores` — template for new folders + +## Tool Categories + +### Read Tools (39 total → concise by default) + +**Instance & System:** +`syncthing_list_instances`, `syncthing_system_status`, `syncthing_health_summary`, +`syncthing_system_errors`, `syncthing_system_log`, `syncthing_recent_changes`, +`syncthing_restart_required`, `syncthing_check_upgrade` + +**Folders:** +`syncthing_list_folders`, `syncthing_folder_status`, `syncthing_folder_completion`, +`syncthing_replication_report`, `syncthing_folder_errors`, `syncthing_browse_folder`, +`syncthing_file_info`, `syncthing_folder_need`, `syncthing_remote_need` + +**Devices:** +`syncthing_list_devices`, `syncthing_device_completion`, `syncthing_connections`, +`syncthing_device_stats` + +**Config (read):** +`syncthing_pending_devices`, `syncthing_pending_folders`, `syncthing_get_ignores`, +`syncthing_get_default_ignores` + +### Write Tools + +`syncthing_clear_errors`, `syncthing_restart`, `syncthing_pause_folder`, +`syncthing_resume_folder`, `syncthing_scan_folder`, `syncthing_override_folder`, +`syncthing_revert_folder`, `syncthing_accept_device`, `syncthing_reject_device`, +`syncthing_accept_folder`, `syncthing_reject_folder`, `syncthing_set_ignores`, +`syncthing_set_default_ignores` + +## Multi-Instance + +When multiple instances are configured, every tool accepts an `instance` parameter. +If omitted with a single instance, it auto-selects. With multiple instances, omitting +`instance` returns an error listing available names. + +Use `syncthing_list_instances` to discover instance names and availability. + +## Common Parameters + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `instance` | string | auto | Target instance name | +| `concise` | bool | `true` | Compact output (read tools only) | +| `folder_id` | string | required | Syncthing folder ID | +| `device_id` | string | required | Full Syncthing device ID | +| `page` / `per_page` | int | 1 / 50 | Pagination for need/remoteneed | + +## Troubleshooting + +| Error | Cause | Fix | +|-------|-------|-----| +| 401 Unauthorized | Bad API key | Check `SYNCTHING_API_KEY` or `SYNCTHING_INSTANCES` JSON | +| 403 Forbidden | API key lacks permissions | Regenerate API key in Syncthing web UI | +| Connection refused | Syncthing not running | Start Syncthing or check URL | +| Timeout | Syncthing busy or unreachable | Retry, or check network / firewall | +| "Multiple instances configured" | Missing `instance` param | Specify `instance` name | + +## Performance Notes + +- `syncthing_folder_status` and `syncthing_replication_report` call `/rest/db/status` + which is expensive on the Syncthing side (CPU + RAM). Avoid calling in tight loops. +- `syncthing_health_summary` calls `/rest/db/status` per folder — equivalent cost. +- The replication report makes one `/rest/db/completion` call per remote device per + folder. On large setups this generates significant API traffic. +- Syncthing v2.x uses SQLite (replacing LevelDB). First launch after upgrade may be + slow due to migration. diff --git a/docker-compose.tunnel.yml b/docker-compose.tunnel.yml new file mode 100644 index 0000000..cd0b6aa --- /dev/null +++ b/docker-compose.tunnel.yml @@ -0,0 +1,44 @@ +--- +# Syncthing MCP — Cloudflare Tunnel deployment +# +# Exposes the MCP server via a Cloudflare Tunnel (zero-trust, no open ports). +# Requires a Cloudflare Tunnel token — create one at: +# https://one.dash.cloudflare.com → Networks → Tunnels → Create +# +# Usage: +# docker compose -f docker-compose.tunnel.yml up -d +# +# The tunnel routes traffic to the MCP server on port 8000. +# Bearer token auth (MCP_AUTH_TOKEN) secures the MCP endpoint. +# The /health endpoint is unauthenticated for Cloudflare health probes. + +services: + syncthing-mcp: + build: . + container_name: syncthing-mcp + restart: unless-stopped + env_file: .env + environment: + MCP_TRANSPORT: streamable-http + MCP_HOST: "0.0.0.0" + MCP_PORT: "8000" + expose: + - "8000" + networks: + - tunnel + + cloudflared: + image: cloudflare/cloudflared:latest + container_name: syncthing-mcp-tunnel + restart: unless-stopped + command: tunnel run + environment: + TUNNEL_TOKEN: ${CLOUDFLARE_TUNNEL_TOKEN:?set CLOUDFLARE_TUNNEL_TOKEN in .env} + networks: + - tunnel + depends_on: + - syncthing-mcp + +networks: + tunnel: + driver: bridge diff --git a/pyproject.toml b/pyproject.toml index 64af123..96d5719 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "syncthing-mcp" -version = "0.2.0" -description = "MCP server for Syncthing — query folder replication status, manage configuration, and identify datasets safe to remove locally." +version = "0.3.0" +description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation." requires-python = ">=3.11" dependencies = [ "mcp[cli]>=1.0.0", @@ -9,8 +9,6 @@ dependencies = [ "pydantic>=2.0.0", "uvicorn>=0.30.0", "starlette>=0.37.0", - "uvicorn>=0.30.0", - "starlette>=0.37.0", ] [project.scripts] diff --git a/src/syncthing_mcp/__init__.py b/src/syncthing_mcp/__init__.py index 6f1e1b4..c14d655 100644 --- a/src/syncthing_mcp/__init__.py +++ b/src/syncthing_mcp/__init__.py @@ -1,3 +1,3 @@ """Syncthing MCP Server — manage Syncthing instances via MCP tools.""" -__version__ = "0.2.0" +__version__ = "0.3.0" diff --git a/src/syncthing_mcp/formatters.py b/src/syncthing_mcp/formatters.py new file mode 100644 index 0000000..c930d86 --- /dev/null +++ b/src/syncthing_mcp/formatters.py @@ -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, + } diff --git a/src/syncthing_mcp/models.py b/src/syncthing_mcp/models.py index 1a13ae9..13edf0e 100644 --- a/src/syncthing_mcp/models.py +++ b/src/syncthing_mcp/models.py @@ -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 diff --git a/src/syncthing_mcp/registry.py b/src/syncthing_mcp/registry.py index 45da922..7b0f9ca 100644 --- a/src/syncthing_mcp/registry.py +++ b/src/syncthing_mcp/registry.py @@ -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]: diff --git a/src/syncthing_mcp/tools/config.py b/src/syncthing_mcp/tools/config.py index 7cf6945..4af9e53 100644 --- a/src/syncthing_mcp/tools/config.py +++ b/src/syncthing_mcp/tools/config.py @@ -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) diff --git a/src/syncthing_mcp/tools/devices.py b/src/syncthing_mcp/tools/devices.py index 2e55054..9518566 100644 --- a/src/syncthing_mcp/tools/devices.py +++ b/src/syncthing_mcp/tools/devices.py @@ -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) diff --git a/src/syncthing_mcp/tools/folders.py b/src/syncthing_mcp/tools/folders.py index 62c85e5..9db4c15 100644 --- a/src/syncthing_mcp/tools/folders.py +++ b/src/syncthing_mcp/tools/folders.py @@ -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) diff --git a/src/syncthing_mcp/tools/instances.py b/src/syncthing_mcp/tools/instances.py index e2db6c3..5aeeddf 100644 --- a/src/syncthing_mcp/tools/instances.py +++ b/src/syncthing_mcp/tools/instances.py @@ -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) diff --git a/src/syncthing_mcp/tools/system.py b/src/syncthing_mcp/tools/system.py index 52c4cab..d8dd2d4 100644 --- a/src/syncthing_mcp/tools/system.py +++ b/src/syncthing_mcp/tools/system.py @@ -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) diff --git a/tests/test_tools_config.py b/tests/test_tools_config.py index 96da194..f416981 100644 --- a/tests/test_tools_config.py +++ b/tests/test_tools_config.py @@ -140,7 +140,7 @@ class TestSetIgnores: SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"]) )) assert result["status"] == "updated" - assert result["patternCount"] == 2 + assert result["count"] == 2 class TestGetDefaultIgnores: diff --git a/tests/test_tools_devices.py b/tests/test_tools_devices.py index 796ca0e..e184695 100644 --- a/tests/test_tools_devices.py +++ b/tests/test_tools_devices.py @@ -1,4 +1,4 @@ -"""Tests for device tools (list, completion, connections).""" +"""Tests for device tools (list, completion, connections, stats).""" import json @@ -41,7 +41,7 @@ class TestDeviceCompletion: DeviceInput(device_id=DEVICE_ID_REMOTE) )) assert result["completion"] == 100.0 - assert result["needBytes"] == 0 + assert result["needSize"] == "0.0 B" class TestConnections: @@ -51,3 +51,12 @@ class TestConnections: result = json.loads(await syncthing_connections(EmptyInput())) assert len(result) == 2 assert any(c["connected"] for c in result) + + +class TestDeviceStats: + async def test_returns_stats(self, mock_api): + from syncthing_mcp.tools.devices import syncthing_device_stats + + result = json.loads(await syncthing_device_stats(EmptyInput())) + assert len(result) >= 1 + assert "lastSeen" in result[0] diff --git a/tests/test_tools_folders.py b/tests/test_tools_folders.py index d74fc0f..8702619 100644 --- a/tests/test_tools_folders.py +++ b/tests/test_tools_folders.py @@ -52,7 +52,7 @@ class TestFolderCompletion: 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["fullyReplicated"] == 1 assert result["devices"][0]["completion"] == 100.0 async def test_partially_replicated(self, mock_api): @@ -60,7 +60,7 @@ class TestFolderCompletion: 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 + assert result["fullyReplicated"] == 0 async def test_folder_not_found(self, mock_api): from syncthing_mcp.tools.folders import syncthing_folder_completion @@ -76,8 +76,8 @@ class TestReplicationReport: 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 + assert result["summary"]["safe"] == 1 + assert result["folders"][0]["safe"] is True async def test_not_safe_when_incomplete(self, mock_api): from syncthing_mcp.tools.folders import syncthing_replication_report @@ -85,7 +85,7 @@ class TestReplicationReport: 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 + assert result["summary"]["safe"] == 0 class TestPauseFolder: @@ -116,7 +116,7 @@ class TestResumeFolder: ) result = json.loads(await syncthing_resume_folder(PauseFolderInput(folder_id=FOLDER_ID))) assert result["status"] == "resumed" - assert result["folderType"] == "sendreceive" + assert result["type"] == "sendreceive" class TestScanFolder: @@ -134,7 +134,7 @@ class TestFolderErrors: 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 + assert result["count"] == 0 class TestBrowseFolder: @@ -172,7 +172,8 @@ class TestFileInfo: FileInfoInput(folder_id=FOLDER_ID, file_path="test.txt") )) assert result["file"] == "test.txt" - assert result["global"]["sizeFormatted"] == "1.0 KB" + # Concise mode returns globalSize at top level + assert result["globalSize"] == "1.0 KB" class TestFolderNeed: diff --git a/tests/test_tools_system.py b/tests/test_tools_system.py index 386fcc6..0a26115 100644 --- a/tests/test_tools_system.py +++ b/tests/test_tools_system.py @@ -33,7 +33,8 @@ class TestSystemStatus: from syncthing_mcp.tools.system import syncthing_system_status result = json.loads(await syncthing_system_status(EmptyInput())) - assert result["myID"] == DEVICE_ID_LOCAL + # Concise mode truncates device ID to 8 chars + assert result["myID"] == DEVICE_ID_LOCAL[:8] assert result["deviceName"] == "local-dev" assert result["version"] == "v1.28.0" assert result["instance"] == "default" @@ -44,7 +45,7 @@ class TestSystemErrors: from syncthing_mcp.tools.system import syncthing_system_errors result = json.loads(await syncthing_system_errors(EmptyInput())) - assert result["errorCount"] == 0 + assert result["count"] == 0 async def test_with_errors(self, mock_api): from syncthing_mcp.tools.system import syncthing_system_errors @@ -53,7 +54,7 @@ class TestSystemErrors: json={"errors": [{"when": "2025-01-01", "message": "disk full"}]} ) result = json.loads(await syncthing_system_errors(EmptyInput())) - assert result["errorCount"] == 1 + assert result["count"] == 1 class TestClearErrors: @@ -70,7 +71,7 @@ class TestSystemLog: from syncthing_mcp.tools.system import syncthing_system_log result = json.loads(await syncthing_system_log(EmptyInput())) - assert result["messageCount"] == 0 + assert result["count"] == 0 class TestRecentChanges: @@ -81,7 +82,7 @@ class TestRecentChanges: {"id": 1, "type": "LocalChangeDetected", "data": {"path": "file.txt"}} ]) result = json.loads(await syncthing_recent_changes(EmptyInput())) - assert result["eventCount"] == 1 + assert result["count"] == 1 class TestRestartRequired: @@ -118,7 +119,7 @@ class TestCheckUpgrade: mock_api.get("/rest/system/upgrade").respond(status_code=501) result = json.loads(await syncthing_check_upgrade(EmptyInput())) - assert "not available" in result["message"] + assert result["upgradeCheck"] == "unavailable" class TestHealthSummary: @@ -128,7 +129,7 @@ class TestHealthSummary: 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 + assert result["summary"]["idle"] == 1 async def test_error_state(self, mock_api): from syncthing_mcp.tools.system import syncthing_health_summary