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

Major improvements following best-in-class MCP patterns:

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

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

No files matched your search

+10 -2
View File
@@ -1,3 +1,11 @@
DOMAIN=example.com # --- Syncthing instances ---
MCP_AUTH_TOKEN=CHANGEME
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"}} 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...
+115 -46
View File
@@ -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. 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 (39 total)
## Tools (36 total)
### Instance Management ### Instance Management
@@ -23,30 +26,31 @@ This MCP server exposes that information as structured tool calls, so you can as
| Tool | Description | Mutating | | Tool | Description | Mutating |
|------|-------------|----------| |------|-------------|----------|
| `syncthing_system_status` | Device ID, name, uptime, version | No | | `syncthing_system_status` | Device ID, name, uptime, version | No |
| `syncthing_list_folders` | All folders with paths, types, and shared device lists | No | | `syncthing_list_folders` | All folders with types and device counts | No |
| `syncthing_list_devices` | All devices with connection status and last seen | No | | `syncthing_list_devices` | All devices with connection status | No |
| `syncthing_connections` | Active connection details (addresses, crypto, throughput) | 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_system_errors` | Recent system errors and warnings | No |
| `syncthing_clear_errors` | Clear the system error log | Yes | | `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_recent_changes` | Recent file change events (local + remote) | No |
| `syncthing_health_summary` | Single-call health overview: status, alerts, folder/device/pending counts | No | | `syncthing_health_summary` | Single-call health overview with alerts | No |
| `syncthing_check_upgrade` | Check if a newer version of Syncthing is available | No | | `syncthing_check_upgrade` | Check for newer Syncthing version | No |
### Folder Status & Replication ### Folder Status & Replication
| Tool | Description | Mutating | | 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_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 | | `syncthing_folder_errors` | Current sync errors for a folder | No |
### Device Status ### Device Status
| Tool | Description | Mutating | | 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 ### Folder Operations
@@ -60,16 +64,17 @@ This MCP server exposes that information as structured tool calls, so you can as
| Tool | Description | Mutating | | Tool | Description | Mutating |
|------|-------------|----------| |------|-------------|----------|
| `syncthing_browse_folder` | Browse folder contents at a path prefix (directory listing from Syncthing's DB) | No | | `syncthing_browse_folder` | Browse folder contents (directory listing from DB) | No |
| `syncthing_file_info` | Detailed info about a specific file (versions, availability, conflicts) | No | | `syncthing_file_info` | Detailed info about a specific file | No |
| `syncthing_folder_need` | List out-of-sync files a folder still needs (with pagination) | 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 ### Conflict Resolution
| Tool | Description | Mutating | | Tool | Description | Mutating |
|------|-------------|----------| |------|-------------|----------|
| `syncthing_override_folder` | Override remote changes on a send-only folder (make local authoritative) | Yes | | `syncthing_override_folder` | Override remote changes (send-only folder) | Yes |
| `syncthing_revert_folder` | Revert local changes on a receive-only folder (pull remote state) | Yes | | `syncthing_revert_folder` | Revert local changes (receive-only folder) | Yes |
### Config Mutation: Pending Devices & Folders ### 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_devices` | List pending device connection requests | No |
| `syncthing_pending_folders` | List pending folder share offers | 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_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 | | `syncthing_reject_folder` | Dismiss a pending folder offer | Yes |
### Config Mutation: Restart & Ignore Patterns ### 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_required` | Check if config changes require a restart | No |
| `syncthing_restart` | Restart the Syncthing service | Yes | | `syncthing_restart` | Restart the Syncthing service | Yes |
| `syncthing_get_ignores` | Get .stignore patterns for a folder | No | | `syncthing_get_ignores` | Get .stignore patterns for a folder | No |
| `syncthing_set_ignores` | Set .stignore patterns for a folder (replaces all) | Yes | | `syncthing_set_ignores` | Set .stignore patterns for a folder | Yes |
| `syncthing_get_default_ignores` | Get default ignore patterns for new folders | No | | `syncthing_get_default_ignores` | Get default ignore patterns | No |
| `syncthing_set_default_ignores` | Set default ignore patterns for new folders | Yes | | `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 ## Project Structure
@@ -99,20 +119,25 @@ This MCP server exposes that information as structured tool calls, so you can as
syncthing-mcp/ syncthing-mcp/
├── src/syncthing_mcp/ ├── src/syncthing_mcp/
│ ├── __init__.py # Package version │ ├── __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) │ ├── 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 │ ├── registry.py # Multi-instance registry from env vars
│ ├── server.py # FastMCP server + lifespan │ ├── server.py # FastMCP server + lifespan
│ └── tools/ │ └── tools/
│ ├── system.py # System status, health, errors, log, restart, upgrade │ ├── system.py # System status, health, errors, log, restart, upgrade
│ ├── folders.py # Folder status, completion, replication, operations, file queries │ ├── folders.py # Folder status, completion, replication, file queries
│ ├── devices.py # Device completion, connections │ ├── devices.py # Device listing, completion, connections, stats
│ ├── config.py # Pending accept/reject, ignore patterns │ ├── config.py # Pending accept/reject, ignore patterns
│ └── instances.py # Instance listing, folder listing │ └── 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 ├── pyproject.toml
└── README.md ├── Dockerfile
├── docker-compose.yml # Traefik reverse proxy (HTTPS/ACME)
└── docker-compose.tunnel.yml # Cloudflare Tunnel (zero-trust)
``` ```
## Multi-Instance Support ## Multi-Instance Support
@@ -150,7 +175,7 @@ Every tool accepts an optional `instance` parameter to target a specific node. W
## Safe Removal Workflow ## 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 2. Confirm the fully-replicated remote device(s) are the ones you expect
3. `syncthing_pause_folder` — stops Syncthing from propagating local changes 3. `syncthing_pause_folder` — stops Syncthing from propagating local changes
4. Delete the local data outside of Syncthing 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. > **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 ## Setup
@@ -180,12 +205,8 @@ uv sync
Open the Syncthing web UI → Actions → Settings → API Key. Open the Syncthing web UI → Actions → Settings → API Key.
Alternatively, find it in your Syncthing config file under `<gui><apikey>`.
### Configure Claude Desktop (single instance) ### Configure Claude Desktop (single instance)
Add to your Claude Desktop MCP config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):
```json ```json
{ {
"mcpServers": { "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.<DOMAIN>/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 ```bash
uv sync uv sync
uv run pytest -v uv run pytest -v
``` ```
### Environment Variables ## Environment Variables
| Variable | Required | Default | Description | | Variable | Required | Default | Description |
|----------|----------|---------|-------------| |----------|----------|---------|-------------|
| `SYNCTHING_API_KEY` | Yes* | — | API key (single-instance mode) | | `SYNCTHING_API_KEY` | Yes* | — | API key (single-instance mode) |
| `SYNCTHING_URL` | No | `http://localhost:8384` | Base URL (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. \* Required unless `SYNCTHING_INSTANCES` is set.
## Performance Notes ## 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. - `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. On setups with many folders and devices, this can generate significant API traffic. - 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 to the replication report. - `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.
## Contributing
Issues and PRs welcome.
## License ## License
+142
View File
@@ -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.
+44
View File
@@ -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
+2 -4
View File
@@ -1,7 +1,7 @@
[project] [project]
name = "syncthing-mcp" name = "syncthing-mcp"
version = "0.2.0" version = "0.3.0"
description = "MCP server for Syncthing — query folder replication status, manage configuration, and identify datasets safe to remove locally." description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation."
requires-python = ">=3.11" requires-python = ">=3.11"
dependencies = [ dependencies = [
"mcp[cli]>=1.0.0", "mcp[cli]>=1.0.0",
@@ -9,8 +9,6 @@ dependencies = [
"pydantic>=2.0.0", "pydantic>=2.0.0",
"uvicorn>=0.30.0", "uvicorn>=0.30.0",
"starlette>=0.37.0", "starlette>=0.37.0",
"uvicorn>=0.30.0",
"starlette>=0.37.0",
] ]
[project.scripts] [project.scripts]
+1 -1
View File
@@ -1,3 +1,3 @@
"""Syncthing MCP Server — manage Syncthing instances via MCP tools.""" """Syncthing MCP Server — manage Syncthing instances via MCP tools."""
__version__ = "0.2.0" __version__ = "0.3.0"
+265
View File
@@ -0,0 +1,265 @@
"""Token-efficient formatters for Syncthing API responses.
Design principles (following best-in-class MCP patterns):
- Default output is compact JSON (no indentation, no spaces after separators)
- Device IDs are truncated to short form unless full detail is requested
- Redundant fields (both raw bytes AND human-readable size) are collapsed
- Large responses are truncated with guidance to use pagination/filters
- Summary modes return counts only, skipping per-item detail
"""
import json
import random
from typing import Any
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
CHARACTER_LIMIT = 25_000
SHORT_ID_LEN = 7
# ---------------------------------------------------------------------------
# Core helpers
# ---------------------------------------------------------------------------
def fmt(data: Any, *, concise: bool = True) -> str:
"""Serialize to JSON. Compact by default for token efficiency."""
if concise:
return json.dumps(data, separators=(",", ":"))
return json.dumps(data, indent=2)
def short_id(device_id: str) -> str:
"""Truncate a Syncthing device ID to its first block."""
return device_id[:SHORT_ID_LEN] if device_id else ""
def format_bytes(n: int | float) -> str:
"""Human-readable byte size."""
for unit in ("B", "KB", "MB", "GB", "TB"):
if abs(n) < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
def truncate(text: str, limit: int = CHARACTER_LIMIT) -> str:
"""Truncate text that exceeds the character limit, with guidance."""
if len(text) <= limit:
return text
cut = text[:limit]
last_nl = cut.rfind("\n")
if last_nl > limit * 0.8:
cut = cut[:last_nl]
return (
cut
+ f"\n... truncated ({len(text):,} chars, limit {limit:,})."
" Use pagination or filters to narrow results."
)
def sample(items: list, size: int = 5) -> list:
"""Return a random sample from a list without replacement."""
if len(items) <= size:
return items
return random.sample(items, size)
# ---------------------------------------------------------------------------
# Entity formatters — concise mode strips to essential fields only
# ---------------------------------------------------------------------------
def format_folder(cfg: dict, *, concise: bool = True) -> dict:
"""Format a folder config entry."""
if concise:
return {
"id": cfg["id"],
"label": cfg.get("label", cfg["id"]),
"type": cfg.get("type", "sendreceive"),
"paused": cfg.get("paused", False),
"devices": len(cfg.get("devices", [])),
}
devices = []
for d in cfg.get("devices", []):
did = d.get("deviceID", "")
devices.append(did)
return {
"id": cfg["id"],
"label": cfg.get("label", cfg["id"]),
"path": cfg.get("path", ""),
"type": cfg.get("type", "sendreceive"),
"paused": cfg.get("paused", False),
"devices": devices,
}
def format_device(
dev: dict,
conn: dict | None = None,
stat: dict | None = None,
*,
concise: bool = True,
) -> dict:
"""Format a device config + connection entry."""
did = dev["deviceID"]
conn = conn or {}
stat = stat or {}
if concise:
return {
"id": short_id(did),
"name": dev.get("name", short_id(did)),
"connected": conn.get("connected", False),
"address": conn.get("address", ""),
}
return {
"deviceID": did,
"name": dev.get("name", short_id(did)),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
"crypto": conn.get("crypto", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
"lastSeen": stat.get("lastSeen", ""),
}
def format_folder_status(status: dict, *, concise: bool = True) -> dict:
"""Format a /rest/db/status response."""
if concise:
return {
"state": status.get("state"),
"globalFiles": status.get("globalFiles"),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"localFiles": status.get("localFiles"),
"localSize": format_bytes(status.get("localBytes", 0)),
"needFiles": status.get("needFiles"),
"needSize": format_bytes(status.get("needBytes", 0)),
}
return {
"state": status.get("state"),
"stateChanged": status.get("stateChanged"),
"globalFiles": status.get("globalFiles"),
"globalBytes": status.get("globalBytes"),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"localFiles": status.get("localFiles"),
"localBytes": status.get("localBytes"),
"localSize": format_bytes(status.get("localBytes", 0)),
"needFiles": status.get("needFiles"),
"needBytes": status.get("needBytes"),
"needSize": format_bytes(status.get("needBytes", 0)),
"inSyncFiles": status.get("inSyncFiles"),
"inSyncBytes": status.get("inSyncBytes"),
"globalDeleted": status.get("globalDeleted"),
"localDeleted": status.get("localDeleted"),
"ignorePatterns": status.get("ignorePatterns"),
}
def format_completion(
comp: dict,
device_name: str = "",
*,
connected: bool = False,
concise: bool = True,
) -> dict:
"""Format a /rest/db/completion response for a single device."""
if concise:
return {
"device": device_name or short_id(comp.get("deviceID", "")),
"connected": connected,
"completion": round(comp.get("completion", 0), 2),
"needSize": format_bytes(comp.get("needBytes", 0)),
"remoteState": comp.get("remoteState", "unknown"),
}
return {
"device": device_name,
"connected": connected,
"completion": round(comp.get("completion", 0), 2),
"globalBytes": comp.get("globalBytes", 0),
"globalSize": format_bytes(comp.get("globalBytes", 0)),
"needBytes": comp.get("needBytes", 0),
"needSize": format_bytes(comp.get("needBytes", 0)),
"needItems": comp.get("needItems", 0),
"needDeletes": comp.get("needDeletes", 0),
"remoteState": comp.get("remoteState", "unknown"),
}
def format_connection(did: str, conn: dict, name: str = "", *, concise: bool = True) -> dict:
"""Format a single connection entry."""
if concise:
return {
"device": name or short_id(did),
"connected": conn.get("connected", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
}
return {
"deviceID": did,
"deviceName": name or short_id(did),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
"crypto": conn.get("crypto", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
}
# ---------------------------------------------------------------------------
# Replication helpers
# ---------------------------------------------------------------------------
def format_replication_entry(
folder_cfg: dict,
status: dict,
device_completions: list[dict],
*,
concise: bool = True,
) -> dict:
"""Format a single folder's replication data for the replication report."""
fid = folder_cfg["id"]
label = folder_cfg.get("label", fid)
local_bytes = status.get("localBytes", 0)
state = status.get("state", "unknown")
paused = folder_cfg.get("paused", False)
fully_replicated = [
d for d in device_completions
if d.get("completion") == 100 and d.get("remoteState") == "valid"
]
safe = len(fully_replicated) >= 1 and state == "idle" and not paused
if concise:
return {
"id": fid,
"label": label,
"safe": safe,
"local": format_bytes(local_bytes),
"state": state,
"replicated": len(fully_replicated),
"totalDevices": len(device_completions),
}
return {
"id": fid,
"label": label,
"path": folder_cfg.get("path", ""),
"type": folder_cfg.get("type", "sendreceive"),
"paused": paused,
"state": state,
"localBytes": local_bytes,
"localSize": format_bytes(local_bytes),
"globalSize": format_bytes(status.get("globalBytes", 0)),
"safeToRemove": safe,
"fullyReplicatedOn": len(fully_replicated),
"totalRemoteDevices": len(device_completions),
"devices": device_completions,
}
+85 -27
View File
@@ -3,47 +3,90 @@
from pydantic import BaseModel, ConfigDict, Field 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") model_config = ConfigDict(extra="forbid")
instance: str | None = Field( instance: str | None = Field(
None, description="Instance name. Omit if only one instance is configured." 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field( folder_id: str = Field(
..., description="Syncthing folder ID (e.g. 'abcd-1234')", min_length=1 ..., 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field( device_id: str = Field(
..., ...,
description="Syncthing device ID (long alphanumeric string with dashes)", description="Syncthing device ID (long alphanumeric string with dashes)",
min_length=1, 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1) folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
device_id: str = Field(..., description="Syncthing device 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field( 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
device_id: str = Field( device_id: str = Field(
..., description="Device ID to accept (from pending list)", min_length=1 ..., description="Device ID to accept (from pending list)", min_length=1
@@ -52,10 +95,9 @@ class AcceptDeviceInput(BaseModel):
None, None,
description="Friendly name to assign. If omitted, uses the name from the pending request.", 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field( folder_id: str = Field(
..., description="Folder ID to accept (from pending list)", min_length=1 ..., description="Folder ID to accept (from pending list)", min_length=1
@@ -64,10 +106,9 @@ class AcceptFolderInput(BaseModel):
None, None,
description="Local path for the folder. If omitted, uses Syncthing's default path.", 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field( folder_id: str = Field(
..., description="Folder ID to reject", min_length=1 ..., description="Folder ID to reject", min_length=1
@@ -76,32 +117,31 @@ class RejectFolderInput(BaseModel):
None, None,
description="Device ID that offered the folder. If omitted, rejects from all devices.", 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Folder ID", min_length=1) folder_id: str = Field(..., description="Folder ID", min_length=1)
patterns: list[str] = Field( patterns: list[str] = Field(
..., ...,
description="List of ignore patterns (e.g. ['*.tmp', '.DS_Store', '// #include'])", 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") model_config = ConfigDict(extra="forbid")
lines: list[str] = Field( lines: list[str] = Field(
..., ...,
description="Default ignore patterns for new folders (e.g. ['.DS_Store', 'Thumbs.db'])", 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1) folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
prefix: str | None = Field( prefix: str | None = Field(
@@ -113,21 +153,39 @@ class BrowseFolderInput(BaseModel):
description="How many directory levels deep to return (default: 1).", description="How many directory levels deep to return (default: 1).",
ge=0, 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1) folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
file_path: str = Field( file_path: str = Field(
..., description="Relative path of the file within the folder", min_length=1 ..., 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) model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1) folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
page: int = Field(1, description="Page number (1-based)", ge=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) per_page: int = Field(50, description="Items per page", ge=1, le=500)
instance: str | None = Field(None, description="Instance name")
class RemoteNeedInput(ReadParams):
"""Query files a remote device still needs for a folder."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
folder_id: str = Field(..., description="Syncthing folder ID", min_length=1)
device_id: str = Field(..., description="Remote device ID", min_length=1)
page: int = Field(1, description="Page number (1-based)", ge=1)
per_page: int = Field(50, description="Items per page", ge=1, le=500)
# ---------------------------------------------------------------------------
# Backward-compatible aliases (referenced by existing tests)
# ---------------------------------------------------------------------------
EmptyInput = ReadParams
FolderInput = FolderReadParams
DeviceInput = DeviceReadParams
PauseFolderInput = FolderWriteParams
FolderDeviceInput = FolderDeviceReadParams
+4 -6
View File
@@ -7,12 +7,10 @@ from syncthing_mcp.client import SyncthingClient
def format_bytes(n: int) -> str: def format_bytes(n: int) -> str:
"""Human-readable byte size.""" """Human-readable byte size. Delegates to formatters.format_bytes."""
for unit in ("B", "KB", "MB", "GB", "TB"): from syncthing_mcp.formatters import format_bytes as _fb
if abs(n) < 1024:
return f"{n:.1f} {unit}" return _fb(n)
n /= 1024
return f"{n:.1f} PB"
def load_instances() -> dict[str, SyncthingClient]: def load_instances() -> dict[str, SyncthingClient]:
+71 -184
View File
@@ -1,16 +1,16 @@
"""Config mutation tools: pending devices/folders, ignores, accept/reject.""" """Config mutation tools: pending devices/folders, ignores, accept/reject."""
import json from syncthing_mcp.formatters import fmt, truncate
from syncthing_mcp.models import ( from syncthing_mcp.models import (
AcceptDeviceInput, AcceptDeviceInput,
AcceptFolderInput, AcceptFolderInput,
DeviceInput, DeviceWriteParams,
EmptyInput, FolderReadParams,
FolderInput, ReadParams,
RejectFolderInput, RejectFolderInput,
SetDefaultIgnoresInput, SetDefaultIgnoresInput,
SetIgnoresInput, SetIgnoresInput,
WriteParams,
) )
from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp from syncthing_mcp.server import mcp
@@ -31,18 +31,14 @@ from syncthing_mcp.server import mcp
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_pending_devices(params: EmptyInput) -> str: async def syncthing_pending_devices(params: ReadParams) -> str:
"""List remote devices that have tried to connect but are not yet configured. """Remote devices that tried to connect but are not yet configured."""
Returns:
str: JSON object keyed by device ID, each with name, address, and time.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices") pending = await client._get("/rest/cluster/pending/devices")
return json.dumps( return fmt(
{"instance": client.name, "pendingDevices": pending}, {"instance": client.name, "pendingDevices": pending},
indent=2, concise=params.concise,
) )
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -58,18 +54,14 @@ async def syncthing_pending_devices(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_pending_folders(params: EmptyInput) -> str: async def syncthing_pending_folders(params: ReadParams) -> str:
"""List folders that remote devices have offered to share but are not yet accepted. """Folders that remote devices have offered to share but are not yet accepted."""
Returns:
str: JSON object keyed by folder ID, each listing offering devices with labels.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/folders") pending = await client._get("/rest/cluster/pending/folders")
return json.dumps( return fmt(
{"instance": client.name, "pendingFolders": pending}, {"instance": client.name, "pendingFolders": pending},
indent=2, concise=params.concise,
) )
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
"""Accept a pending device by adding it to the Syncthing configuration. """Accept a pending device by adding it to the Syncthing configuration."""
The device will be added with 'dynamic' addressing. You can optionally
provide a friendly name.
Args:
params: AcceptDeviceInput with device_id and optional name.
Returns:
str: Confirmation message with the device details.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/devices") 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["deviceID"] = params.device_id
new_device["name"] = name new_device["name"] = name
await client._post("/rest/config/devices", body=new_device) await client._post("/rest/config/devices", body=new_device)
return json.dumps( return fmt({
{ "status": "accepted",
"status": "accepted", "deviceID": params.device_id[:8],
"deviceID": params.device_id, "name": name,
"name": name, "instance": client.name,
"instance": client.name, })
"message": f"Device '{name}' ({params.device_id[:8]}...) has been added.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -133,33 +111,19 @@ async def syncthing_accept_device(params: AcceptDeviceInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_reject_device(params: DeviceInput) -> str: async def syncthing_reject_device(params: DeviceWriteParams) -> str:
"""Dismiss a pending device connection request. """Dismiss a pending device connection request."""
This only clears the pending notification. The device can try again later;
for permanent blocking, use Syncthing's ignore-device feature via the web UI.
Args:
params: DeviceInput with device_id.
Returns:
str: Confirmation message.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._delete( await client._delete(
"/rest/cluster/pending/devices", "/rest/cluster/pending/devices",
params={"device": params.device_id}, params={"device": params.device_id},
) )
return json.dumps( return fmt({
{ "status": "rejected",
"status": "rejected", "deviceID": params.device_id[:8],
"deviceID": params.device_id, "instance": client.name,
"instance": client.name, })
"message": f"Pending device '{params.device_id[:8]}...' has been dismissed.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_accept_folder(params: AcceptFolderInput) -> str:
"""Accept a pending folder share offer by adding it to the configuration. """Accept a pending folder share offer. Uses default folder config as template."""
Uses the default folder configuration as a template. If no path is provided,
Syncthing's default folder path is used.
Args:
params: AcceptFolderInput with folder_id and optional path.
Returns:
str: Confirmation with assigned path and sharing details.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
pending = await client._get("/rest/cluster/pending/folders") pending = await client._get("/rest/cluster/pending/folders")
folder_pending = pending.get(params.folder_id, {}) folder_pending = pending.get(params.folder_id, {})
if not folder_pending: if not folder_pending:
return json.dumps( return fmt({"error": f"Folder '{params.folder_id}' not found in pending offers."})
{"error": f"Folder '{params.folder_id}' not found in pending offers."}
)
offering_devices = list(folder_pending.get("offeredBy", {}).keys()) offering_devices = list(folder_pending.get("offeredBy", {}).keys())
first_offer = next(iter(folder_pending.get("offeredBy", {}).values()), {}) first_offer = next(iter(folder_pending.get("offeredBy", {}).values()), {})
label = first_offer.get("label", params.folder_id) 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}) device_list.append({"deviceID": did})
new_folder["devices"] = device_list new_folder["devices"] = device_list
await client._post("/rest/config/folders", body=new_folder) await client._post("/rest/config/folders", body=new_folder)
return json.dumps( return fmt({
{ "status": "accepted",
"status": "accepted", "folder": params.folder_id,
"folderID": params.folder_id, "label": label,
"label": label, "path": new_folder.get("path", "(default)"),
"path": new_folder.get("path", "(default)"), "instance": client.name,
"sharedWith": offering_devices, })
"instance": client.name,
"message": (
f"Folder '{label}' ({params.folder_id}) has been added "
f"at '{new_folder.get('path', '(default)')}'."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_reject_folder(params: RejectFolderInput) -> str:
"""Dismiss a pending folder share offer. """Dismiss a pending folder share offer."""
Args:
params: RejectFolderInput with folder_id and optional device_id.
If device_id is omitted, rejects the offer from all devices.
Returns:
str: Confirmation message.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
delete_params: dict[str, str] = {"folder": params.folder_id} delete_params: dict[str, str] = {"folder": params.folder_id}
if params.device_id: if params.device_id:
delete_params["device"] = params.device_id delete_params["device"] = params.device_id
await client._delete("/rest/cluster/pending/folders", params=delete_params) await client._delete("/rest/cluster/pending/folders", params=delete_params)
return json.dumps( return fmt({
{ "status": "rejected",
"status": "rejected", "folder": params.folder_id,
"folderID": params.folder_id, "instance": client.name,
"deviceID": params.device_id or "(all)", })
"instance": client.name,
"message": f"Pending folder offer for '{params.folder_id}' has been dismissed.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -284,29 +215,21 @@ async def syncthing_reject_folder(params: RejectFolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_get_ignores(params: FolderInput) -> str: async def syncthing_get_ignores(params: FolderReadParams) -> str:
"""Get the current .stignore patterns for a folder. """Get the .stignore patterns for a folder."""
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with ignore patterns list and whether the folder has expanded patterns.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get( result = await client._get(
"/rest/db/ignores", params={"folder": params.folder_id} "/rest/db/ignores", params={"folder": params.folder_id}
) )
return json.dumps( data = {
{ "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, "patterns": result.get("ignore", []) or [],
"patterns": result.get("ignore", []) or [], }
"expanded": result.get("expanded", []) or [], if not params.concise:
}, data["expanded"] = result.get("expanded", []) or []
indent=2, return fmt(data, concise=params.concise)
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
"""Set the .stignore patterns for a folder. Replaces all existing patterns. """Set .stignore patterns for a folder. Replaces all existing patterns."""
Common patterns: '*.tmp', '.DS_Store', 'Thumbs.db', '(?d).Trash*',
'// #include common-ignores' (to include shared pattern files).
Args:
params: SetIgnoresInput with folder_id and patterns list.
Returns:
str: Confirmation with the applied patterns.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._post( await client._post(
@@ -340,17 +253,12 @@ async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
params={"folder": params.folder_id}, params={"folder": params.folder_id},
body={"ignore": params.patterns}, body={"ignore": params.patterns},
) )
return json.dumps( return fmt({
{ "status": "updated",
"status": "updated", "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, "count": len(params.patterns),
"patternCount": len(params.patterns), })
"patterns": params.patterns,
"message": f"Ignore patterns for '{params.folder_id}' have been updated.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -365,22 +273,15 @@ async def syncthing_set_ignores(params: SetIgnoresInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_get_default_ignores(params: EmptyInput) -> str: async def syncthing_get_default_ignores(params: ReadParams) -> str:
"""Get the default ignore patterns applied to newly created folders. """Default ignore patterns applied to newly created folders."""
Returns:
str: JSON with default ignore pattern lines.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get("/rest/config/defaults/ignores") result = await client._get("/rest/config/defaults/ignores")
return json.dumps( return fmt({
{ "instance": client.name,
"instance": client.name, "lines": result.get("lines", []) or [],
"lines": result.get("lines", []) or [], }, concise=params.concise)
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_set_default_ignores(params: SetDefaultIgnoresInput) -> str:
"""Set the default ignore patterns for newly created folders. """Set the default ignore patterns for newly created folders."""
These patterns will be automatically applied when new folders are added.
Args:
params: SetDefaultIgnoresInput with lines list.
Returns:
str: Confirmation with the applied patterns.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._put( await client._put(
"/rest/config/defaults/ignores", "/rest/config/defaults/ignores",
body={"lines": params.lines}, body={"lines": params.lines},
) )
return json.dumps( return fmt({
{ "status": "updated",
"status": "updated", "instance": client.name,
"instance": client.name, "count": len(params.lines),
"lineCount": len(params.lines), })
"lines": params.lines,
"message": "Default ignore patterns have been updated for new folders.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
+74 -76
View File
@@ -1,13 +1,10 @@
"""Device completion and connection tools.""" """Device listing, completion, connection, and stats tools."""
import json from typing import Any
from syncthing_mcp.models import DeviceInput, EmptyInput from syncthing_mcp.formatters import fmt, format_bytes, format_connection, format_device, truncate
from syncthing_mcp.registry import ( from syncthing_mcp.models import DeviceReadParams, ReadParams
format_bytes, from syncthing_mcp.registry import get_instance, handle_error_global
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp from syncthing_mcp.server import mcp
@@ -21,36 +18,24 @@ from syncthing_mcp.server import mcp
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_list_devices(params: EmptyInput) -> str: async def syncthing_list_devices(params: ReadParams) -> str:
"""List all configured devices with their names, connection status, and last seen time. """All configured devices with connection status and last seen time."""
Returns:
str: JSON array of devices with deviceID, name, connected, paused, address, lastSeen.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
config = await client._get("/rest/config") config = await client._get("/rest/config")
connections = await client._get("/rest/system/connections") connections = await client._get("/rest/system/connections")
stats = await client._get("/rest/stats/device") stats = await client._get("/rest/stats/device")
conn_data = connections.get("connections", {}) conn_data = connections.get("connections", {})
result = [] result = [
for dev in config.get("devices", []): format_device(
did = dev["deviceID"] dev,
conn = conn_data.get(did, {}) conn_data.get(dev["deviceID"]),
stat = stats.get(did, {}) stats.get(dev["deviceID"]),
result.append( concise=params.concise,
{
"deviceID": did,
"name": dev.get("name", did[:8]),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"lastSeen": stat.get("lastSeen", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
}
) )
return json.dumps(result, indent=2) for dev in config.get("devices", [])
]
return fmt(result, concise=params.concise)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -65,34 +50,26 @@ async def syncthing_list_devices(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_device_completion(params: DeviceInput) -> str: async def syncthing_device_completion(params: DeviceReadParams) -> str:
"""Get the aggregated sync completion for a specific remote device across all shared folders. """Aggregated sync completion for a remote device across all shared folders."""
Args:
params: DeviceInput with device_id.
Returns:
str: JSON with overall completion %, globalBytes, needBytes for that device.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
comp = await client._get( comp = await client._get(
"/rest/db/completion", params={"device": params.device_id} "/rest/db/completion", params={"device": params.device_id}
) )
return json.dumps( data: dict[str, Any] = {
{ "device": params.device_id[:8] if params.concise else params.device_id,
"deviceID": params.device_id, "instance": client.name,
"instance": client.name, "completion": round(comp.get("completion", 0), 2),
"completion": round(comp.get("completion", 0), 2), "needSize": format_bytes(comp.get("needBytes", 0)),
"globalBytes": comp.get("globalBytes", 0), "remoteState": comp.get("remoteState", "unknown"),
"globalSize": format_bytes(comp.get("globalBytes", 0)), }
"needBytes": comp.get("needBytes", 0), if not params.concise:
"needSize": format_bytes(comp.get("needBytes", 0)), data["globalBytes"] = comp.get("globalBytes", 0)
"needItems": comp.get("needItems", 0), data["globalSize"] = format_bytes(comp.get("globalBytes", 0))
"remoteState": comp.get("remoteState", "unknown"), data["needBytes"] = comp.get("needBytes", 0)
}, data["needItems"] = comp.get("needItems", 0)
indent=2, return fmt(data, concise=params.concise)
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -107,13 +84,8 @@ async def syncthing_device_completion(params: DeviceInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_connections(params: EmptyInput) -> str: async def syncthing_connections(params: ReadParams) -> str:
"""Get current connection details for all devices. """Current connection details for all devices."""
Returns:
str: JSON with per-device connection info including address,
bytes transferred, crypto, and connection type.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
connections = await client._get("/rest/system/connections") 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]) d["deviceID"]: d.get("name", d["deviceID"][:8])
for d in config.get("devices", []) for d in config.get("devices", [])
} }
result = [] result = [
for did, conn in connections.get("connections", {}).items(): format_connection(
result.append( did, conn, devices_map.get(did, did[:8]), concise=params.concise,
{
"deviceID": did,
"deviceName": devices_map.get(did, did[:8]),
"connected": conn.get("connected", False),
"paused": conn.get("paused", False),
"address": conn.get("address", ""),
"type": conn.get("type", ""),
"crypto": conn.get("crypto", ""),
"inBytesTotal": conn.get("inBytesTotal", 0),
"outBytesTotal": conn.get("outBytesTotal", 0),
}
) )
return json.dumps(result, indent=2) 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: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
+209 -390
View File
@@ -1,21 +1,25 @@
"""Folder status, completion, replication, operations, and file-level query tools.""" """Folder status, completion, replication, operations, and file-level query tools."""
import json
from typing import Any 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 ( from syncthing_mcp.models import (
BrowseFolderInput, BrowseFolderInput,
FileInfoInput, FileInfoInput,
FolderInput,
FolderNeedInput, FolderNeedInput,
PauseFolderInput, FolderReadParams,
EmptyInput, FolderWriteParams,
) ReadParams,
from syncthing_mcp.registry import ( RemoteNeedInput,
format_bytes,
get_instance,
handle_error_global,
) )
from syncthing_mcp.registry import get_instance, handle_error_global
from syncthing_mcp.server import mcp from syncthing_mcp.server import mcp
@@ -34,48 +38,23 @@ from syncthing_mcp.server import mcp
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_folder_status(params: FolderInput) -> str: async def syncthing_folder_status(params: FolderReadParams) -> str:
"""Get detailed status for a specific folder — local/global file counts, bytes, sync state. """Detailed status for a folder — file counts, bytes, sync state.
Note: expensive call on the Syncthing side. Use sparingly."""
Note: This is an expensive call on the Syncthing side. Use sparingly.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with globalBytes, globalFiles, localBytes, localFiles, needBytes,
needFiles, state, stateChanged, and human-readable size strings.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
status = await client._get("/rest/db/status", params={"folder": params.folder_id}) status = await client._get("/rest/db/status", params={"folder": params.folder_id})
stats = await client._get("/rest/stats/folder") stats = await client._get("/rest/stats/folder")
folder_stats = stats.get(params.folder_id, {}) folder_stats = stats.get(params.folder_id, {})
return json.dumps( data: dict[str, Any] = {
{ "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, **format_folder_status(status, concise=params.concise),
"state": status.get("state"), }
"stateChanged": status.get("stateChanged"), if not params.concise:
"globalFiles": status.get("globalFiles"), data["lastScan"] = folder_stats.get("lastScan", "")
"globalBytes": status.get("globalBytes"), data["lastFile"] = folder_stats.get("lastFile", {})
"globalSize": format_bytes(status.get("globalBytes", 0)), return fmt(data, concise=params.concise)
"localFiles": status.get("localFiles"),
"localBytes": status.get("localBytes"),
"localSize": format_bytes(status.get("localBytes", 0)),
"needFiles": status.get("needFiles"),
"needBytes": status.get("needBytes"),
"needSize": format_bytes(status.get("needBytes", 0)),
"inSyncFiles": status.get("inSyncFiles"),
"inSyncBytes": status.get("inSyncBytes"),
"globalDeleted": status.get("globalDeleted"),
"localDeleted": status.get("localDeleted"),
"ignorePatterns": status.get("ignorePatterns"),
"lastScan": folder_stats.get("lastScan", ""),
"lastFile": folder_stats.get("lastFile", {}),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -90,19 +69,9 @@ async def syncthing_folder_status(params: FolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_folder_completion(params: FolderInput) -> str: async def syncthing_folder_completion(params: FolderReadParams) -> str:
"""Get the replication completion percentage for a folder across ALL devices that share it. """Per-device replication completion % for a folder. Key tool for
determining if a folder is fully replicated before local removal."""
This is the key tool for determining whether a folder is fully replicated
on remote devices before removing it locally.
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with folder info and per-device completion percentages,
including whether each device is connected and has a valid remote state.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
config = await client._get("/rest/config") config = await client._get("/rest/config")
@@ -117,7 +86,7 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
folder_cfg = f folder_cfg = f
break break
if not folder_cfg: 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 = { devices_map = {
d["deviceID"]: d.get("name", d["deviceID"][:8]) d["deviceID"]: d.get("name", d["deviceID"][:8])
@@ -128,54 +97,38 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
did = dev.get("deviceID", "") did = dev.get("deviceID", "")
if did == my_id: if did == my_id:
continue continue
connected = conn_data.get(did, {}).get("connected", False)
try: try:
comp = await client._get( comp = await client._get(
"/rest/db/completion", "/rest/db/completion",
params={"folder": params.folder_id, "device": did}, params={"folder": params.folder_id, "device": did},
) )
connected = conn_data.get(did, {}).get("connected", False) completions.append(format_completion(
completions.append( comp,
{ devices_map.get(did, did[:8]),
"deviceID": did, connected=connected,
"deviceName": devices_map.get(did, did[:8]), concise=params.concise,
"connected": connected, ))
"completion": round(comp.get("completion", 0), 2),
"globalBytes": comp.get("globalBytes", 0),
"globalSize": format_bytes(comp.get("globalBytes", 0)),
"needBytes": comp.get("needBytes", 0),
"needSize": format_bytes(comp.get("needBytes", 0)),
"needItems": comp.get("needItems", 0),
"needDeletes": comp.get("needDeletes", 0),
"remoteState": comp.get("remoteState", "unknown"),
}
)
except Exception: except Exception:
completions.append( completions.append({
{ "device": devices_map.get(did, did[:8]),
"deviceID": did, "connected": False,
"deviceName": devices_map.get(did, did[:8]), "completion": None,
"connected": False, "error": "unreachable",
"completion": None, })
"error": "Could not query completion for this device.",
}
)
fully_replicated_count = sum( fully = sum(
1 1 for c in completions
for c in completions
if c.get("completion") == 100 and c.get("remoteState") == "valid" if c.get("completion") == 100 and c.get("remoteState") == "valid"
) )
return json.dumps( return fmt({
{ "folder": params.folder_id,
"folder": params.folder_id, "label": folder_cfg.get("label", params.folder_id),
"label": folder_cfg.get("label", params.folder_id), "instance": client.name,
"instance": client.name, "remoteDevices": len(completions),
"totalRemoteDevices": len(completions), "fullyReplicated": fully,
"fullyReplicatedOn": fully_replicated_count, "devices": completions,
"devices": completions, }, concise=params.concise)
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -190,22 +143,9 @@ async def syncthing_folder_completion(params: FolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_replication_report(params: EmptyInput) -> str: async def syncthing_replication_report(params: ReadParams) -> str:
"""Generate a comprehensive replication report for ALL folders on this device. """Replication analysis for ALL folders. Shows safe-to-remove flag and
reclaimable space. Primary tool for disk-space cleanup decisions."""
For each folder, shows:
- Local disk usage (bytes and human-readable)
- Number of remote devices sharing it
- How many of those have a 100% complete, valid replica
- A 'safeToRemove' flag: True when at least one remote device has a full valid replica
- A 'reclaimableBytes' total for folders that are safe to remove
This is the primary tool for deciding which folders to remove to free local disk space.
Returns:
str: JSON with per-folder replication analysis and a summary section with
total reclaimable space.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
config = await client._get("/rest/config") config = await client._get("/rest/config")
@@ -224,19 +164,12 @@ async def syncthing_replication_report(params: EmptyInput) -> str:
for folder_cfg in folders: for folder_cfg in folders:
fid = folder_cfg["id"] fid = folder_cfg["id"]
label = folder_cfg.get("label", fid)
paused = folder_cfg.get("paused", False)
try: try:
fstatus = await client._get("/rest/db/status", params={"folder": fid}) fstatus = await client._get("/rest/db/status", params={"folder": fid})
except Exception: 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 continue
local_bytes = fstatus.get("localBytes", 0)
global_bytes = fstatus.get("globalBytes", 0)
state = fstatus.get("state", "unknown")
remote_devices = [ remote_devices = [
d for d in folder_cfg.get("devices", []) if d.get("deviceID") != my_id 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", "/rest/db/completion",
params={"folder": fid, "device": did}, params={"folder": fid, "device": did},
) )
device_completions.append( device_completions.append(format_completion(
{ comp,
"deviceID": did, devices_map.get(did, did[:8]),
"deviceName": devices_map.get(did, did[:8]), connected=connected,
"connected": connected, concise=params.concise,
"completion": round(comp.get("completion", 0), 2), ))
"remoteState": comp.get("remoteState", "unknown"),
"needBytes": comp.get("needBytes", 0),
}
)
except Exception: except Exception:
device_completions.append( device_completions.append({
{ "device": devices_map.get(did, did[:8]),
"deviceID": did, "connected": connected,
"deviceName": devices_map.get(did, did[:8]), "completion": None,
"connected": connected, "remoteState": "unknown",
"completion": None, })
"remoteState": "unknown",
}
)
fully_replicated = [ entry = format_replication_entry(
d folder_cfg, fstatus, device_completions, concise=params.concise,
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,
}
) )
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( return fmt({
{ "instance": client.name,
"instance": client.name, "summary": {
"summary": { "total": len(report),
"totalFolders": len(report), "safe": sum(1 for r in report if r.get("safe") or r.get("safeToRemove")),
"safeToRemoveCount": sum(1 for r in report if r.get("safeToRemove")), "reclaimable": format_bytes(total_reclaimable),
"totalReclaimableBytes": total_reclaimable,
"totalReclaimableSize": format_bytes(total_reclaimable),
},
"folders": report,
}, },
indent=2, "folders": report,
) }, concise=params.concise)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -334,36 +237,19 @@ async def syncthing_replication_report(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_pause_folder(params: PauseFolderInput) -> str: async def syncthing_pause_folder(params: FolderWriteParams) -> str:
"""Pause syncing for a specific folder. Useful before removing data locally. """Pause syncing for a folder. Does NOT delete data — only stops sync
so you can safely remove the local copy without propagating deletions."""
This does NOT delete data — it only pauses sync activity so you can safely
remove the local copy without Syncthing propagating the deletion to other devices.
Args:
params: PauseFolderInput with folder_id.
Returns:
str: Confirmation message.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}") folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_cfg["paused"] = True folder_cfg["paused"] = True
await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg) await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg)
return json.dumps( return fmt({
{ "status": "paused",
"status": "paused", "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, })
"message": (
f"Folder '{params.folder_id}' is now paused. "
"Syncthing will NOT sync changes (including deletions) for this folder. "
"You can now safely remove the local data without affecting remote copies."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -378,40 +264,22 @@ async def syncthing_pause_folder(params: PauseFolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_resume_folder(params: PauseFolderInput) -> str: async def syncthing_resume_folder(params: FolderWriteParams) -> str:
"""Resume syncing for a previously paused folder. """Resume syncing for a paused folder. WARNING: if local data was deleted
while paused, behaviour depends on folder type (sendreceive may propagate
WARNING: If you deleted local data while paused, resuming will cause Syncthing deletions; receiveonly will re-download)."""
to either re-download the data (receive-only/sendreceive) or propagate deletions
to other devices (sendreceive). Understand the folder type before resuming.
Args:
params: PauseFolderInput with folder_id.
Returns:
str: Confirmation message with warnings.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}") folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}")
folder_type = folder_cfg.get("type", "sendreceive") folder_type = folder_cfg.get("type", "sendreceive")
folder_cfg["paused"] = False folder_cfg["paused"] = False
await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg) await client._patch(f"/rest/config/folders/{params.folder_id}", body=folder_cfg)
return json.dumps( return fmt({
{ "status": "resumed",
"status": "resumed", "folder": params.folder_id,
"folder": params.folder_id, "type": folder_type,
"folderType": folder_type, "instance": client.name,
"instance": client.name, })
"message": f"Folder '{params.folder_id}' is now active again (type: {folder_type}).",
"warning": (
"If local data was deleted while paused, behaviour depends on folder type: "
"'sendreceive' may propagate deletions to peers; "
"'receiveonly' will re-download missing files."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -426,29 +294,16 @@ async def syncthing_resume_folder(params: PauseFolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_scan_folder(params: FolderInput) -> str: async def syncthing_scan_folder(params: FolderWriteParams) -> str:
"""Request an immediate rescan of a folder to refresh its status. """Trigger an immediate rescan of a folder to refresh its status."""
Useful to ensure completion data is up to date before deciding to remove files.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that scan was requested.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._post("/rest/db/scan", params={"folder": params.folder_id}) await client._post("/rest/db/scan", params={"folder": params.folder_id})
return json.dumps( return fmt({
{ "status": "scan_requested",
"status": "scan_requested", "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, })
"message": "Scan initiated. Folder status will update shortly.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -463,36 +318,26 @@ async def syncthing_scan_folder(params: FolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_folder_errors(params: FolderInput) -> str: async def syncthing_folder_errors(params: FolderReadParams) -> str:
"""Get current sync errors for a specific folder. """Current sync errors for a specific folder."""
Args:
params: FolderInput with folder_id.
Returns:
str: JSON with error list and count.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
errors = await client._get( errors = await client._get(
"/rest/folder/errors", params={"folder": params.folder_id} "/rest/folder/errors", params={"folder": params.folder_id}
) )
return json.dumps( error_list = errors.get("errors", []) or []
{ return truncate(fmt({
"folder": params.folder_id, "folder": params.folder_id,
"instance": client.name, "instance": client.name,
"errorCount": len(errors.get("errors", []) or []), "count": len(error_list),
"errors": errors.get("errors", []), "errors": error_list,
"page": errors.get("page", 1), }, concise=params.concise))
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_browse_folder(params: BrowseFolderInput) -> str:
"""Browse the contents of a folder at a given path prefix. """Browse folder contents at a path prefix (directory listing from DB)."""
Returns a directory-style listing of files and subdirectories known to
Syncthing's database — useful for inspecting what is being synced without
direct filesystem access.
Args:
params: BrowseFolderInput with folder_id, optional prefix and levels.
Returns:
str: JSON with the folder contents at the requested path.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
query: dict[str, str] = {"folder": params.folder_id} 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: if params.levels is not None:
query["levels"] = str(params.levels) query["levels"] = str(params.levels)
result = await client._get("/rest/db/browse", params=query) result = await client._get("/rest/db/browse", params=query)
return json.dumps( return truncate(fmt({
{ "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, "prefix": params.prefix or "",
"prefix": params.prefix or "", "entries": result,
"entries": result, }, concise=params.concise))
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_file_info(params: FileInfoInput) -> str:
"""Get detailed information about a specific file within a folder. """Detailed info about a file — versions, availability, modification time."""
Returns version vectors, availability on devices, modification time,
size, and whether the file is locally present. Useful for diagnosing
sync conflicts or understanding file state across the cluster.
Args:
params: FileInfoInput with folder_id and file_path.
Returns:
str: JSON with file metadata including global and local info.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get( result = await client._get(
"/rest/db/file", "/rest/db/file",
params={"folder": params.folder_id, "file": params.file_path}, 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"): for key in ("global", "local"):
entry = result.get(key) entry = result.get(key)
if isinstance(entry, dict) and "size" in entry: if isinstance(entry, dict) and "size" in entry:
entry["sizeFormatted"] = format_bytes(entry["size"]) entry["sizeFormatted"] = format_bytes(entry["size"])
return json.dumps( return fmt({
{ "folder": params.folder_id,
"folder": params.folder_id, "file": params.file_path,
"file": params.file_path, "instance": client.name,
"instance": client.name, "availability": result.get("availability"),
"availability": result.get("availability"), "global": result.get("global"),
"global": result.get("global"), "local": result.get("local"),
"local": result.get("local"), }, concise=False)
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(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: async def syncthing_folder_need(params: FolderNeedInput) -> str:
"""List files that the folder still needs — items that are out of sync locally. """Files this folder still needs — items that are out of sync locally."""
Supports pagination for large result sets.
Args:
params: FolderNeedInput with folder_id, page, per_page.
Returns:
str: JSON with lists of files needed (progress, queued, rest) and a total page count.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get( result = await client._get(
@@ -620,24 +439,59 @@ async def syncthing_folder_need(params: FolderNeedInput) -> str:
"perpage": str(params.per_page), "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, "folder": params.folder_id,
"instance": client.name, "device": params.device_id,
"page": result.get("page", params.page), "page": str(params.page),
"perpage": result.get("perpage", params.per_page), "perpage": str(params.per_page),
"progress": result.get("progress", []),
"queued": result.get("queued", []),
"rest": result.get("rest", []),
}, },
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: except Exception as e:
return handle_error_global(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, "openWorldHint": False,
}, },
) )
async def syncthing_override_folder(params: FolderInput) -> str: async def syncthing_override_folder(params: FolderWriteParams) -> str:
"""Override remote changes on a send-only folder, making local state authoritative. """Override remote changes on a send-only folder (make local authoritative)."""
Use this when a send-only folder shows 'out of sync' items that you want
to push to remote devices. Only meaningful for folders configured as
'sendonly'.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that the override was requested.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._post("/rest/db/override", params={"folder": params.folder_id}) await client._post("/rest/db/override", params={"folder": params.folder_id})
return json.dumps( return fmt({
{ "status": "override_requested",
"status": "override_requested", "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, })
"message": (
f"Override requested for folder '{params.folder_id}'. "
"Local state will be pushed to remote devices."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -693,32 +529,15 @@ async def syncthing_override_folder(params: FolderInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_revert_folder(params: FolderInput) -> str: async def syncthing_revert_folder(params: FolderWriteParams) -> str:
"""Revert local changes on a receive-only folder, pulling the remote state. """Revert local changes on a receive-only folder (pull remote state)."""
Use this when a receive-only folder has local modifications that should be
discarded in favour of the remote version.
Args:
params: FolderInput with folder_id.
Returns:
str: Confirmation that the revert was requested.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._post("/rest/db/revert", params={"folder": params.folder_id}) await client._post("/rest/db/revert", params={"folder": params.folder_id})
return json.dumps( return fmt({
{ "status": "revert_requested",
"status": "revert_requested", "folder": params.folder_id,
"folder": params.folder_id, "instance": client.name,
"instance": client.name, })
"message": (
f"Revert requested for folder '{params.folder_id}'. "
"Local changes will be replaced by the remote state."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
+32 -42
View File
@@ -1,11 +1,10 @@
"""Tools for instance management and listing folders (config-level).""" """Tools for instance management and listing folders (config-level)."""
import json
from typing import Any 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 ( from syncthing_mcp.registry import (
format_bytes,
get_all_instances, get_all_instances,
get_instance, get_instance,
handle_error_global, handle_error_global,
@@ -23,12 +22,8 @@ from syncthing_mcp.server import mcp
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_list_instances(params: EmptyInput) -> str: async def syncthing_list_instances(params: ReadParams) -> str:
"""List all configured Syncthing instances and probe their availability. """List all configured Syncthing instances and probe their availability."""
Returns:
str: JSON array with instance name, URL, availability, and device ID.
"""
results = [] results = []
for name, client in get_all_instances().items(): for name, client in get_all_instances().items():
entry: dict[str, Any] = {"name": name, "url": client.url} 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: if dev.get("deviceID") == my_id:
my_name = dev.get("name", my_id[:8]) my_name = dev.get("name", my_id[:8])
break break
entry.update( entry.update({
{ "available": True,
"available": True, "deviceName": my_name,
"myID": my_id, "version": version.get("version"),
"deviceName": my_name, "folders": len(config.get("folders", [])),
"version": version.get("version"), "devices": len(config.get("devices", [])),
"numFolders": len(config.get("folders", [])), })
"numDevices": len(config.get("devices", [])), if not params.concise:
} entry["myID"] = my_id
)
except Exception as exc: except Exception as exc:
entry.update({"available": False, "error": str(exc)}) entry.update({"available": False, "error": str(exc)})
results.append(entry) results.append(entry)
return json.dumps(results, indent=2) return fmt(results, concise=params.concise)
@mcp.tool( @mcp.tool(
@@ -68,37 +62,33 @@ async def syncthing_list_instances(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_list_folders(params: EmptyInput) -> str: async def syncthing_list_folders(params: ReadParams) -> str:
"""List all configured Syncthing folders with their labels, paths, type, and shared devices. """All configured folders with labels, types, and device counts."""
Returns:
str: JSON array of folders with id, label, path, type, paused, and list of shared device names/IDs.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
config = await client._get("/rest/config") config = await client._get("/rest/config")
folders = config.get("folders", []) folders = config.get("folders", [])
devices = { if params.concise:
d["deviceID"]: d.get("name", d["deviceID"][:8]) result = [format_folder(f, concise=True) for f in folders]
for d in config.get("devices", []) else:
} devices_map = {
result = [] d["deviceID"]: d.get("name", d["deviceID"][:8])
for f in folders: for d in config.get("devices", [])
shared = [] }
for d in f.get("devices", []): result = []
did = d.get("deviceID", "") for f in folders:
shared.append({"deviceID": did, "name": devices.get(did, did[:8])}) shared = [
result.append( {"deviceID": d.get("deviceID", ""), "name": devices_map.get(d.get("deviceID", ""), "")}
{ for d in f.get("devices", [])
]
result.append({
"id": f["id"], "id": f["id"],
"label": f.get("label", f["id"]), "label": f.get("label", f["id"]),
"path": f.get("path", ""), "path": f.get("path", ""),
"type": f.get("type", "sendreceive"), "type": f.get("type", "sendreceive"),
"paused": f.get("paused", False), "paused": f.get("paused", False),
"sharedWith": shared, "sharedWith": shared,
"numDevices": len(shared), })
} return fmt(result, concise=params.concise)
)
return json.dumps(result, indent=2)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
+111 -191
View File
@@ -1,16 +1,12 @@
"""System status, health, errors, log, restart, and upgrade tools.""" """System status, health, errors, log, restart, and upgrade tools."""
import json
from typing import Any from typing import Any
import httpx import httpx
from syncthing_mcp.models import EmptyInput from syncthing_mcp.formatters import fmt, format_bytes, truncate
from syncthing_mcp.registry import ( from syncthing_mcp.models import ReadParams, WriteParams
format_bytes, from syncthing_mcp.registry import get_instance, handle_error_global
get_instance,
handle_error_global,
)
from syncthing_mcp.server import mcp from syncthing_mcp.server import mcp
@@ -24,12 +20,8 @@ from syncthing_mcp.server import mcp
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_system_status(params: EmptyInput) -> str: async def syncthing_system_status(params: ReadParams) -> str:
"""Get Syncthing system status including this device's ID, name, uptime, and version. """Device ID, name, uptime, version, and folder/device counts."""
Returns:
str: JSON with myID, device name, uptime, version, and connection stats.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
status = await client._get("/rest/system/status") 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: if dev.get("deviceID") == my_id:
my_name = dev.get("name", my_id[:8]) my_name = dev.get("name", my_id[:8])
break break
return json.dumps( data: dict[str, Any] = {
{ "instance": client.name,
"instance": client.name, "myID": my_id[:8] if params.concise else my_id,
"myID": my_id, "deviceName": my_name,
"deviceName": my_name, "uptime": status.get("uptime"),
"uptime": status.get("uptime"), "version": version.get("version"),
"version": version.get("version"), "folders": len(config.get("folders", [])),
"os": version.get("os"), "devices": len(config.get("devices", [])),
"arch": version.get("arch"), }
"numFolders": len(config.get("folders", [])), if not params.concise:
"numDevices": len(config.get("devices", [])), data["os"] = version.get("os")
}, data["arch"] = version.get("arch")
indent=2, return fmt(data, concise=params.concise)
)
except Exception as e: except Exception as e:
if isinstance(e, ValueError): if isinstance(e, ValueError):
return handle_error_global(e) return handle_error_global(e)
@@ -74,24 +65,18 @@ async def syncthing_system_status(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_system_errors(params: EmptyInput) -> str: async def syncthing_system_errors(params: ReadParams) -> str:
"""Get recent system errors and warnings from Syncthing. """Recent system errors and warnings."""
Returns:
str: JSON with error list, each containing 'when' timestamp and 'message'.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get("/rest/system/error") result = await client._get("/rest/system/error")
errors = result.get("errors", []) or [] errors = result.get("errors", []) or []
return json.dumps( data: dict[str, Any] = {
{ "instance": client.name,
"instance": client.name, "count": len(errors),
"errorCount": len(errors), "errors": errors,
"errors": errors, }
}, return truncate(fmt(data, concise=params.concise))
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -106,23 +91,12 @@ async def syncthing_system_errors(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_clear_errors(params: EmptyInput) -> str: async def syncthing_clear_errors(params: WriteParams) -> str:
"""Clear the system error log. """Clear the system error log."""
Returns:
str: Confirmation message.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
await client._post("/rest/system/error/clear") await client._post("/rest/system/error/clear")
return json.dumps( return fmt({"status": "cleared", "instance": client.name})
{
"status": "cleared",
"instance": client.name,
"message": "System error log has been cleared.",
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -137,25 +111,18 @@ async def syncthing_clear_errors(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_system_log(params: EmptyInput) -> str: async def syncthing_system_log(params: ReadParams) -> str:
"""Get recent system log entries from Syncthing. """Recent system log entries."""
Returns:
str: JSON with log messages, each containing 'when' timestamp, 'message',
and 'level'.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get("/rest/system/log") result = await client._get("/rest/system/log")
messages = result.get("messages", []) or [] messages = result.get("messages", []) or []
return json.dumps( data: dict[str, Any] = {
{ "instance": client.name,
"instance": client.name, "count": len(messages),
"messageCount": len(messages), "messages": messages,
"messages": messages, }
}, return truncate(fmt(data, concise=params.concise))
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -170,14 +137,8 @@ async def syncthing_system_log(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_recent_changes(params: EmptyInput) -> str: async def syncthing_recent_changes(params: ReadParams) -> str:
"""Get recent file change events (local and remote) across all folders. """Recent file change events (local and remote) across all folders."""
Uses a non-blocking poll of the Syncthing event stream with limit=50.
Returns:
str: JSON with recent LocalChangeDetected and RemoteChangeDetected events.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
events = await client._get( events = await client._get(
@@ -190,14 +151,22 @@ async def syncthing_recent_changes(params: EmptyInput) -> str:
) )
if not isinstance(events, list): if not isinstance(events, list):
events = [] events = []
return json.dumps( if params.concise:
{ events = [
"instance": client.name, {
"eventCount": len(events), "type": e.get("type", "")[:6], # "Local" or "Remote"
"events": events, "folder": e.get("data", {}).get("folderID", ""),
}, "path": e.get("data", {}).get("path", ""),
indent=2, "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: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -212,22 +181,15 @@ async def syncthing_recent_changes(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_restart_required(params: EmptyInput) -> str: async def syncthing_restart_required(params: ReadParams) -> str:
"""Check if Syncthing requires a restart for configuration changes to take effect. """Check if Syncthing requires a restart for config changes to take effect."""
Returns:
str: JSON with restartRequired boolean.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
result = await client._get("/rest/config/restart-required") result = await client._get("/rest/config/restart-required")
return json.dumps( return fmt({
{ "instance": client.name,
"instance": client.name, "restartRequired": result.get("requiresRestart", False),
"restartRequired": result.get("requiresRestart", False), })
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -242,31 +204,19 @@ async def syncthing_restart_required(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_restart(params: EmptyInput) -> str: async def syncthing_restart(params: WriteParams) -> str:
"""Restart the Syncthing service to apply pending configuration changes. """Restart the Syncthing service. Temporarily stops all sync activity."""
WARNING: This temporarily stops synchronization on all folders for this instance.
Returns:
str: Confirmation message.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
try: try:
await client._post("/rest/system/restart") await client._post("/rest/system/restart")
except (httpx.ConnectError, httpx.RemoteProtocolError): except (httpx.ConnectError, httpx.RemoteProtocolError):
pass # Expected — Syncthing closes the connection as it restarts pass # Expected — Syncthing closes the connection as it restarts
return json.dumps( return fmt({
{ "status": "restart_initiated",
"status": "restart_initiated", "instance": client.name,
"instance": client.name, "message": f"Syncthing '{client.name}' is restarting.",
"message": ( })
f"Syncthing on '{client.name}' is restarting. "
"Connection may be lost briefly. Sync resumes automatically."
),
},
indent=2,
)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -281,38 +231,26 @@ async def syncthing_restart(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_check_upgrade(params: EmptyInput) -> str: async def syncthing_check_upgrade(params: ReadParams) -> str:
"""Check if a newer version of Syncthing is available. """Check if a newer version of Syncthing is available."""
Returns:
str: JSON with running version, latest version, and whether an upgrade
is available.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
version = await client._get("/rest/system/version") version = await client._get("/rest/system/version")
try: try:
upgrade = await client._get("/rest/system/upgrade") upgrade = await client._get("/rest/system/upgrade")
return json.dumps( return fmt({
{ "instance": client.name,
"instance": client.name, "running": version.get("version"),
"running": version.get("version"), "latest": upgrade.get("latest"),
"latest": upgrade.get("latest"), "newer": upgrade.get("newer", False),
"newer": upgrade.get("newer", False), }, concise=params.concise)
"majorNewer": upgrade.get("majorNewer", False),
},
indent=2,
)
except httpx.HTTPStatusError as ue: except httpx.HTTPStatusError as ue:
if ue.response.status_code == 501: if ue.response.status_code == 501:
return json.dumps( return fmt({
{ "instance": client.name,
"instance": client.name, "running": version.get("version"),
"running": version.get("version"), "upgradeCheck": "unavailable",
"message": "Upgrade check not available (disabled or unsupported).", })
},
indent=2,
)
raise raise
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
@@ -328,16 +266,9 @@ async def syncthing_check_upgrade(params: EmptyInput) -> str:
"openWorldHint": False, "openWorldHint": False,
}, },
) )
async def syncthing_health_summary(params: EmptyInput) -> str: async def syncthing_health_summary(params: ReadParams) -> str:
"""Generate a single-call health overview: system status, folder states, """Single-call health overview: system status, folder states, device
device connectivity, errors, and pending items. connectivity, errors, and pending items. Start here for quick triage."""
Designed for quick triage — aggregates data from multiple endpoints.
Returns:
str: JSON with overall status ('good', 'warning', 'error'), summary
counts, alert list, and per-folder health.
"""
try: try:
client = get_instance(params.instance) client = get_instance(params.instance)
@@ -368,31 +299,25 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
for f_cfg in folders: for f_cfg in folders:
fid = f_cfg["id"] 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): if f_cfg.get("paused", False):
paused_count += 1 paused_count += 1
entry["state"] = "paused" folder_health.append({"id": fid, "state": "paused"})
else: else:
try: try:
fstatus = await client._get( fstatus = await client._get(
"/rest/db/status", params={"folder": fid} "/rest/db/status", params={"folder": fid}
) )
state = fstatus.get("state", "unknown") state = fstatus.get("state", "unknown")
entry["state"] = state entry: dict[str, Any] = {"id": fid, "state": state}
entry["needBytes"] = fstatus.get("needBytes", 0)
entry["needSize"] = format_bytes(fstatus.get("needBytes", 0))
if state in ("syncing", "sync-preparing"): if state in ("syncing", "sync-preparing"):
syncing_count += 1 syncing_count += 1
entry["needSize"] = format_bytes(fstatus.get("needBytes", 0))
elif state == "error": elif state == "error":
error_folders += 1 error_folders += 1
folder_health.append(entry)
except Exception: except Exception:
entry["state"] = "unreachable"
error_folders += 1 error_folders += 1
folder_health.append(entry) folder_health.append({"id": fid, "state": "unreachable"})
alerts: list[str] = [] alerts: list[str] = []
error_list = sys_errors.get("errors", []) or [] error_list = sys_errors.get("errors", []) or []
@@ -406,13 +331,13 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
if paused_count > 0: if paused_count > 0:
alerts.append(f"{paused_count} folder(s) paused") alerts.append(f"{paused_count} folder(s) paused")
if syncing_count > 0: 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_dev = len(pending_devices) if isinstance(pending_devices, dict) else 0
num_pending_fld = len(pending_folders) if isinstance(pending_folders, dict) else 0 num_pending_fld = len(pending_folders) if isinstance(pending_folders, dict) else 0
if num_pending_dev > 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: 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: if error_folders > 0 or len(error_list) > 0:
overall = "error" overall = "error"
@@ -421,30 +346,25 @@ async def syncthing_health_summary(params: EmptyInput) -> str:
else: else:
overall = "good" overall = "good"
return json.dumps( data: dict[str, Any] = {
{ "instance": client.name,
"instance": client.name, "status": overall,
"status": overall, "uptime": sys_status.get("uptime"),
"uptime": sys_status.get("uptime"), "summary": {
"summary": { "folders": len(folders),
"totalFolders": len(folders), "idle": sum(1 for f in folder_health if f.get("state") == "idle"),
"foldersIdle": sum( "syncing": syncing_count,
1 for f in folder_health if f.get("state") == "idle" "paused": paused_count,
), "errors": error_folders,
"foldersSyncing": syncing_count, "devicesOnline": online_count,
"foldersPaused": paused_count, "devicesOffline": offline_count,
"foldersError": error_folders, "pendingDevices": num_pending_dev,
"totalDevices": len(config.get("devices", [])), "pendingFolders": num_pending_fld,
"devicesOnline": online_count,
"devicesOffline": offline_count,
"systemErrors": len(error_list),
"pendingDevices": num_pending_dev,
"pendingFolders": num_pending_fld,
},
"alerts": alerts,
"folders": folder_health,
}, },
indent=2, "alerts": alerts,
) }
if not params.concise:
data["folders"] = folder_health
return fmt(data, concise=params.concise)
except Exception as e: except Exception as e:
return handle_error_global(e) return handle_error_global(e)
+1 -1
View File
@@ -140,7 +140,7 @@ class TestSetIgnores:
SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"]) SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"])
)) ))
assert result["status"] == "updated" assert result["status"] == "updated"
assert result["patternCount"] == 2 assert result["count"] == 2
class TestGetDefaultIgnores: class TestGetDefaultIgnores:
+11 -2
View File
@@ -1,4 +1,4 @@
"""Tests for device tools (list, completion, connections).""" """Tests for device tools (list, completion, connections, stats)."""
import json import json
@@ -41,7 +41,7 @@ class TestDeviceCompletion:
DeviceInput(device_id=DEVICE_ID_REMOTE) DeviceInput(device_id=DEVICE_ID_REMOTE)
)) ))
assert result["completion"] == 100.0 assert result["completion"] == 100.0
assert result["needBytes"] == 0 assert result["needSize"] == "0.0 B"
class TestConnections: class TestConnections:
@@ -51,3 +51,12 @@ class TestConnections:
result = json.loads(await syncthing_connections(EmptyInput())) result = json.loads(await syncthing_connections(EmptyInput()))
assert len(result) == 2 assert len(result) == 2
assert any(c["connected"] for c in result) 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]
+9 -8
View File
@@ -52,7 +52,7 @@ class TestFolderCompletion:
mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) mock_api.get("/rest/db/completion").respond(json=make_completion(100.0))
result = json.loads(await syncthing_folder_completion(FolderInput(folder_id=FOLDER_ID))) 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 assert result["devices"][0]["completion"] == 100.0
async def test_partially_replicated(self, mock_api): 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")) 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))) 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): async def test_folder_not_found(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_folder_completion 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/status").respond(json=make_db_status())
mock_api.get("/rest/db/completion").respond(json=make_completion(100.0)) mock_api.get("/rest/db/completion").respond(json=make_completion(100.0))
result = json.loads(await syncthing_replication_report(EmptyInput())) result = json.loads(await syncthing_replication_report(EmptyInput()))
assert result["summary"]["safeToRemoveCount"] == 1 assert result["summary"]["safe"] == 1
assert result["folders"][0]["safeToRemove"] is True assert result["folders"][0]["safe"] is True
async def test_not_safe_when_incomplete(self, mock_api): async def test_not_safe_when_incomplete(self, mock_api):
from syncthing_mcp.tools.folders import syncthing_replication_report 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/status").respond(json=make_db_status())
mock_api.get("/rest/db/completion").respond(json=make_completion(50.0)) mock_api.get("/rest/db/completion").respond(json=make_completion(50.0))
result = json.loads(await syncthing_replication_report(EmptyInput())) result = json.loads(await syncthing_replication_report(EmptyInput()))
assert result["summary"]["safeToRemoveCount"] == 0 assert result["summary"]["safe"] == 0
class TestPauseFolder: class TestPauseFolder:
@@ -116,7 +116,7 @@ class TestResumeFolder:
) )
result = json.loads(await syncthing_resume_folder(PauseFolderInput(folder_id=FOLDER_ID))) result = json.loads(await syncthing_resume_folder(PauseFolderInput(folder_id=FOLDER_ID)))
assert result["status"] == "resumed" assert result["status"] == "resumed"
assert result["folderType"] == "sendreceive" assert result["type"] == "sendreceive"
class TestScanFolder: class TestScanFolder:
@@ -134,7 +134,7 @@ class TestFolderErrors:
mock_api.get("/rest/folder/errors").respond(json={"errors": None, "page": 1}) mock_api.get("/rest/folder/errors").respond(json={"errors": None, "page": 1})
result = json.loads(await syncthing_folder_errors(FolderInput(folder_id=FOLDER_ID))) result = json.loads(await syncthing_folder_errors(FolderInput(folder_id=FOLDER_ID)))
assert result["errorCount"] == 0 assert result["count"] == 0
class TestBrowseFolder: class TestBrowseFolder:
@@ -172,7 +172,8 @@ class TestFileInfo:
FileInfoInput(folder_id=FOLDER_ID, file_path="test.txt") FileInfoInput(folder_id=FOLDER_ID, file_path="test.txt")
)) ))
assert result["file"] == "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: class TestFolderNeed:
+8 -7
View File
@@ -33,7 +33,8 @@ class TestSystemStatus:
from syncthing_mcp.tools.system import syncthing_system_status from syncthing_mcp.tools.system import syncthing_system_status
result = json.loads(await syncthing_system_status(EmptyInput())) 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["deviceName"] == "local-dev"
assert result["version"] == "v1.28.0" assert result["version"] == "v1.28.0"
assert result["instance"] == "default" assert result["instance"] == "default"
@@ -44,7 +45,7 @@ class TestSystemErrors:
from syncthing_mcp.tools.system import syncthing_system_errors from syncthing_mcp.tools.system import syncthing_system_errors
result = json.loads(await syncthing_system_errors(EmptyInput())) result = json.loads(await syncthing_system_errors(EmptyInput()))
assert result["errorCount"] == 0 assert result["count"] == 0
async def test_with_errors(self, mock_api): async def test_with_errors(self, mock_api):
from syncthing_mcp.tools.system import syncthing_system_errors from syncthing_mcp.tools.system import syncthing_system_errors
@@ -53,7 +54,7 @@ class TestSystemErrors:
json={"errors": [{"when": "2025-01-01", "message": "disk full"}]} json={"errors": [{"when": "2025-01-01", "message": "disk full"}]}
) )
result = json.loads(await syncthing_system_errors(EmptyInput())) result = json.loads(await syncthing_system_errors(EmptyInput()))
assert result["errorCount"] == 1 assert result["count"] == 1
class TestClearErrors: class TestClearErrors:
@@ -70,7 +71,7 @@ class TestSystemLog:
from syncthing_mcp.tools.system import syncthing_system_log from syncthing_mcp.tools.system import syncthing_system_log
result = json.loads(await syncthing_system_log(EmptyInput())) result = json.loads(await syncthing_system_log(EmptyInput()))
assert result["messageCount"] == 0 assert result["count"] == 0
class TestRecentChanges: class TestRecentChanges:
@@ -81,7 +82,7 @@ class TestRecentChanges:
{"id": 1, "type": "LocalChangeDetected", "data": {"path": "file.txt"}} {"id": 1, "type": "LocalChangeDetected", "data": {"path": "file.txt"}}
]) ])
result = json.loads(await syncthing_recent_changes(EmptyInput())) result = json.loads(await syncthing_recent_changes(EmptyInput()))
assert result["eventCount"] == 1 assert result["count"] == 1
class TestRestartRequired: class TestRestartRequired:
@@ -118,7 +119,7 @@ class TestCheckUpgrade:
mock_api.get("/rest/system/upgrade").respond(status_code=501) mock_api.get("/rest/system/upgrade").respond(status_code=501)
result = json.loads(await syncthing_check_upgrade(EmptyInput())) result = json.loads(await syncthing_check_upgrade(EmptyInput()))
assert "not available" in result["message"] assert result["upgradeCheck"] == "unavailable"
class TestHealthSummary: class TestHealthSummary:
@@ -128,7 +129,7 @@ class TestHealthSummary:
mock_api.get("/rest/db/status").respond(json=make_db_status()) mock_api.get("/rest/db/status").respond(json=make_db_status())
result = json.loads(await syncthing_health_summary(EmptyInput())) result = json.loads(await syncthing_health_summary(EmptyInput()))
assert result["status"] == "good" assert result["status"] == "good"
assert result["summary"]["foldersIdle"] == 1 assert result["summary"]["idle"] == 1
async def test_error_state(self, mock_api): async def test_error_state(self, mock_api):
from syncthing_mcp.tools.system import syncthing_health_summary from syncthing_mcp.tools.system import syncthing_health_summary