diff --git a/CHANGELOG.md b/CHANGELOG.md index ccfe02f..b03ce7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to `syncthing-blade-mcp` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [0.9.0] - 2026-06-11 + +### Security + +- **AUD-04-02 / DD-385 Phase W — write gate + confirm discipline (class baseline).** + All 13 mutating tools now require `SYNCTHING_WRITE_ENABLED=true` and refuse + with a clear error when the gate is off. Previously every mutating tool + (override, revert, restart, accept-device, replace-stignore, …) fired + ungated. +- **`confirm=true` required for destructive/disruptive operations:** + `syncthing_override_folder`, `syncthing_revert_folder`, `syncthing_restart`, + `syncthing_accept_device`, `syncthing_accept_folder`, `syncthing_set_ignores`. + The refusal message explains what the operation would do. These tools are + now annotated `destructiveHint: true`. + +### Changed + +- Server-level MCP instructions now document the write gate and confirm + requirements. + ## [0.8.0] - 2026-05-24 ### Changed diff --git a/README.md b/README.md index 5c75eb4..dbf10b7 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing' - **Token-efficient output** — compact JSON by default; `concise=false` for full details - **Multi-instance** — manage multiple Syncthing nodes from a single server +- **Write-gated** — mutating tools require `SYNCTHING_WRITE_ENABLED=true`; destructive operations additionally require `confirm=true` - **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 @@ -98,6 +99,23 @@ Built to give AI assistants (Claude, etc.) read and control access to Syncthing' | `syncthing_get_default_ignores` | Get default ignore patterns | No | | `syncthing_set_default_ignores` | Set default ignore patterns | Yes | +## Write Safety + +All mutating tools (the "Yes" rows above) refuse unless the environment variable +`SYNCTHING_WRITE_ENABLED=true` is set. The gate is off by default. + +Destructive or disruptive operations additionally require `confirm=true` on the +call itself, with a refusal message explaining what the operation will do: + +| Tool | Why confirm is required | +|------|------------------------| +| `syncthing_override_folder` | Pushes local state over remote edits — remote changes discarded cluster-wide | +| `syncthing_revert_folder` | Discards local changes on a receive-only folder | +| `syncthing_restart` | Stops the daemon and interrupts all active sync transfers | +| `syncthing_accept_device` | Admits a pending device into the cluster | +| `syncthing_accept_folder` | Starts syncing a remote folder's contents to local disk | +| `syncthing_set_ignores` | Replaces the folder's entire `.stignore` pattern set | + ## Token Efficiency All read tools default to `concise=true`, producing compact JSON with minimal fields and diff --git a/SKILL.md b/SKILL.md index b3312f7..aa5769c 100644 --- a/SKILL.md +++ b/SKILL.md @@ -103,6 +103,13 @@ replication analysis and safe disk-space reclamation. `syncthing_accept_folder`, `syncthing_reject_folder`, `syncthing_set_ignores`, `syncthing_set_default_ignores` +All write tools require the environment variable `SYNCTHING_WRITE_ENABLED=true` +(off by default). Destructive/disruptive tools — `syncthing_override_folder`, +`syncthing_revert_folder`, `syncthing_restart`, `syncthing_accept_device`, +`syncthing_accept_folder`, `syncthing_set_ignores` — additionally require +`confirm=true` in the call; without it they return a refusal explaining what +the operation would do. + ## Multi-Instance When multiple instances are configured, every tool accepts an `instance` parameter. diff --git a/pyproject.toml b/pyproject.toml index 150f9e3..d87a403 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "syncthing-blade-mcp" -version = "0.8.0" +version = "0.9.0" description = "MCP server for Syncthing — token-efficient replication management, multi-instance, safe disk-space reclamation." requires-python = ">=3.11" dependencies = [ diff --git a/src/syncthing_mcp/__init__.py b/src/syncthing_mcp/__init__.py index 07a7e50..afc1b23 100644 --- a/src/syncthing_mcp/__init__.py +++ b/src/syncthing_mcp/__init__.py @@ -1,3 +1,3 @@ """Syncthing MCP Server — manage Syncthing instances via MCP tools.""" -__version__ = "0.8.0" +__version__ = "0.9.0" diff --git a/src/syncthing_mcp/models.py b/src/syncthing_mcp/models.py index 45128a3..d99b3a0 100644 --- a/src/syncthing_mcp/models.py +++ b/src/syncthing_mcp/models.py @@ -57,6 +57,28 @@ def _resolve_scope_folders( return folder_ids, [] +# --------------------------------------------------------------------------- +# Write gate (AUD-04-02 / DD-385 Phase W) +# --------------------------------------------------------------------------- + + +def is_write_enabled() -> bool: + """Check whether write operations are enabled.""" + return os.environ.get("SYNCTHING_WRITE_ENABLED", "").strip().lower() == "true" + + +def require_write() -> str | None: + """Return an error message if writes are disabled, else None.""" + if is_write_enabled(): + return None + return "Write operations are disabled. Set SYNCTHING_WRITE_ENABLED=true to enable." + + +_CONFIRM_DESCRIPTION = ( + "Must be true to confirm — this operation is destructive or disruptive." +) + + # --------------------------------------------------------------------------- # Read-oriented base models (include concise toggle for token efficiency) # --------------------------------------------------------------------------- @@ -144,6 +166,18 @@ class DeviceWriteParams(WriteParams): ) +class ConfirmWriteParams(WriteParams): + """Write tool requiring explicit confirmation (destructive/disruptive).""" + + confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION) + + +class ConfirmFolderWriteParams(FolderWriteParams): + """Folder write tool requiring explicit confirmation (destructive/disruptive).""" + + confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION) + + # --------------------------------------------------------------------------- # Specialised input models # --------------------------------------------------------------------------- @@ -158,6 +192,7 @@ class AcceptDeviceInput(WriteParams): None, description="Friendly name to assign. If omitted, uses the name from the pending request.", ) + confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION) class AcceptFolderInput(WriteParams): @@ -169,6 +204,7 @@ class AcceptFolderInput(WriteParams): None, description="Local path for the folder. If omitted, uses Syncthing's default path.", ) + confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION) class RejectFolderInput(WriteParams): @@ -189,6 +225,7 @@ class SetIgnoresInput(WriteParams): ..., description="List of ignore patterns (e.g. ['*.tmp', '.DS_Store', '// #include'])", ) + confirm: bool = Field(False, description=_CONFIRM_DESCRIPTION) class SetDefaultIgnoresInput(WriteParams): diff --git a/src/syncthing_mcp/server.py b/src/syncthing_mcp/server.py index d1306aa..3debbca 100644 --- a/src/syncthing_mcp/server.py +++ b/src/syncthing_mcp/server.py @@ -148,6 +148,15 @@ async def app_lifespan(app): mcp = FastMCP( "syncthing_mcp", + instructions=( + "Syncthing replication operations across one or more instances. " + "Monitor folders, devices, and sync health; manage pending devices/" + "folders, ignore patterns, and conflict resolution. Multi-instance: " + "pass instance= to target a specific node. Write operations require " + "SYNCTHING_WRITE_ENABLED=true. Destructive/disruptive operations " + "(override, revert, restart, accept device/folder, replace ignores) " + "also require confirm=true." + ), lifespan=app_lifespan, stateless_http=True, json_response=True, diff --git a/src/syncthing_mcp/tools/config.py b/src/syncthing_mcp/tools/config.py index 4af9e53..1c4f38d 100644 --- a/src/syncthing_mcp/tools/config.py +++ b/src/syncthing_mcp/tools/config.py @@ -11,6 +11,7 @@ from syncthing_mcp.models import ( SetDefaultIgnoresInput, SetIgnoresInput, WriteParams, + require_write, ) from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -72,13 +73,23 @@ async def syncthing_pending_folders(params: ReadParams) -> str: annotations={ "title": "Accept Pending Device", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": False, "openWorldHint": False, }, ) 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. + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "Accepting a pending device admits it into the Syncthing cluster, " + "allowing it to connect and be offered folder shares. " + "Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) pending = await client._get("/rest/cluster/pending/devices") @@ -112,7 +123,11 @@ async def syncthing_accept_device(params: AcceptDeviceInput) -> str: }, ) async def syncthing_reject_device(params: DeviceWriteParams) -> str: - """Dismiss a pending device connection request.""" + """Dismiss a pending device connection request. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) await client._delete( @@ -133,13 +148,23 @@ async def syncthing_reject_device(params: DeviceWriteParams) -> str: annotations={ "title": "Accept Pending Folder Offer", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": False, "openWorldHint": False, }, ) async def syncthing_accept_folder(params: AcceptFolderInput) -> str: - """Accept a pending folder share offer. Uses default folder config as template.""" + """Accept a pending folder share offer. Uses default folder config as template. + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "Accepting a pending folder adds it to the configuration and " + "starts syncing its contents to local disk from the offering " + "device(s). Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) pending = await client._get("/rest/cluster/pending/folders") @@ -184,7 +209,11 @@ async def syncthing_accept_folder(params: AcceptFolderInput) -> str: }, ) async def syncthing_reject_folder(params: RejectFolderInput) -> str: - """Dismiss a pending folder share offer.""" + """Dismiss a pending folder share offer. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) delete_params: dict[str, str] = {"folder": params.folder_id} @@ -239,13 +268,23 @@ async def syncthing_get_ignores(params: FolderReadParams) -> str: annotations={ "title": "Set Folder Ignore Patterns", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": True, "openWorldHint": False, }, ) async def syncthing_set_ignores(params: SetIgnoresInput) -> str: - """Set .stignore patterns for a folder. Replaces all existing patterns.""" + """Set .stignore patterns for a folder. Replaces all existing patterns. + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "This REPLACES the folder's entire .stignore pattern set — " + "existing patterns are lost and the change alters which files " + "sync. Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) await client._post( @@ -297,7 +336,11 @@ async def syncthing_get_default_ignores(params: ReadParams) -> 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. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) await client._put( diff --git a/src/syncthing_mcp/tools/folders.py b/src/syncthing_mcp/tools/folders.py index 261df93..3a74e7a 100644 --- a/src/syncthing_mcp/tools/folders.py +++ b/src/syncthing_mcp/tools/folders.py @@ -15,6 +15,7 @@ from syncthing_mcp.formatters import ( ) from syncthing_mcp.models import ( BrowseFolderInput, + ConfirmFolderWriteParams, FileInfoInput, FolderNeedInput, FolderReadParams, @@ -22,6 +23,7 @@ from syncthing_mcp.models import ( ReadParams, RemoteNeedInput, _resolve_scope_folders, + require_write, ) from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -316,7 +318,11 @@ async def syncthing_replication_report(params: ReadParams) -> str: ) async def syncthing_pause_folder(params: FolderWriteParams) -> str: """Pause syncing for a folder. Does NOT delete data — only stops sync - so you can safely remove the local copy without propagating deletions.""" + so you can safely remove the local copy without propagating deletions. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}") @@ -344,7 +350,11 @@ async def syncthing_pause_folder(params: FolderWriteParams) -> str: async def syncthing_resume_folder(params: FolderWriteParams) -> str: """Resume syncing for a paused folder. WARNING: if local data was deleted while paused, behaviour depends on folder type (sendreceive may propagate - deletions; receiveonly will re-download).""" + deletions; receiveonly will re-download). + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) folder_cfg = await client._get(f"/rest/config/folders/{params.folder_id}") @@ -372,7 +382,11 @@ async def syncthing_resume_folder(params: FolderWriteParams) -> str: }, ) async def syncthing_scan_folder(params: FolderWriteParams) -> str: - """Trigger an immediate rescan of a folder to refresh its status.""" + """Trigger an immediate rescan of a folder to refresh its status. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) await client._post("/rest/db/scan", params={"folder": params.folder_id}) @@ -689,13 +703,23 @@ async def syncthing_remote_need(params: RemoteNeedInput) -> str: annotations={ "title": "Override Remote Changes (Send-Only)", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": True, "openWorldHint": False, }, ) -async def syncthing_override_folder(params: FolderWriteParams) -> str: - """Override remote changes on a send-only folder (make local authoritative).""" +async def syncthing_override_folder(params: ConfirmFolderWriteParams) -> str: + """Override remote changes on a send-only folder (make local authoritative). + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "Override pushes this device's local state over remote edits on a " + "send-only folder — remote changes are discarded cluster-wide. " + "Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) await client._post("/rest/db/override", params={"folder": params.folder_id}) @@ -713,13 +737,23 @@ async def syncthing_override_folder(params: FolderWriteParams) -> str: annotations={ "title": "Revert Local Changes (Receive-Only)", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": True, "openWorldHint": False, }, ) -async def syncthing_revert_folder(params: FolderWriteParams) -> str: - """Revert local changes on a receive-only folder (pull remote state).""" +async def syncthing_revert_folder(params: ConfirmFolderWriteParams) -> str: + """Revert local changes on a receive-only folder (pull remote state). + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "Revert discards this device's local changes on a receive-only " + "folder and re-downloads the remote state — local edits are lost. " + "Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) await client._post("/rest/db/revert", params={"folder": params.folder_id}) diff --git a/src/syncthing_mcp/tools/system.py b/src/syncthing_mcp/tools/system.py index 2179977..0afbd48 100644 --- a/src/syncthing_mcp/tools/system.py +++ b/src/syncthing_mcp/tools/system.py @@ -6,7 +6,13 @@ from typing import Any import httpx from syncthing_mcp.formatters import append_meta, fmt, format_bytes, meta_envelope, truncate -from syncthing_mcp.models import ReadParams, WriteParams, _resolve_scope_folders +from syncthing_mcp.models import ( + ConfirmWriteParams, + ReadParams, + WriteParams, + _resolve_scope_folders, + require_write, +) from syncthing_mcp.registry import get_instance, handle_error_global from syncthing_mcp.server import mcp @@ -93,7 +99,11 @@ async def syncthing_system_errors(params: ReadParams) -> str: }, ) async def syncthing_clear_errors(params: WriteParams) -> str: - """Clear the system error log.""" + """Clear the system error log. + Requires SYNCTHING_WRITE_ENABLED=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) try: client = get_instance(params.instance) await client._post("/rest/system/error/clear") @@ -232,13 +242,23 @@ async def syncthing_restart_required(params: ReadParams) -> str: annotations={ "title": "Restart Syncthing", "readOnlyHint": False, - "destructiveHint": False, + "destructiveHint": True, "idempotentHint": True, "openWorldHint": False, }, ) -async def syncthing_restart(params: WriteParams) -> str: - """Restart the Syncthing service. Temporarily stops all sync activity.""" +async def syncthing_restart(params: ConfirmWriteParams) -> str: + """Restart the Syncthing service. Temporarily stops all sync activity. + Requires SYNCTHING_WRITE_ENABLED=true and confirm=true.""" + gate = require_write() + if gate: + return fmt({"error": gate}) + if not params.confirm: + return fmt({"error": ( + "Restarting stops the Syncthing daemon and interrupts all active " + "sync transfers on this instance until it comes back up. " + "Set confirm=true to proceed." + )}) try: client = get_instance(params.instance) try: diff --git a/stallari-plugin.yaml b/stallari-plugin.yaml index c3d08bb..1f1f2af 100644 --- a/stallari-plugin.yaml +++ b/stallari-plugin.yaml @@ -76,6 +76,11 @@ setup: required: false placeholder: '{"name": {"url": "...", "apiKey": "..."}}' help: "JSON object for multi-instance mode. Overrides API Key and URL above" + - key: SYNCTHING_WRITE_ENABLED + label: "Enable Write Operations" + required: false + placeholder: "true" + help: "Set to 'true' to allow mutating tools (pause/resume, accept, restart, override, ignores). Off by default; destructive operations also require confirm=true per call" install: runtime: uv @@ -95,6 +100,10 @@ env: secret: true required: false description: "JSON object for multi-instance mode (overrides API_KEY/URL)" + - name: SYNCTHING_WRITE_ENABLED + secret: false + required: false + description: "Set to 'true' to enable mutating tools; destructive/disruptive operations also require confirm=true (default: writes disabled)" conformance: required: "38" diff --git a/tests/conftest.py b/tests/conftest.py index 8651665..a6301c5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -157,6 +157,12 @@ def single_instance_env(monkeypatch): monkeypatch.delenv("SYNCTHING_INSTANCES", raising=False) +@pytest.fixture +def write_enabled_env(monkeypatch): + """Enable the AUD-04-02 write gate for tests exercising mutating tools.""" + monkeypatch.setenv("SYNCTHING_WRITE_ENABLED", "true") + + @pytest.fixture def multi_instance_env(monkeypatch): """Set env vars for multi-instance mode.""" diff --git a/tests/test_tools_config.py b/tests/test_tools_config.py index f416981..30ca553 100644 --- a/tests/test_tools_config.py +++ b/tests/test_tools_config.py @@ -49,7 +49,7 @@ class TestPendingFolders: class TestAcceptDevice: - async def test_accept(self, mock_api): + async def test_accept(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_accept_device mock_api.get("/rest/cluster/pending/devices").respond(json={ @@ -60,14 +60,14 @@ class TestAcceptDevice: }) mock_api.post("/rest/config/devices").respond(status_code=200, content=b"") result = json.loads(await syncthing_accept_device( - AcceptDeviceInput(device_id=DEVICE_ID_REMOTE2) + AcceptDeviceInput(device_id=DEVICE_ID_REMOTE2, confirm=True) )) assert result["status"] == "accepted" assert result["name"] == "new-device" class TestRejectDevice: - async def test_reject(self, mock_api): + async def test_reject(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_reject_device mock_api.delete("/rest/cluster/pending/devices").respond(status_code=200, content=b"") @@ -78,7 +78,7 @@ class TestRejectDevice: class TestAcceptFolder: - async def test_accept(self, mock_api): + async def test_accept(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_accept_folder mock_api.get("/rest/cluster/pending/folders").respond(json={ @@ -94,22 +94,22 @@ class TestAcceptFolder: }) mock_api.post("/rest/config/folders").respond(status_code=200, content=b"") result = json.loads(await syncthing_accept_folder( - AcceptFolderInput(folder_id="new-folder") + AcceptFolderInput(folder_id="new-folder", confirm=True) )) assert result["status"] == "accepted" assert result["label"] == "Shared Docs" - async def test_not_pending(self, mock_api): + async def test_not_pending(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_accept_folder result = json.loads(await syncthing_accept_folder( - AcceptFolderInput(folder_id="nonexistent") + AcceptFolderInput(folder_id="nonexistent", confirm=True) )) assert "error" in result class TestRejectFolder: - async def test_reject(self, mock_api): + async def test_reject(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_reject_folder mock_api.delete("/rest/cluster/pending/folders").respond(status_code=200, content=b"") @@ -132,12 +132,12 @@ class TestGetIgnores: class TestSetIgnores: - async def test_set(self, mock_api): + async def test_set(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_set_ignores mock_api.post("/rest/db/ignores").respond(status_code=200, content=b"") result = json.loads(await syncthing_set_ignores( - SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"]) + SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.log", "node_modules"], confirm=True) )) assert result["status"] == "updated" assert result["count"] == 2 @@ -153,7 +153,7 @@ class TestGetDefaultIgnores: class TestSetDefaultIgnores: - async def test_set(self, mock_api): + async def test_set(self, mock_api, write_enabled_env): from syncthing_mcp.tools.config import syncthing_set_default_ignores mock_api.put("/rest/config/defaults/ignores").respond( diff --git a/tests/test_tools_folders.py b/tests/test_tools_folders.py index d0cb97a..a7c9a5b 100644 --- a/tests/test_tools_folders.py +++ b/tests/test_tools_folders.py @@ -7,6 +7,7 @@ import respx from syncthing_mcp.models import ( BrowseFolderInput, + ConfirmFolderWriteParams, EmptyInput, FileInfoInput, FolderInput, @@ -281,7 +282,7 @@ class TestReplicationReport: class TestPauseFolder: - async def test_pause(self, mock_api): + async def test_pause(self, mock_api, write_enabled_env): from syncthing_mcp.tools.folders import syncthing_pause_folder mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond( @@ -296,7 +297,7 @@ class TestPauseFolder: class TestResumeFolder: - async def test_resume(self, mock_api): + async def test_resume(self, mock_api, write_enabled_env): from syncthing_mcp.tools.folders import syncthing_resume_folder mock_api.get(f"/rest/config/folders/{FOLDER_ID}").respond( @@ -312,7 +313,7 @@ class TestResumeFolder: class TestScanFolder: - async def test_scan(self, mock_api): + async def test_scan(self, mock_api, write_enabled_env): from syncthing_mcp.tools.folders import syncthing_scan_folder mock_api.post("/rest/db/scan").respond(status_code=200, content=b"") @@ -577,18 +578,22 @@ class TestRemoteNeed: class TestOverrideFolder: - async def test_override(self, mock_api): + async def test_override(self, mock_api, write_enabled_env): from syncthing_mcp.tools.folders import syncthing_override_folder mock_api.post("/rest/db/override").respond(status_code=200, content=b"") - result = json.loads(await syncthing_override_folder(FolderInput(folder_id=FOLDER_ID))) + result = json.loads(await syncthing_override_folder( + ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True) + )) assert result["status"] == "override_requested" class TestRevertFolder: - async def test_revert(self, mock_api): + async def test_revert(self, mock_api, write_enabled_env): from syncthing_mcp.tools.folders import syncthing_revert_folder mock_api.post("/rest/db/revert").respond(status_code=200, content=b"") - result = json.loads(await syncthing_revert_folder(FolderInput(folder_id=FOLDER_ID))) + result = json.loads(await syncthing_revert_folder( + ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True) + )) assert result["status"] == "revert_requested" diff --git a/tests/test_tools_system.py b/tests/test_tools_system.py index f6069e3..9ed67da 100644 --- a/tests/test_tools_system.py +++ b/tests/test_tools_system.py @@ -6,7 +6,7 @@ import pytest import respx from httpx import Response -from syncthing_mcp.models import EmptyInput +from syncthing_mcp.models import ConfirmWriteParams, EmptyInput from syncthing_mcp.registry import reload_instances from tests.conftest import ( BASE_URL, @@ -59,7 +59,7 @@ class TestSystemErrors: class TestClearErrors: - async def test_clear(self, mock_api): + async def test_clear(self, mock_api, write_enabled_env): from syncthing_mcp.tools.system import syncthing_clear_errors mock_api.post("/rest/system/error/clear").respond(status_code=200, content=b"") @@ -100,11 +100,11 @@ class TestRestartRequired: class TestRestart: - async def test_restart(self, mock_api): + async def test_restart(self, mock_api, write_enabled_env): from syncthing_mcp.tools.system import syncthing_restart mock_api.post("/rest/system/restart").respond(status_code=200, content=b"") - result = json.loads(await syncthing_restart(EmptyInput())) + result = json.loads(await syncthing_restart(ConfirmWriteParams(confirm=True))) assert result["status"] == "restart_initiated" diff --git a/tests/test_write_gate.py b/tests/test_write_gate.py new file mode 100644 index 0000000..b7d8b8d --- /dev/null +++ b/tests/test_write_gate.py @@ -0,0 +1,133 @@ +"""Regression tests for the write gate + confirm discipline (AUD-04-02 / DD-385 Phase W). + +Every mutating tool must refuse when ``SYNCTHING_WRITE_ENABLED`` is not +``true``; destructive/disruptive tools must additionally refuse without +``confirm=true`` even when the gate is open. +""" + +import json + +import pytest + +from syncthing_mcp.models import ( + AcceptDeviceInput, + AcceptFolderInput, + ConfirmFolderWriteParams, + ConfirmWriteParams, + DeviceInput, + PauseFolderInput, + RejectFolderInput, + SetDefaultIgnoresInput, + SetIgnoresInput, + WriteParams, +) +from syncthing_mcp.registry import reload_instances +from syncthing_mcp.tools.config import ( + syncthing_accept_device, + syncthing_accept_folder, + syncthing_reject_device, + syncthing_reject_folder, + syncthing_set_default_ignores, + syncthing_set_ignores, +) +from syncthing_mcp.tools.folders import ( + syncthing_override_folder, + syncthing_pause_folder, + syncthing_resume_folder, + syncthing_revert_folder, + syncthing_scan_folder, +) +from syncthing_mcp.tools.system import syncthing_clear_errors, syncthing_restart +from tests.conftest import DEVICE_ID_REMOTE2, FOLDER_ID + +WRITE_DISABLED_MSG = ( + "Write operations are disabled. Set SYNCTHING_WRITE_ENABLED=true to enable." +) + + +@pytest.fixture(autouse=True) +def _setup(single_instance_env, monkeypatch): + monkeypatch.delenv("SYNCTHING_WRITE_ENABLED", raising=False) + reload_instances() + yield + reload_instances() + + +# Every mutating tool, with valid params. confirm=True so the gated-off test +# proves the env gate refuses even a fully-confirmed call. +ALL_MUTATING = [ + pytest.param(syncthing_pause_folder, PauseFolderInput(folder_id=FOLDER_ID), id="pause_folder"), + pytest.param(syncthing_resume_folder, PauseFolderInput(folder_id=FOLDER_ID), id="resume_folder"), + pytest.param(syncthing_scan_folder, PauseFolderInput(folder_id=FOLDER_ID), id="scan_folder"), + pytest.param(syncthing_override_folder, ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True), id="override_folder"), + pytest.param(syncthing_revert_folder, ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True), id="revert_folder"), + pytest.param(syncthing_clear_errors, WriteParams(), id="clear_errors"), + pytest.param(syncthing_restart, ConfirmWriteParams(confirm=True), id="restart"), + pytest.param(syncthing_accept_device, AcceptDeviceInput(device_id=DEVICE_ID_REMOTE2, confirm=True), id="accept_device"), + pytest.param(syncthing_reject_device, DeviceInput(device_id=DEVICE_ID_REMOTE2), id="reject_device"), + pytest.param(syncthing_accept_folder, AcceptFolderInput(folder_id=FOLDER_ID, confirm=True), id="accept_folder"), + pytest.param(syncthing_reject_folder, RejectFolderInput(folder_id=FOLDER_ID), id="reject_folder"), + pytest.param(syncthing_set_ignores, SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.tmp"], confirm=True), id="set_ignores"), + pytest.param(syncthing_set_default_ignores, SetDefaultIgnoresInput(lines=[".DS_Store"]), id="set_default_ignores"), +] + +# Destructive/disruptive tools requiring confirm=true, with confirm left False. +DESTRUCTIVE_NO_CONFIRM = [ + pytest.param(syncthing_override_folder, ConfirmFolderWriteParams(folder_id=FOLDER_ID), id="override_folder"), + pytest.param(syncthing_revert_folder, ConfirmFolderWriteParams(folder_id=FOLDER_ID), id="revert_folder"), + pytest.param(syncthing_restart, ConfirmWriteParams(), id="restart"), + pytest.param(syncthing_accept_device, AcceptDeviceInput(device_id=DEVICE_ID_REMOTE2), id="accept_device"), + pytest.param(syncthing_accept_folder, AcceptFolderInput(folder_id=FOLDER_ID), id="accept_folder"), + pytest.param(syncthing_set_ignores, SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.tmp"]), id="set_ignores"), +] + + +class TestWriteGateOff: + @pytest.mark.parametrize("tool, params", ALL_MUTATING) + async def test_refuses_when_gate_unset(self, mock_api, tool, params): + result = json.loads(await tool(params)) + assert result == {"error": WRITE_DISABLED_MSG} + + @pytest.mark.parametrize("tool, params", ALL_MUTATING) + async def test_refuses_when_gate_not_true(self, mock_api, monkeypatch, tool, params): + monkeypatch.setenv("SYNCTHING_WRITE_ENABLED", "1") + result = json.loads(await tool(params)) + assert result == {"error": WRITE_DISABLED_MSG} + + +class TestConfirmRequired: + @pytest.mark.parametrize("tool, params", DESTRUCTIVE_NO_CONFIRM) + async def test_refuses_without_confirm(self, mock_api, write_enabled_env, tool, params): + result = json.loads(await tool(params)) + assert "error" in result + assert "confirm=true" in result["error"] + # Refusal must not be the gate message — the gate is open. + assert result["error"] != WRITE_DISABLED_MSG + + +class TestGatedOnProceeds: + async def test_restart_with_confirm(self, mock_api, write_enabled_env): + mock_api.post("/rest/system/restart").respond(status_code=200, content=b"") + result = json.loads(await syncthing_restart(ConfirmWriteParams(confirm=True))) + assert result["status"] == "restart_initiated" + + async def test_override_with_confirm(self, mock_api, write_enabled_env): + mock_api.post("/rest/db/override").respond(status_code=200, content=b"") + result = json.loads(await syncthing_override_folder( + ConfirmFolderWriteParams(folder_id=FOLDER_ID, confirm=True) + )) + assert result["status"] == "override_requested" + + async def test_set_ignores_with_confirm(self, mock_api, write_enabled_env): + mock_api.post("/rest/db/ignores").respond(status_code=200, content=b"") + result = json.loads(await syncthing_set_ignores( + SetIgnoresInput(folder_id=FOLDER_ID, patterns=["*.tmp"], confirm=True) + )) + assert result["status"] == "updated" + + async def test_non_destructive_needs_no_confirm(self, mock_api, write_enabled_env): + mock_api.post("/rest/db/scan").respond(status_code=200, content=b"") + result = json.loads(await syncthing_scan_folder( + PauseFolderInput(folder_id=FOLDER_ID) + )) + assert result["status"] == "scan_requested" diff --git a/uv.lock b/uv.lock index b33eee5..05371fe 100644 --- a/uv.lock +++ b/uv.lock @@ -837,7 +837,7 @@ wheels = [ [[package]] name = "syncthing-blade-mcp" -version = "0.8.0" +version = "0.9.0" source = { editable = "." } dependencies = [ { name = "httpx" },