Skip to main content
Glama
Navidrome MCP Player

Navidrome MCP Player

by Rjtsahu
README.md
# Navidrome MCP Player

[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![MCP: Streamable HTTP](https://img.shields.io/badge/MCP-Streamable%20HTTP-purple.svg)](https://modelcontextprotocol.io/)
[![Platform: macOS | Linux | Windows](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey.svg)](#prerequisites)

A lightweight, cross-platform **Model Context Protocol (MCP)** server and **Web UI** in Python that turns your Mac, Linux, or Windows machine into a remote-controlled music player backed by **Navidrome** (or any Subsonic-compatible server) using `mpv`.

Built for AI agents (**n8n**, **Claude**, **Cursor**, **Telegram bots**) over **Tailscale** or LAN, with an integrated dark-mode browser dashboard for manual playback control and runtime settings.

---

## Architecture

```mermaid
flowchart LR
    Agent["AI Agent / n8n / MCP Client"] -->|"Streamable HTTP (/mcp)\nBearer Token"| FastAPI["FastAPI + MCPServer"]
    Browser["Web UI (/)"] -->|"HttpOnly Session Cookie\nREST (/api/*)"| FastAPI
    FastAPI -->|"Subsonic REST API\n(Salted MD5 Auth)"| Navidrome["Navidrome Server"]
    FastAPI -->|"JSON IPC\n(Unix Socket / Named Pipe)"| MPV["mpv Subprocess"]
    Navidrome -->|"Direct Audio Stream\n(/rest/stream)"| MPV
    MPV --> Speakers["Local Audio Output"]
```

## Features

- **MCP Streamable HTTP (`/mcp`)**: Exposes 11 ready-to-use tools for searching, playing songs/playlists, managing the queue, and controlling playback and volume.
- **Lightweight Web UI (`/`)**: Clean, zero-build dark dashboard with Now Playing, queue view, search & play, playlists, volume slider, and runtime MCP settings.
- **Cross-platform `mpv` JSON IPC**: Uses Unix domain sockets on Linux/macOS and named pipes on Windows — no external player daemon required.
- **Direct Streaming & Auto-Scrobbling**: Streams `/rest/stream` directly from Navidrome without temporary files and optionally scrobbles finished tracks back to Navidrome.
- **Secure by Default**: Fail-closed Bearer token & `HttpOnly` cookie authentication with constant-time comparison, strict Subsonic ID validation, CSP headers, and stream URLs kept strictly server-side.

---

## Prerequisites

1. **Python 3.11+**
2. **A running [Navidrome](https://www.navidrome.org/) (or Subsonic-compatible) server**
3. **`mpv`** installed and available on your `PATH`:
   - **macOS:** `brew install mpv`
   - **Linux (Debian/Ubuntu):** `sudo apt install mpv`
   - **Windows:** `winget install mpv` (or `scoop install mpv`)

---

## Quick Start

```bash
git clone https://github.com/Rjtsahu/navidrome-mcp-player.git
cd navidrome-mcp-player

python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate

pip install -e ".[dev]"

cp .env.example .env
# Generate a strong MCP_AUTH_TOKEN:
python3 -c "import secrets; print(secrets.token_urlsafe(32))"
```

Edit `.env` with your Navidrome URL, credentials, and generated `MCP_AUTH_TOKEN`, then start the server:

```bash
navidrome-mcp
```

Open `http://127.0.0.1:8765` in your browser and unlock the dashboard with your `MCP_AUTH_TOKEN`.

> **Note:** If `MCP_AUTH_TOKEN` is left empty, an ephemeral token is generated per process and logged as a warning. Set a persistent token in `.env` for production or agent integrations.

---

## Configuration

All settings are loaded from environment variables or `.env`:

| Variable | Default | Description |
| --- | --- | --- |
| `NAVIDROME_URL` | `http://127.0.0.1:4533` | Base URL of your Navidrome/Subsonic server |
| `NAVIDROME_USER` | `""` | Navidrome username |
| `NAVIDROME_PASSWORD` | `""` | Navidrome password |
| `MCP_AUTH_TOKEN` | `""` | Bearer token for `/mcp`, `/api/*`, and Web UI login |
| `HOST` | `127.0.0.1` | Bind address (`127.0.0.1` for local, or Tailscale/LAN IP) |
| `PORT` | `8765` | HTTP server port (`1`–`65535`) |
| `MPV_PATH` | `mpv` | Executable name or full path to `mpv` |
| `DEFAULT_VOLUME` | `80` | Initial player volume (`0`–`100`) |
| `AUTO_SCROBBLE` | `true` | Scrobble finished tracks to Navidrome |
| `SEARCH_LIMIT` | `5` | Max search results returned (`1`–`25`) |
| `QUEUE_SEARCH_MATCHES` | `true` | Queue all matched songs on `play_song(query=...)` |

The last four settings (`DEFAULT_VOLUME`, `AUTO_SCROBBLE`, `SEARCH_LIMIT`, `QUEUE_SEARCH_MATCHES`) can also be adjusted live at runtime from the Web UI **MCP Settings** panel.

---

## MCP Tools Reference

All tools are exposed over Streamable HTTP at `/mcp`:

| Tool | Parameters | Description |
| --- | --- | --- |
| `search_music` | `query: str`, `search_type: str = "song"` | Search songs, albums, or artists (`"song"`, `"album"`, `"artist"`) |
| `play_song` | `query: str = ""`, `song_id: str = ""` | Play a song by ID or search query (queues matches if enabled) |
| `play_playlist` | `name_or_id: str`, `shuffle: bool = False` | Load a playlist by ID or name (exact match preferred) and play |
| `pause_resume` | — | Toggle pause/resume on the active track |
| `stop` | — | Stop playback and clear the queue |
| `next_track` | — | Skip to the next track in the queue |
| `previous_track` | — | Return to the previous track (or restart the first track) |
| `now_playing` | — | Get current track, state, position, duration, volume, and remaining queue |
| `list_playlists` | — | List all playlists visible to the configured Navidrome user |
| `get_queue` | — | Return the current playback queue and active index |
| `set_volume` | `level: int` | Set playback volume (`0`–`100`) |

---

## REST API Reference

The Web UI communicates with these JSON endpoints (protected by Bearer token or `mcp_session` cookie):

- `GET /health` — Unauthenticated liveness probe (`{"status": "ok"}`)
- `POST /auth/login` — Exchange `{"token": "..."}` for an `HttpOnly` session cookie
- `POST /auth/logout` — Clear the session cookie
- `GET /api/status` — Current playback state, track, queue, position, and volume
- `POST /api/play` — Play by `{"query": "..."}` or `{"song_id": "..."}`
- `POST /api/play-playlist` — Play a playlist by `{"playlist_id": "...", "shuffle": false}`
- `POST /api/pause`, `POST /api/stop`, `POST /api/next`, `POST /api/prev` — Transport controls
- `POST /api/volume` — Set volume (`{"level": 80}`)
- `GET /api/playlists` — List playlists
- `GET /api/search?q=...` — Search songs
- `GET /api/settings`, `POST /api/settings` — Read or update runtime MCP settings

---

## Connecting Clients

### n8n over Tailscale (e.g., Telegram AI Agent)

1. Set `HOST` in `.env` to your machine's Tailscale IP (e.g., `100.x.y.z`).
2. In n8n, add an **MCP Client Tool** node connected to your **AI Agent**:
   - **Endpoint:** `http://100.x.y.z:8765/mcp`
   - **Transport:** Streamable HTTP
   - **Header Auth:** `Authorization: Bearer <your_MCP_AUTH_TOKEN>`

### Generic MCP Streamable HTTP Client

Point any MCP-compatible client at `http://<host>:8765/mcp` with header:

```http
Authorization: Bearer <your_MCP_AUTH_TOKEN>
```

---

## Security Model

- **Authentication:** Every `/mcp` and `/api/*` request requires a valid `Authorization: Bearer <token>` header or `mcp_session` `HttpOnly` cookie, verified with `hmac.compare_digest`.
- **Credential Isolation:** Subsonic API requests use salted MD5 tokens (`t = md5(password + salt)`). Authenticated `/rest/stream` URLs are passed directly to the local `mpv` process and never returned in MCP or REST responses.
- **Input Validation:** Song and playlist IDs are validated against `^[A-Za-z0-9._-]+$` before constructing Subsonic requests.
- **HTTP Hardening:** Responses include `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, and a strict `Content-Security-Policy`.

---

## Development & Testing

```bash
# Run the test suite
pytest -v
```

### Project Structure

```text
navidrome-mcp-player/
├── src/navidrome_mcp/
│   ├── config.py        # Pydantic settings & runtime MCP options
│   ├── navidrome.py     # Async Subsonic / Navidrome REST client
│   ├── player.py        # Cross-platform mpv JSON IPC & queue manager
│   ├── mcp_server.py    # FastMCP tool definitions
│   ├── web.py           # FastAPI app, auth middleware, REST API & entrypoint
│   └── static/          # Zero-build Web UI (HTML, CSS, vanilla JS)
├── tests/               # Unit tests for Navidrome client, mpv player, MCP tools & web API
├── .env.example
└── pyproject.toml
```

---

## Contributing

Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on reporting issues, running tests, and submitting pull requests.

## License

MIT — see [LICENSE](LICENSE).