Skip to main content
Glama
README.md
# ๐Ÿ’พ Synology MCP Server

![Synology MCP Server](assets/banner.png)

A Model Context Protocol (MCP) server for Synology NAS devices. Enables AI assistants to manage files and downloads through secure authentication and session management.

**๐ŸŒŸ NEW: Unified server supports both Claude/Cursor (stdio) and Xiaozhi (WebSocket) simultaneously!**

## ๐Ÿ“ฆ Install from PyPI

No need to clone the repository โ€” install the package directly from PyPI:

```bash
# With pip
pip install mcp-server-synology

# Or with pipx (isolated environment)
pipx install mcp-server-synology

# Or with uv
uv tool install mcp-server-synology
```

This installs two equivalent commands: `synology-mcp` and `mcp-server-synology`.

For MCP clients, `uvx` is the simplest option โ€” it downloads and caches the package automatically, no manual install or local clone required:

```json
{
  "mcpServers": {
    "synology": {
      "command": "uvx",
      "args": ["mcp-server-synology"]
    }
  }
}
```

Configuration lives outside the package, so it works the same as a source checkout: create `~/.config/synology-mcp/settings.json` as described in [Configuration Options](#๏ธ-configuration-options).

## ๐Ÿš€ Quick Start with Docker

### 1๏ธโƒฃ Setup Environment
```bash
# Clone repository
git clone https://github.com/atom2ueki/mcp-server-synology.git
cd mcp-server-synology

# Create environment file
cp env.example .env
```

### 2๏ธโƒฃ Configure .env File

**Basic Configuration (Claude/Cursor only):**
```bash
# Required: Synology NAS connection
SYNOLOGY_URL=http://192.168.1.100:5000
SYNOLOGY_USERNAME=your_username
SYNOLOGY_PASSWORD=your_password

# Optional: Auto-login on startup
AUTO_LOGIN=true
VERIFY_SSL=false
```

**Extended Configuration (Both Claude/Cursor + Xiaozhi):**
```bash
# Required: Synology NAS connection
SYNOLOGY_URL=http://192.168.1.100:5000
SYNOLOGY_USERNAME=your_username
SYNOLOGY_PASSWORD=your_password

# Optional: Auto-login on startup
AUTO_LOGIN=true
VERIFY_SSL=false

# Enable Xiaozhi support
ENABLE_XIAOZHI=true
XIAOZHI_TOKEN=your_xiaozhi_token_here
XIAOZHI_MCP_ENDPOINT=wss://api.xiaozhi.me/mcp/
```

`.env` is read at **run time**, never baked into the image โ€” `docker-compose.yml`
injects its entries as container environment variables via `env_file`, so the
file itself is not present inside the container. It is optional: if you
configure NASes with `settings.json` instead (recommended), you can skip this
file entirely.

### 3๏ธโƒฃ Run with Docker

**One simple command supports both modes:**

```bash
# Claude/Cursor only mode (default if ENABLE_XIAOZHI not set)
docker-compose up -d

# Both Claude/Cursor + Xiaozhi mode (if ENABLE_XIAOZHI=true in .env)
docker-compose up -d

# Build and run
docker-compose up -d --build
```

Instead of building locally, you can pull the published image and use it in `docker-compose.yml` exactly as described for the HTTP compose file in [Pre-built image](#pre-built-image) below โ€” replace `build: .` with `image: ghcr.io/atom2ueki/mcp-server-synology:latest` (or a pinned `X.Y.Z`).

### 4๏ธโƒฃ Alternative: Local Python

```bash
# Install the package and its dependencies (from PyPI, or from a clone with 'pip install .')
pip install mcp-server-synology

# Run with environment control
python main.py
```

## ๐Ÿ”Œ Client Setup

The examples below use Docker with a local clone of this repository. If you installed from PyPI, use the `uvx` configuration from [Install from PyPI](#-install-from-pypi) instead โ€” it works for Claude Desktop, Cursor, Continue and Codeium alike, with no local paths to adjust.

### ๐Ÿค– Claude Desktop

Add to your Claude Desktop configuration file:

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "synology": {
      "command": "docker-compose",
      "args": [
        "-f", "/path/to/your/mcp-server-synology/docker-compose.yml",
        "run", "--rm", "synology-mcp"
      ],
      "cwd": "/path/to/your/mcp-server-synology"
    }
  }
}
```

### โ†—๏ธ Cursor

Add to your Cursor MCP settings:

```json
{
  "mcpServers": {
    "synology": {
      "command": "docker-compose",
      "args": [
        "-f", "/path/to/your/mcp-server-synology/docker-compose.yml",
        "run", "--rm", "synology-mcp"
      ],
      "cwd": "/path/to/your/mcp-server-synology"
    }
  }
}
```

### ๐Ÿ”„ Continue (VS Code Extension)

Add to your Continue configuration (`.continue/config.json`):

```json
{
  "mcpServers": {
    "synology": {
      "command": "docker-compose",
      "args": [
        "-f", "/path/to/your/mcp-server-synology/docker-compose.yml",
        "run", "--rm", "synology-mcp"
      ],
      "cwd": "/path/to/your/mcp-server-synology"
    }
  }
}
```

### ๐Ÿ’ป Codeium

For Codeium's MCP support:

```json
{
  "mcpServers": {
    "synology": {
      "command": "docker-compose",
      "args": [
        "-f", "/path/to/your/mcp-server-synology/docker-compose.yml",
        "run", "--rm", "synology-mcp"
      ],
      "cwd": "/path/to/your/mcp-server-synology"
    }
  }
}
```

### ๐Ÿ Alternative: Direct Python Execution

If you prefer not to use Docker:

```json
{
  "mcpServers": {
    "synology": {
      "command": "python",
      "args": ["main.py"],
      "cwd": "/path/to/your/mcp-server-synology",
      "env": {
        "SYNOLOGY_URL": "http://192.168.1.100:5000",
        "SYNOLOGY_USERNAME": "your_username",
        "SYNOLOGY_PASSWORD": "your_password",
        "AUTO_LOGIN": "true",
        "ENABLE_XIAOZHI": "false"
      }
    }
  }
}
```
## ๐ŸŒ Remote Streamable HTTP Deployment

By default the server speaks **stdio**, which means the MCP client has to spawn the process locally (or via a bridge such as SSH/docker exec). For setups where the NAS is remote (different machine from where Claude/Cursor runs), set `MCP_HTTP=true` and the server serves **native Streamable HTTP** from uvicorn in the same process โ€” no `mcp-proxy` sidecar and no separate `/sse` endpoint. This makes it consumable by any MCP client that supports URL-based connectors โ€” exactly like `ha-mcp` or other "remote" MCP servers.

### Architecture

```
[Claude Desktop / Cursor / ...]
        โ”‚
        โ”‚ HTTPS (URL connector)
        โ–ผ
[Reverse proxy: DSM / Nginx / Traefik / Caddy]
        โ”‚  (TLS termination + auth)
        โ”‚ HTTP localhost:8765
        โ–ผ
[Docker container]
  โ””โ”€ python main.py
       โ””โ”€ uvicorn โ†’ Streamable HTTP at /mcp
```

### Deploy

1. All dependencies come from `pyproject.toml`: `mcp>=2.0.0` ships starlette,
   uvicorn, and sse-starlette, so the same image serves both stdio and
   Streamable HTTP โ€” no extra build arg or separate requirements file.
2. Use the provided `docker-compose.http.yml`:

```bash
# Edit credentials in docker-compose.http.yml first
docker compose -f docker-compose.http.yml up -d --build
docker logs -f synology-mcp-http
```

You should see the server log `Starting Streamable HTTP MCP server on http://0.0.0.0:8765/mcp` and the auto-login succeed. uvicorn's own `Uvicorn running on โ€ฆ` banner is *not* printed at the compose file's defaults โ€” it is INFO on the `uvicorn.error` logger, which the server pins to `warning` unless `DEBUG=true`.

#### Pre-built image

Instead of building locally, you can pull the image published to GitHub Container Registry on every release (`linux/amd64` and `linux/arm64`, so it also runs on ARM-based NAS models):

```bash
docker pull ghcr.io/atom2ueki/mcp-server-synology:latest   # or pin a release tag, e.g. :X.Y.Z
```

Tags: `X.Y.Z` and `X.Y` per stable release, `latest` for the newest stable release (pre-releases only get their own version tag, never `latest`), and `edge` for manual builds from a branch. `1.9.0` is the first release with an image; earlier tags (up to `1.8.0`) have none, so build locally (above) or use `edge` for a manual build. To use it with `docker-compose.http.yml`, replace `build: .` with `image: ghcr.io/atom2ueki/mcp-server-synology:latest` (or a pinned `X.Y.Z`). Like the locally built image, it contains no credentials; pass them at run time as described above.

GHCR creates the package as **private** on first publish; the maintainer makes it public once (Packages โ†’ mcp-server-synology โ†’ Package settings โ†’ Change visibility). Until then, `docker pull` fails anonymously โ€” you can still pull after `docker login ghcr.io` with a GitHub token that has `read:packages`.

### Reverse proxy

Most MCP clients require HTTPS, so the HTTP endpoint must be fronted by a TLS-terminating reverse proxy. For DSM users, the built-in **Login Portal โ†’ Reverse Proxy** does the job:

- **Source**: `HTTPS`, hostname `synology-mcp.example.com`, port `443`
- **Destination**: `HTTP`, `localhost`, port `8765`
- **Custom Headers**: none required โ€” Streamable HTTP is plain POST/GET on a single endpoint, not a WebSocket upgrade. The *Create โ†’ WebSocket* preset is harmless if you already apply it elsewhere (it sets `Connection: upgrade` only for real upgrade requests), but it is not what keeps a stream open

For Nginx, the equivalent is:

```nginx
location / {
    proxy_pass http://localhost:8765;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    # Responses may stream as long-lived text/event-stream
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 24h;
}
```

### Client configuration

In Claude Desktop (or any MCP client that supports remote connectors), add a custom connector pointing at:

```
https://synology-mcp.example.com/mcp
```

The path is whatever `MCP_HTTP_PATH` is set to (default `/mcp`). No `command`, no `args`, no local Python โ€” just a URL.

### Security

The server does **not** implement any application-level authentication โ€” anything that can reach the HTTP endpoint can call every tool. It does enable the MCP SDK's DNS-rebinding protection, which rejects requests whose `Host`/`Origin` headers are not on an allowlist (`MCP_HTTP_ALLOWED_HOSTS` / `MCP_HTTP_ALLOWED_ORIGINS`, defaulting to loopback). Behind a reverse proxy set both, minding the differing formats โ€” hosts are bare (`synology-mcp.example.com`), origins are scheme-qualified (`https://synology-mcp.example.com`), as in the commented examples in `docker-compose.http.yml`. That guards browsers against rebinding attacks; it is **not** authentication. Mitigations:

- Keep it on a private network or behind a VPN
- Leave the published port on loopback (`docker-compose.http.yml` binds `127.0.0.1:8765`) so only a same-host reverse proxy can reach it
- Use the reverse proxy to enforce an IP allow-list
- Add Basic Auth / mTLS / OAuth2 proxy at the reverse proxy layer
- Use a dedicated low-privilege DSM user (already recommended in the security warning above)

## ๐ŸŒŸ Xiaozhi Integration

**New unified architecture supports both clients simultaneously!**

### How It Works

- **ENABLE_XIAOZHI=false** (default): Standard MCP server for Claude/Cursor via stdio
- **ENABLE_XIAOZHI=true**: Multi-client bridge supporting both:
  - ๐Ÿ“ก **Xiaozhi**: WebSocket connection
  - ๐Ÿ’ป **Claude/Cursor**: stdio connection

### Setup Steps

1. **Add to your .env file:**
```bash
ENABLE_XIAOZHI=true
XIAOZHI_TOKEN=your_xiaozhi_token_here
```

2. **Run normally:**
```bash
# Same command, different behavior based on environment
python main.py
# OR
docker-compose up
```

### Key Features
- โœ… **Zero Configuration Conflicts**: One server, multiple clients
- โœ… **Parallel Operation**: Both clients can work simultaneously  
- โœ… **All Tools Available**: Xiaozhi gets access to all Synology MCP tools
- โœ… **Backward Compatible**: Existing setups work unchanged
- โœ… **Auto-Reconnection**: Handles WebSocket connection drops
- โœ… **Environment Controlled**: Simple boolean flag to enable/disable

### Startup Messages

**Claude/Cursor only mode:**
```
๐Ÿš€ Synology MCP Server
==============================
๐Ÿ“Œ Claude/Cursor only mode (ENABLE_XIAOZHI=false)
```

**Both clients mode:**
```
๐Ÿš€ Synology MCP Server with Xiaozhi Bridge
==================================================
๐ŸŒŸ Supports BOTH Xiaozhi and Claude/Cursor simultaneously!
```

## ๐Ÿงพ Audit Trail and Tool Annotations

Every tool call appends a JSON result record to `logs/audit.jsonl` โ€” the tool, its risk class, the path it acted on, redacted arguments, the outcome and the duration. It is deliberately independent of DSM: reading Log Center needs an admin account, and the MCP account is not one (`SYNO.Core.SyslogClient.Log` returns error 105).

```json
{"ts":"2026-10-23T01:25:36.412+00:00","event":"tool_call","run":"9f3c1a2b8d4e","pid":7,
 "tool":"delete","risk":"destructive","target":"/media/library/Movies/Old/Movie.mkv",
 "args":{"path":"/media/library/Movies/Old/Movie.mkv"},"outcome":"ok","duration_ms":41}
```

- **Fail closed for destructive calls.** Before a tool classified `destructive` runs, the server persists and flushes a `tool_intent` record. If it cannot, the call is refused with `audit_unavailable` โ€” an unrecorded destructive action is not allowed to happen. Set `MCP_AUDIT=false` only if you deliberately want no trail (and no such protection).
- **Best effort after the fact.** If the append fails after an action already ran, the loss is reported on stderr and the tool result is unchanged.
- **Secrets are masked by key name** (`password`, `passwd`, `token`, `api_key`, `session`, `sid`, `chap_password`, โ€ฆ); long values such as file bodies are truncated to 512 characters.
- **Rotation** is size-based: `audit.jsonl` โ†’ `.1` โ€ฆ `.5` by default.

Tools also carry **MCP annotations** (`readOnlyHint`, `destructiveHint`), declared on each tool's `ToolSpec` in `src/tools/` next to its description, JSON schema and handler. A spec cannot be constructed without a classification, so no tool can ship unannotated. They let a client with approval UI prompt on the calls that matter, but they are **hints**: a client may ignore them. The server separately derives its own tier from the same declared annotations with `tool_policy.risk_for` โ€” including the `overwrite`/`password` escalations โ€” and enforces the confirmation gate and audit preflight with that tier.

### Destructive calls need confirmation

A destructive call, including `create_file`, `copy_file`, or `move_file` with `overwrite: true`, first returns an MCP `2026-07-28` `InputRequiredResult` with a confirmation form and HMAC-signed `requestState`. The client collects consent and retries the exact call. State has a fresh nonce, expires, is consumed atomically once, and is invalidated by a server restart.

Clients without this protocol and form capability receive `confirmation_required`; there is no model-callable token issuer or legacy approval fallback. `MCP_CONFIRM=off` explicitly disables the gate. Audit records carry `confirmation: round-trip | none`. The client's UI is responsible for human consent: a server cannot distinguish an actual human response from a client that automatically accepts forms.

```json
{"event":"tool_call","tool":"delete","risk":"destructive",
 "target":"/media/library/a.mkv","outcome":"ok","confirmation":"round-trip"}
```

### Confining File Station writes

`MCP_FILESTATION_WRITE_PATHS` confines writes to chosen subtrees, and a NAS entry overrides it per device:

```bash
MCP_FILESTATION_WRITE_PATHS=/volume1/media,/volume1/backups
```

```json
{
  "synology": {
    "nas1": {
      "host": "192.168.1.10",
      "filestation_write_paths": ["/volume1/docker/app/config"]
    }
  }
}
```

It applies to `create_directory`, `create_file`, `copy_file`, `move_file`, `rename_file` and `delete`; with file copies only the destination is checked, while a move checks both ends because removing the source is a write too. A structurally valid path outside the list fails with `path_outside_roots` before any NAS call. Roots are canonicalized at startup and a malformed entry aborts startup rather than silently widening access; leaving the setting empty keeps today's behaviour. Independently of the list, a write whose target is a share, volume or filesystem root is always refused.

### Least privilege: tool profiles

`MCP_TOOL_PROFILE` decides which tools exist at all: `full` (default), `no_destructive` (read-only + additive only) or `read_only`. Filtering happens at registration, so a withheld tool is not listed and cannot be called โ€” stronger than a client-side deny list, and useful when an agent should monitor a NAS without changing it. The startup log names the profile and the number of withheld tools. Session tools (`synology_login`/`synology_logout`) stay available in every profile: they change no NAS data and are the only way to read anything when auto-login is off.

Container details are sanitized regardless of profile: `synology_container_get` keeps environment variable **names** (`env_keys`) and drops their values, because DSM returns database passwords and tokens in `Config.Env` and `profile.env_variables`.

### Deletes go to a trash folder when the share can host one

`delete` moves the target into `<share>/#trash/<date>/` first โ€” a same-share move, so no extra space โ€” and only unlinks when the share cannot host a trash folder. Nothing is assumed about the layout: `MCP_TRASH=auto` probes, falls back to a normal delete if the folder cannot be created, and records the placement (`event: "delete_placement"`, `outcome: soft|hard`) in the audit trail. `always` refuses instead of falling back; `never` deletes directly. The result reports `soft_delete`, `trash_path`, `trash_root`, and `original_path`. Use the recorded paths to restore; the trash layout does not mirror the source tree.

If the MCP account cannot write the share root, point the trash inside the library with an absolute template: `MCP_TRASH_DIR=/media/library/.trash/{share}`.

This is **not** DSM's Recycle Bin and does not require it to be enabled. Share roots and ambiguous traversal paths are always refused. Once a move has been attempted, any failure stops deletion; it never triggers a hard-delete retry. Name collisions use a unique subdirectory, preserving previous trash entries. Trash must stay in the source share. There is no automatic purge or retention schedule; remove retained items only through an explicitly approved operation.

| Env var | Default | Meaning |
|---|---|---|
| `MCP_AUDIT` | `true` | `false` disables the trail and the destructive pre-flight |
| `MCP_AUDIT_LOG` | `logs/audit.jsonl` | Trail path (`./logs` is mounted in Docker) |
| `MCP_AUDIT_MAX_BYTES` | `10485760` | Rotate at this size (`0` disables rotation) |
| `MCP_AUDIT_KEEP` | `5` | Rotated files to keep |
| `MCP_CONFIRM` | `mrtr` | `mrtr` or `off` |
| `MCP_CONFIRM_TTL_SECONDS` | `300` | Confirmation state lifetime |
| `MCP_CONFIRM_SECRET` | โ€” | HMAC key; otherwise generated once at `logs/.confirm-secret` |
| `MCP_TRASH` | `auto` | `auto`, `always`, or `never` |
| `MCP_TRASH_DIR` | `#trash` | Folder under the share, or an absolute `{share}` template |

The same settings can live in `settings.json` under `server.audit` (`enabled`, `path`, `max_bytes`, `keep`), `server.confirm` (`mode`, `ttl_seconds`) and `server.trash` (`mode`, `dir`).

## ๐Ÿ› ๏ธ Available MCP Tools

### ๐Ÿ” Authentication
- **`synology_status`** - Check authentication status and active sessions
- **`synology_list_nas`** - List all configured NAS units from settings.json
- **`synology_login`** - Authenticate with Synology NAS *(conditional)*
- **`synology_logout`** - Logout from session *(conditional)*

### ๐Ÿ“ File System Operations
- **`list_shares`** - List all available NAS shares
- **`list_directory`** - List directory contents with metadata
  - `path` (required): Directory path starting with `/`
- **`get_file_info`** - Get detailed file/directory information
  - `path` (required): File path starting with `/`
- **`get_file_content`** - Read strict UTF-8 text or lossless base64 content
  - `path` (required): File path starting with `/`
  - `encoding` (optional): `text` (default) or `base64`
  - `max_bytes` (optional): Maximum raw bytes to read (default 1 MiB, hard limit 8 MiB)
- **`search_files`** - Recursively search for files and folders by name
  - `path` (required): Search directory
  - `pattern` (required): Case-insensitive substring of the name (e.g., `invoice`, `.pdf`). Wildcards are not special โ€” DSM matches `report` and `*report*` identically.
- **`create_file`** - Create new files with content
  - `path` (required): Full file path starting with `/`
  - `content` (optional): File content (default: empty string)
  - `overwrite` (optional): Overwrite existing files (default: false)
  - `encoding` (optional): `text` (default) or strict `base64`; decoded content is limited to 8 MiB
- **`create_directory`** - Create new directories
  - `folder_path` (required): Parent directory path starting with `/`
  - `name` (required): New directory name
  - `force_parent` (optional): Create parent directories if needed (default: false)
- **`delete`** - Delete files or directories (auto-detects type)
  - `path` (required): File/directory path starting with `/`
- **`rename_file`** - Rename files or directories
  - `path` (required): Current file path
  - `new_name` (required): New filename
- **`move_file`** - Move files to new location
  - `source_path` (required): Source file path
  - `destination_path` (required): Destination path
  - `overwrite` (optional): Overwrite existing files
- **`copy_file`** - Copy a regular file inside the NAS without sending its bytes through the MCP client
  - `source_path` (required): Source file path
  - `destination_folder` (required): Existing destination directory; the filename is preserved
  - `overwrite` (optional): Overwrite an existing same-named file (default: false)

`copy_file` verifies the destination path and byte count. It is not a consistent
backup method for a live SQLite database; use SQLite's online backup mechanism
for databases that may be changing during the copy.

### ๐Ÿ“ฅ Download Station Management
- **`ds_get_info`** - Get Download Station information
- **`ds_list_tasks`** - List all download tasks with status
  - `offset` (optional): Pagination offset
  - `limit` (optional): Max tasks to return
- **`ds_create_task`** - Create new download task
  - `uri` (required): Download URL or magnet link
  - `destination` (optional): Download folder path
- **`ds_pause_tasks`** - Pause download tasks
  - `task_ids` (required): Array of task IDs
- **`ds_resume_tasks`** - Resume paused tasks
  - `task_ids` (required): Array of task IDs  
- **`ds_delete_tasks`** - Delete download tasks
  - `task_ids` (required): Array of task IDs
  - `force_complete` (optional): Force delete completed
- **`ds_get_statistics`** - Get download/upload statistics

### ๐Ÿฅ Health Monitoring
- **`synology_system_info`** - Get system model, serial, DSM version, uptime, temperature
- **`synology_utilization`** - Get real-time CPU, memory, swap, and disk I/O utilization
- **`synology_disk_health`** - List all physical disks with SMART status, model, temp, size
- **`synology_disk_smart`** - Get detailed SMART attributes for a specific disk
- **`synology_volume_status`** - List all volumes with status, size, usage, filesystem type
- **`synology_storage_pool`** - List RAID/storage pools with level, status, member disks
- **`synology_lun_list`** - List all iSCSI LUNs with name, UUID, size, type, status and backing volume. To see which target a LUN is attached to, use `synology_target_list` - DSM does not report mappings on the LUN side.
- **`synology_lun_get`** - Get details for a single iSCSI LUN
  - `name` (required): LUN name or UUID from `synology_lun_list` output
- **`synology_network`** - Get network interface status and transfer rates

### ๐Ÿ”„ DSM Updates & Security Posture
- **`synology_update_status`** - Read-only: installed DSM version, available update (version, security release, whether it reboots), download/install state, packages with pending updates, auto-update policy
- **`synology_security_posture`** - Read-only: QuickConnect, auto-block and its allow list, Telnet/SSH, HTTPS redirect, firewall, 2FA enforcement, admin/guest account state, administrators, Security Advisor findings
- **`synology_terminal_set`** - Turn Telnet/SSH on or off *(confirm=true)*
- **`synology_autoblock_set`** - Configure auto-block; enabling with an empty allow list is refused *(confirm=true)*
- **`synology_autoblock_allow_add` / `_remove`** - Manage the never-block allow list *(confirm=true)*
- **`synology_https_redirect_set`** - Toggle DSM's HTTPโ†’HTTPS redirect; restarts the web server *(confirm=true)*
- **`synology_dsm_update_download`** - Download the available DSM update; installs nothing *(confirm=true)*
- **`synology_dsm_update_install`** - Dry-run DSM's pre-install checks, or install with blockers/warnings/EULA each explicitly accepted; the NAS may reboot *(confirm=true to install)*

### SAN Manager (iSCSI provisioning)

Wraps `SYNO.Core.ISCSI.LUN` and `SYNO.Core.ISCSI.Target`. Verified against DSM
7.3.2-86009 Update 4 on an RS1221+; other DSM builds may differ, and DSM's own
refusal is reported as given rather than second-guessed.

- **`synology_lun_create`** - Create a LUN on a volume; returns its `uuid` and `lun_id`
  - `name`, `location` (e.g. `/volume2`), `size` (**in bytes**) required
  - `type` (optional): `thin` (default, DSM `BLUN`), `advanced`, `file`, or a raw
    DSM type name. Note `thin` and `THIN` are **different**: lowercase is the
    friendly alias for `BLUN`, uppercase is DSM's distinct legacy type. Thick
    types were refused on the btrfs volume this was tested against.
  - `description` (optional)
- **`synology_lun_delete`** - **DESTRUCTIVE.** Delete a LUN and everything on it
  - `uuid` and `confirm: true` required
- **`synology_target_list`** - List targets with IQN, auth type, and the LUNs mapped to each
- **`synology_target_get`** - Get one target by `target_id`
- **`synology_target_create`** - Create a target; returns its `target_id`
  - `name` required; `iqn` defaults to `iqn.2000-01.com.synology:<name>`
  - `chap_user` + `chap_password` enable CHAP. **Supply both or neither** -
    one alone, or an empty string, is refused rather than quietly producing a
    target with no authentication. **With neither, the target accepts any
    initiator that can reach it.**
  - `max_sessions` (optional, 0 = DSM default)
- **`synology_target_map_lun`** - Map LUNs to a target (`target_id`, `lun_uuids`)
- **`synology_target_unmap_lun`** - **DESTRUCTIVE.** Unmap LUNs, disconnecting any
  initiator using them (`target_id`, `lun_uuids`, `confirm: true`)

These tools reject any argument they do not declare, rather than ignoring it: a
misspelled `chap_user` would otherwise create an unauthenticated target, and a
misspelled `type` would silently take the default.

- **`synology_ups`** - Get UPS status, battery level, power readings
- **`synology_services`** - List installed packages and their running status
- **`synology_system_log`** - Get recent system log entries
- **`synology_health_summary`** - Aggregate system info, utilization, disk health, and volume status

### ๐Ÿณ Container Manager
- **`synology_container_list`** - List Container Manager containers
  - `offset` (optional): Pagination offset
  - `limit` (optional): Maximum containers to return
  - `container_type` (optional): Container filter (default: `all`)
- **`synology_container_health_summary`** - Summarize container status, health, restart counts, and images
- **`synology_container_disk_usage`** - Show the read-only disk-usage summary available through Container Manager APIs
- **`synology_container_get`** - Get a Container Manager container
  - `name` (required): Container name
- **`synology_container_start`** - Start a Container Manager container
  - `name` (required): Container name
- **`synology_container_stop`** - Stop a Container Manager container
  - `name` (required): Container name
- **`synology_container_restart`** - Restart a Container Manager container
  - `name` (required): Container name
- **`synology_container_delete`** - Delete a Container Manager container
  - `name` (required): Container name
  - `force` (optional): Force deletion (default: false)
  - `preserve_profile` (optional): Preserve Synology container profile (default: true)
- **`synology_container_logs`** - Get Container Manager container logs
  - `name` (required): Container name
  - `since` (optional): Log start time/filter
  - `offset` (optional): Pagination offset (default: 0)
  - `limit` (optional): Maximum log lines to return (default: 1000)
- **`synology_container_resource`** - Get real-time resource usage for a Container Manager container
  - `name` (required): Container name
- **`synology_container_project_list`** - List Container Manager projects
- **`synology_container_project_get`** - Get a Container Manager project (Compose, environment, and secret fields are omitted)
  - `name` (required): Project name
- **`synology_container_project_create`** - Create and save a Container Manager project definition
  - `name` (required): Project name
  - `share_path` (required): Project folder path on the NAS
  - `content` (required): Docker Compose YAML content
  - `enable_service_portal` (optional): Enable Synology service portal (default: false)
  - `service_portal_name` (optional): Service portal name
  - `service_portal_port` (optional): Service portal port
  - `service_portal_protocol` (optional): Service portal protocol (default: `http`)
  - Saves the Compose definition; call `synology_container_project_build` to materialize it.
- **`synology_container_project_update`** - Update a Container Manager project
  - `name` (required): Project name
  - `content` (required): Docker Compose YAML content
  - `enable_service_portal` (optional): Enable Synology service portal
  - `service_portal_name` (optional): Service portal name
  - `service_portal_port` (optional): Service portal port
  - `service_portal_protocol` (optional): Service portal protocol
- **`synology_container_project_start`** - Start a Container Manager project
  - `name` (required): Project name
- **`synology_container_project_stop`** - Stop a Container Manager project
  - `name` (required): Project name
- **`synology_container_project_restart`** - Restart a Container Manager project
  - `name` (required): Project name
- **`synology_container_project_build`** - Materialize or rebuild a saved Container Manager project
  - `name` (required): Project name
- **`synology_container_project_clean`** - Clean a Container Manager project
  - `name` (required): Project name
- **`synology_container_project_delete`** - Delete a Container Manager project
  - `name` (required): Project name
- **`synology_container_image_list`** - List Container Manager images
  - `offset` (optional): Pagination offset
  - `limit` (optional): Maximum images to return
  - `show_dsm` (optional): Include DSM images (default: false)
- **`synology_container_image_get`** - Get a Container Manager image
  - `name` (required): Image repository name
  - `tag` (optional): Image tag (default: `latest`)
- **`synology_container_image_delete`** - Delete a Container Manager image
  - `name` (required): Image repository name
  - `tag` (optional): Image tag (default: `latest`)
- **`synology_container_image_prune`** - Remove images unused by any container
  - **`synology_container_image_prune_preview`** provides a read-only candidate list before cleanup
  - Uses only Container Manager APIs to delete safely identifiable unused tagged images and reports dangling images it cannot remove through DSM
  - Does not remove containers, networks, or build cache
- **`synology_container_image_pull`** - Pull a Container Manager image
  - `repository` (required): Image repository name
  - `tag` (optional): Image tag (default: `latest`)
- **`synology_container_registry_list`** - List Container Manager registries
- **`synology_container_registry_search`** - Search Container Manager registries
  - `query` (required): Image search query
  - `offset` (optional): Pagination offset
  - `limit` (optional): Maximum results to return
- **`synology_container_registry_tags`** - List tags for a registry image
  - `repository` (required): Image repository name
  - `offset` (optional): Pagination offset
  - `limit` (optional): Maximum tags to return
- **`synology_container_registry_download`** - Download a registry image
  - `repository` (required): Image repository name
  - `tag` (optional): Image tag (default: `latest`)
- **`synology_container_network_list`** - List Container Manager networks
- **`synology_container_network_get`** - Get a Container Manager network
  - `name` (required): Network name
- **`synology_container_network_create`** - Create a Container Manager network
  - `name` (required): Network name
  - `driver` (optional): Network driver (default: `bridge`)
  - `subnet` (optional): Subnet CIDR
  - `gateway` (optional): Gateway IP
  - `ip_range` (optional): Allocatable IP range CIDR
  - `enable_ipv6` (optional): Enable IPv6 (default: false)
- **`synology_container_network_delete`** - Delete a Container Manager network
  - `name` (required): Network name

### ๐Ÿ“ฆ NFS Management
- **`synology_nfs_status`** - Get NFS service status and configuration
- **`synology_nfs_enable`** - Enable or disable the NFS service
- **`synology_nfs_list_shares`** - List all shared folders with their NFS permissions
- **`synology_nfs_set_permission`** - Set NFS client access permissions on a shared folder

### ๐Ÿ”€ Login Portal Reverse Proxy
- **`synology_reverse_proxy_list`** - List reverse proxy entries (Control Panel โ†’ Login Portal โ†’ Advanced โ†’ Reverse Proxy) with source, destination, HSTS, WebSocket, custom headers and access control profile
- **`synology_reverse_proxy_get`** - Get one entry by UUID or description
- **`synology_access_control_profile_list`** - List the access control profiles an entry can reference
- **`synology_reverse_proxy_create`** - Create an entry; refused if the description is already in use
- **`synology_reverse_proxy_update`** - Change some fields of an entry, keeping the rest
- **`synology_reverse_proxy_delete`** - **DESTRUCTIVE.** Delete an entry *(requires `confirm=true`)*
- Every write makes DSM rebuild and reload its nginx configuration, which can take a minute on small NAS models. A write that times out is reported with `outcome_unknown: true` โ€” list before retrying.

## ๐Ÿง  Claude Code / Claude.ai Skill

For Claude Code, Claude Desktop, and claude.ai users, this repo ships an Anthropic Agent Skill that teaches Claude how to use the MCP tools effectively โ€” picking the right tool, targeting the right NAS in multi-NAS setups, preferring aggregate health checks over fan-out calls, and using correct path conventions.

The skill lives at [`skills/synology-nas/`](skills/synology-nas/) and uses progressive disclosure across eight domains (auth, files, downloads, health, containers, shares/NFS, user management, updates & security) plus a reverse-proxy reference.

**Install:**

- **Claude Code**: copy or symlink the folder into `~/.claude/skills/synology-nas/`
- **Claude.ai / Claude Desktop**: upload the `synology-nas/` folder via the Skills settings page

The skill is purely additive โ€” it works alongside the MCP and only triggers on Synology/NAS-related prompts.

### Recovery skill

[`skills/synology-recovery/`](skills/synology-recovery/) is the companion runbook for **restoring files from Btrfs share snapshots** after an accidental delete, a failed bulk operation, or a runaway script. It covers inventory, diffing a snapshot against the live share, missing-only reflink restore that shares existing data blocks, verification, and the stale-mount trap that makes a damaged share look emptier than it is. Snapshot access needs an admin path (DSM UI or SSH with `sudo`); the MCP account can verify the result but cannot read `/volume1/@sharesnap`.

## โš™๏ธ Configuration Options

> **โš ๏ธ Security Warning: Use a Dedicated Account**
>
> For this MCP server, create a dedicated Synology user account with appropriate permissions. This account should:
> - Have minimal required permissions only (not admin!)
> - Be used exclusively for MCP server automation
> - **2FA is now supported** โ€” if your DSM account has 2FA enabled, see the
>   [2FA / OTP Accounts](#2fa--otp-accounts-optional) section below to supply
>   an `otp_code` (one-shot) or `device_id` (persistent) field. Older guidance
>   of "no 2FA" is no longer required.

### Using settings.json (Recommended)

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `SYNOLOGY_URL` | Yes* | - | NAS base URL (e.g., `http://192.168.1.100:5000`) |
| `SYNOLOGY_USERNAME` | Yes* | - | Username for authentication |
| `SYNOLOGY_PASSWORD` | Yes* | - | Password for authentication |
| `AUTO_LOGIN` | No | `true` | Auto-login on server start |
| `VERIFY_SSL` | No | `false` | Verify SSL certificates |
| `DEBUG` | No | `false` | Enable debug logging |
| `ENABLE_XIAOZHI` | No | `false` | Enable Xiaozhi WebSocket bridge |
| `XIAOZHI_TOKEN` | Xiaozhi only | - | Authentication token for Xiaozhi |
| `XIAOZHI_MCP_ENDPOINT` | No | `wss://api.xiaozhi.me/mcp/` | Xiaozhi WebSocket endpoint |

*Required for auto-login and default operations

### Using settings.json (Multi-NAS Support)

For managing multiple Synology NAS devices, use the XDG standard config directory (`~/.config/synology-mcp/settings.json`):

```bash
mkdir -p ~/.config/synology-mcp
touch ~/.config/synology-mcp/settings.json
chmod 600 ~/.config/synology-mcp/settings.json  # Important: secure permissions!
```

**Note:** This follows the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) - `~/.config/` is the standard location for user configuration files on Linux/macOS. You can customize the location by setting the `XDG_CONFIG_HOME` environment variable.

**With Docker:**
The docker-compose.yml automatically mounts your `~/.config/synology-mcp` directory into the container at `/home/mcpuser/.config/synology-mcp`, so multi-NAS works out of the box with Docker as well.

**settings.json format:**
```json
{
  "synology": {
    "nas1": {
      "host": "192.168.1.100",
      "port": 5000,
      "username": "admin",
      "password": "your_password",
      "note": "Primary NAS at home"
    },
    "nas2": {
      "host": "192.168.1.200",
      "port": 5001,
      "username": "admin",
      "password": "your_password",
      "note": "Backup NAS"
    },
    "nas3": {
      "url": "https://nas.example.com",
      "username": "admin",
      "password": "your_password",
      "note": "NAS behind a reverse proxy"
    }
  },
  "xiaozhi": {
    "enabled": false,
    "token": "your_xiaozhi_token",
    "endpoint": "wss://api.xiaozhi.me/mcp/"
  },
  "server": {
    "auto_login": true,
    "verify_ssl": false,
    "session_timeout": 3600,
    "debug": false,
    "log_level": "INFO"
  }
}
```

**Configuration fields:**
| Field | Required | Description |
|-------|----------|-------------|
| `host` | Yes* | NAS hostname or IP address |
| `port` | No | API port (default: 5000 for HTTP, 5001 for HTTPS) |
| `url` | Yes* | Full base URL (e.g., `https://nas.example.com`); wins over `host`/`port` โ€” use for a NAS behind a reverse proxy |
| `username` | Yes | NAS username |
| `password` | Yes** | NAS password |
| `password_env` | Yes** | Name of an environment variable holding the NAS password, read when settings.json is loaded, so the password is never stored in the file |
| `otp_code` | No | One-shot 6-digit 2FA code (first login only, then remove) |
| `device_id` | No | Long-lived trusted-device token from DSM (`did`); skip OTP on all future logins |
| `note` | No | Optional description for your reference |

*Either `host` or `url` is required per NAS entry.

**Password source โ€” set exactly one of `password` or `password_env`.** An entry with both, or whose variable is unset or empty, is skipped with a warning. Use `password_env` when a launcher fetches the password from a secret manager at start (for example `"password_env": "NAS1_PASSWORD"`); under Docker, add `- NAS1_PASSWORD` under the existing `environment:` list in docker-compose.yml, or the entry is skipped at startup.

**Notes:**
- The server will use port 5001 (HTTPS) if port is 5001, otherwise defaults to HTTP (5000)
- The `host`/`port` form always appends a port and derives the scheme from it, so it cannot express `https://nas.example.com` on the default 443 โ€” set `url` directly for reverse-proxied setups
- File permissions: `chmod 600 ~/.config/synology-mcp/settings.json` is required for security
- The server will refuse to load settings if permissions are too open
- Both .env and settings.json can be used together (settings.json takes priority)

### โš ๏ธ Security Recommendations

**settings.json File Permissions:**
- **Linux/macOS (POSIX):** `chmod 600 ~/.config/synology-mcp/settings.json` is required. The server refuses to load the file if it is group- or world-readable/writable, or owned by another user.
- **Windows:** Access control is enforced via NTFS ACLs, not POSIX mode bits. The server audits the file's security descriptor and refuses to load unless **all three** hold: (1) the owner SID matches the current user; (2) the DACL is present (a NULL DACL โ€” "everyone full access" โ€” is rejected); (3) no allow-ACE grants access to a principal outside the allowlist: the current user, `NT AUTHORITY\SYSTEM`, and `BUILTIN\Administrators`. Any inherited `Everyone` / `BUILTIN\Users` / `Authenticated Users` grant fails the check.
  - Requires the optional [`pywin32`](https://pypi.org/project/pywin32/) package: `pip install pywin32`. **If pywin32 is not installed, the server fails closed and refuses to load `settings.json`.** Operators who accept the risk of an unverified file can opt back in by setting `SYNOLOGY_MCP_ALLOW_UNVERIFIED_WINDOWS_ACL=true`.
  - The server resolves the file via `XDG_CONFIG_HOME` (default `Path.home() / ".config"`), so on Windows it lives at `%USERPROFILE%\.config\synology-mcp\settings.json` unless `XDG_CONFIG_HOME` is set.
  - Lock down the file from an elevated PowerShell prompt (uses the same path the server loads):

    ```powershell
    # Resolve the path the SAME way the server does: $XDG_CONFIG_HOME if set,
    # otherwise %USERPROFILE%\.config. This honors the override documented above.
    $cfg = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { "$env:USERPROFILE\.config" }
    $f = "$cfg\synology-mcp\settings.json"

    # The server's ACL audit requires: owner == current user, no NULL DACL, and
    # no allow-ACE outside {current user, SYSTEM, Administrators}. The steps
    # below enforce all three.
    #
    # Use the *<SID> form for every built-in principal: account names like
    # "Administrators" / "Everyone" / "Users" are localized on non-English
    # Windows (e.g. German "Administratoren") and won't resolve. The
    # locale-independent SIDs:
    #   *S-1-1-0            Everyone
    #   *S-1-5-11           Authenticated Users
    #   *S-1-5-32-545       BUILTIN\Users
    #   *S-1-5-32-544       BUILTIN\Administrators
    #
    # 1. Ensure the file is owned by the current user (the audit rejects any
    #    other owner). /setowner requires elevation.
    icacls $f /setowner "${env:USERNAME}"
    # 2. Drop inherited ACEs, then revoke the common foreign grants. /grant:r
    #    only replaces the named principal, so revoke first.
    icacls $f /inheritance:r
    icacls $f /remove:g "*S-1-1-0" "*S-1-5-11" "*S-1-5-32-545"
    # Re-run `icacls $f` here; if any principal other than your user or
    # Administrators still appears, run: icacls $f /remove:g "<that principal>"
    # 3. Grant the current user and Administrators full control.
    icacls $f /grant:r "${env:USERNAME}:(F)"
    icacls $f /grant:r "*S-1-5-32-544:(F)"   # BUILTIN\Administrators (locale-independent)
    ```
    If the file is brand new, the `/remove:g` step is a harmless no-op.
  - Verify: `icacls "$f"` โ€” only your user and `*S-1-5-32-544` (Administrators) should appear.

**SSL Certificate Verification (VERIFY_SSL):**
- Default is `false` to support self-signed certificates on internal NAS devices
- **If your NAS has a valid SSL certificate (e.g., from Let's Encrypt or a corporate CA), set `VERIFY_SSL=true`**
- Setting `VERIFY_SSL=false` disables certificate verification and makes your connection vulnerable to man-in-the-middle (MITM) attacks
- Never disable SSL verification on untrusted networks

**Auto-Login (AUTO_LOGIN):**
- Default is `true` for convenience with settings.json
- Credentials are stored securely in `~/.config/synology-mcp/settings.json` with 0600 permissions
- If you prefer manual login, set `AUTO_LOGIN=false` and use the `synology_login` tool

**2FA / OTP Accounts (optional):**

The MCP server supports DSM accounts with 2FA enabled. There are two ways to use it:

1. **One-shot OTP via `synology_login` tool** (interactive):
   ```json
   { "base_url": "https://nas.lan:5001", "username": "alice", "password": "โ€ฆ", "otp_code": "123456" }
   ```
   DSM will return a `did` (device token) in the response โ€” copy that value into `settings.json` (below) to skip OTP on future process restarts.

2. **Persistent trusted-device token** (recommended for `AUTO_LOGIN=true`):

   Add `otp_code` (one-shot, **first login only**) and/or `device_id` (long-lived, ongoing) fields per-NAS in `settings.json`:

   ```json
   {
     "synology": {
       "nas1": {
         "host": "192.168.1.100", "port": 5001,
         "username": "alice", "password": "โ€ฆ",
         "otp_code": "123456",
         "note": "primary โ€” 2FA enabled"
       }
     }
   }
   ```

   **Workflow:**
   1. Set `otp_code` to a fresh 6-digit code from your authenticator and start the server.
   2. On the first successful login, the server logs a warning line like:
      `nas1: 2FA bootstrap โ€” copy this device_id into settings.json to skip OTP on future starts: <did>`
      Copy the `<did>` value.
   3. Paste it into `device_id` and delete `otp_code`.
   4. From now on, DSM treats this process as a trusted device โ€” restarts, relogins after DSM error 119, and container-manager sessions all skip OTP.

   When `device_id` is present, it takes precedence over `otp_code` (trusted-device path). Legacy `.env` users can set the one-shot `SYNOLOGY_OTP_CODE` env var; for persistent `device_id`, migrate to `settings.json` (long opaque token doesn't fit an env var cleanly).

## ๐Ÿ“– Usage Examples

### ๐Ÿ“ File Operations

File Station paths are share-relative โ€” `/photo`, `/documents/notes.txt` โ€” not
filesystem paths like `/volume1/photo`. (Note: `delete` additionally refuses
paths under `/homes`, DSM's home-folder share.)

#### โœ… Creating Files and Directories
![File Creation](assets/add.png)

```json
// List directory
{
  "path": "/homes"
}

// Search for PDFs
{
  "path": "/documents",
  "pattern": ".pdf"
}

// Create new file
{
  "path": "/documents/notes.txt",
  "content": "My important notes\nLine 2 of notes",
  "overwrite": false
}
```

#### ๐Ÿ—‘๏ธ Deleting Files and Directories
![File Deletion](assets/delete.png)

```json
// Delete file or directory (auto-detects type)
{
  "path": "/temp/old-file.txt"
}

// Move file
{
  "source_path": "/temp/file.txt",
  "destination_path": "/archive/file.txt"
}
```

### โฌ‡๏ธ Download Management

#### ๐Ÿ› ๏ธ Creating a Download Task
![Download Sample](assets/download_sample.png)

```json
// Create download task
{
  "uri": "https://example.com/file.zip",
  "destination": "/downloads"
}

// Pause tasks
{
  "task_ids": ["dbid_123", "dbid_456"]
}
```

#### ๐Ÿฆฆ Download Results
![Download Result](assets/download_result.png)

## โœจ Features

- โœ… **Unified Entry Point** - Single `main.py` supports both stdio and WebSocket clients
- โœ… **Environment Controlled** - Switch modes via `ENABLE_XIAOZHI` environment variable
- โœ… **Multi-Client Support** - Simultaneous Claude/Cursor + Xiaozhi access
- โœ… **Secure Authentication** - RSA encrypted password transmission
- โœ… **Session Management** - Persistent sessions across multiple NAS devices  
- โœ… **Complete File Operations** - Create, delete, list, search, rename, move files with detailed metadata
- โœ… **Directory Management** - Recursive directory operations with safety checks
- โœ… **Download Station** - Complete torrent and download management
- โœ… **Docker Support** - Easy containerized deployment
- โœ… **Backward Compatible** - Existing configurations work unchanged
- โœ… **Error Handling** - Comprehensive error reporting and recovery

## ๐Ÿ—๏ธ Architecture

### File Structure
```
mcp-server-synology/
โ”œโ”€โ”€ main.py                    # ๐ŸŽฏ Unified entry point
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ mcp_server.py         # Standard MCP server
โ”‚   โ”œโ”€โ”€ multiclient_bridge.py # Multi-client bridge
โ”‚   โ”œโ”€โ”€ auth/                 # Authentication modules
โ”‚   โ”œโ”€โ”€ filestation/          # File operations
โ”‚   โ””โ”€โ”€ downloadstation/      # Download management
โ”œโ”€โ”€ docker-compose.yml        # Single service, environment-controlled
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ pyproject.toml            # Dependencies (single source of truth)
โ””โ”€โ”€ .env                      # Configuration
```

### Mode Selection
- **`ENABLE_XIAOZHI=false`** โ†’ `main.py` โ†’ `mcp_server.py` (stdio only)
- **`ENABLE_XIAOZHI=true`** โ†’ `main.py` โ†’ `multiclient_bridge.py` โ†’ `mcp_server.py` (both clients)

**Perfect for any workflow - from simple Claude/Cursor usage to advanced multi-client setups!** ๐Ÿš€