Your comprehensive Sonos control companion powered by the Model Context Protocol (MCP). This intelligent server provides seamless access to Sonos audio devices over your local network using UPnP/SOAP protocols. Whether you're controlling playback, managing zones, browsing your music library, or setting up alarms, this MCP server delivers complete device control directly to your AI assistant, enabl
Add this skill
npx mdskills install Tommertom/sonos-ts-mcpComprehensive Sonos control with 50+ tools, excellent docs, and AI agent integration
1# Sonos TypeScript MCP Server23Your comprehensive Sonos control companion powered by the Model Context Protocol (MCP). This intelligent server provides seamless access to Sonos audio devices over your local network using UPnP/SOAP protocols. Whether you're controlling playback, managing zones, browsing your music library, or setting up alarms, this MCP server delivers complete device control directly to your AI assistant, enabling smart home automation and better audio experiences.45**Specifically designed for coding agents and AI-driven home audio automation workflows.** This server enables AI assistants to build intelligent multi-room audio experiences, music library management, zone grouping, queue management, and integration with smart home platforms.67Data is sourced from real-time UPnP/SOAP communication with Sonos devices to ensure accuracy and completeness.89> **📊 Feature Status**: Phase 4 complete! Implements real-time event subscriptions with UPnP GENA protocol for playback, volume, queue, and topology changes. See [Phase 4 completion](./docs/PHASE-4-COMPLETE.md) for details.1011## 📚 Documentation1213- **[Comprehensive Tool Descriptions](./docs/TOOL_DESCRIPTIONS.md)** - Detailed guide for coding agents with use cases, workflows, and best practices for all 50+ tools14- **[API Reference](./docs/)** - Technical API documentation15- **[Example Scripts](./scripts/)** - Sample automation scripts and use cases1617## Getting Started1819The Sonos TypeScript MCP Server can work with any MCP client that supports standard I/O (stdio) as the transport medium. Here are specific instructions for some popular tools:2021### Basic Configuration2223#### Claude Desktop2425To configure Claude Desktop to use the Sonos MCP server, edit the `claude_desktop_config.json` file. You can open or create this file from the Claude > Settings menu. Select the Developer tab, then click Edit Config.2627```json28{29 "mcpServers": {30 "sonos-ts-mcp": {31 "command": "npx",32 "args": ["-y", "sonos-ts-mcp@latest"]33 }34 }35}36```3738#### Cline3940To configure Cline to use the Sonos MCP server, edit the `cline_mcp_settings.json` file. You can open or create this file by clicking the MCP Servers icon at the top of the Cline pane, then clicking the Configure MCP Servers button.4142```json43{44 "mcpServers": {45 "sonos-ts-mcp": {46 "command": "npx",47 "args": ["-y", "sonos-ts-mcp@latest"],48 "disabled": false49 }50 }51}52```5354#### Cursor5556To configure Cursor to use the Sonos MCP server, edit either the file `.cursor/mcp.json` (to configure only a specific project) or the file `~/.cursor/mcp.json` (to make the MCP server available in all projects):5758```json59{60 "mcpServers": {61 "sonos-ts-mcp": {62 "command": "npx",63 "args": ["-y", "sonos-ts-mcp@latest"]64 }65 }66}67```6869#### Visual Studio Code Copilot7071To configure a single project, edit the `.vscode/mcp.json` file in your workspace:7273```json74{75 "servers": {76 "sonos-ts-mcp": {77 "type": "stdio",78 "command": "npx",79 "args": ["-y", "sonos-ts-mcp@latest"]80 }81 }82}83```8485To make the server available in every project you open, edit your user settings:8687```json88{89 "mcp": {90 "servers": {91 "sonos-ts-mcp": {92 "type": "stdio",93 "command": "npx",94 "args": ["-y", "sonos-ts-mcp@latest"]95 }96 }97 }98}99```100101#### Windsurf Editor102103To configure Windsurf Editor, edit the file `~/.codeium/windsurf/mcp_config.json`:104105```json106{107 "mcpServers": {108 "sonos-ts-mcp": {109 "command": "npx",110 "args": ["-y", "sonos-ts-mcp@latest"]111 }112 }113}114```115116## Testing with an Agent117118You can quickly test the MCP server using the built-in CLI agent, which uses natural language to interact with your Sonos system:119120```bash121# Run directly with npx (no installation required)122npx sonos-agent-cli "Play jazz in the living room"123124# Use a specific AI model125npx sonos-agent-cli "What's playing in the kitchen?" --model gpt-4o126127# Use Gemini models128npx sonos-agent-cli "Set volume to 50 in all rooms" --model gemini-3-pro-preview129```130131**Required Environment Variables:**132133- `OPENAI_API_KEY`: For OpenAI models (gpt-4o, gpt-4o-mini, etc.)134- `GOOGLE_GENERATIVE_AI_API_KEY`: For Gemini models135- `SONOS_AGENT_MODEL`: Set a default model (optional)136137**Build Behavior:**138139The CLI automatically builds the MCP server before running to ensure the latest code is used. To skip the build (e.g., during rapid testing), use `--skip-build`:140141```bash142npx sonos-agent-cli "Play music" --skip-build143```144145This agent provides an easy way to verify that the MCP server is working correctly and can communicate with your Sonos devices.146147## Features148149This MCP server provides comprehensive control of your Sonos audio system:150151- **AI-Powered Agent Tool**: Natural language control via the `sonos_agent` tool (requires AI API keys) ✨ NEW152- **Topology Persistence**: Device topology automatically saved to disk and loaded on startup153- **Intelligent Device Resolution**: Control devices by friendly name (e.g., "Kitchen") instead of UUIDs154- **Automatic Discovery**: Discovers devices on startup and every 5 minutes155- **Device Discovery**: Manual SSDP-based discovery of Sonos devices156- **Playback Control**: Play, pause, stop, next, previous157- **Volume Control**: Get and set volume levels, mute/unmute158- **Transport Info**: Get current playback state and track information159- **Zone Topology**: Query zone groups and speaker configurations160- **Queue Management**: Full queue control (add, remove, reorder, save, play)161- **DIDL-Lite Support**: Complete metadata handling for tracks, albums, and containers162- **Playback Properties**: Shuffle, repeat, and crossfade controls163- **Group Management**: Join and unjoin devices to create multi-room groups164- **Music Library Browsing**: Browse artists, albums, tracks, genres, and playlists165- **Library Search**: Fuzzy search across your music library166- **Audio/EQ Controls**: Bass, treble, loudness, night mode, dialog enhancement167- **Sleep Timer**: Automatic playback stop after duration168- **Alarm Management**: Create, update, and delete alarms169- **Snapshot/Restore**: Save and restore complete device state170- **Party Mode**: Join all devices at once171- **Event Subscriptions**: Real-time notifications for state changes ✨ NEW172- **MCP Prompts**: Exposes AI agent instructions as discoverable prompts ✨ NEW173- **Pure TypeScript**: Built from scratch without external Sonos libraries174- **MCP Compatible**: Integrates with any MCP-compatible client175176### Planned Features (Phase 5+)177178This project is actively expanding to match the comprehensive feature set of the Python SoCo library:179180- Music service integration (Spotify, Apple Music)181- 🟢 Advanced group management (stereo pairs, home theater)182- 🟢 Audio analysis and diagnostics183- 🟢 MCP event tool integration184185See the [Phase 4 completion](./docs/PHASE-4-COMPLETE.md) for the latest features.186187## Tools Available188189### AI Agent Tool ✨ NEW190| Tool | Description |191|------|-------------|192| `sonos_agent` | AI-powered natural language control. Give instructions like "Play jazz in the living room" and the agent autonomously handles device discovery, tool selection, and execution. Only available when `OPENAI_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY` is configured. See [Agent Tool Documentation](./docs/agent-tool.md) for details. |193194### Discovery Tools195| Tool | Description |196|------|-------------|197| `sonos_discover` | Discover Sonos devices on the network using SSDP multicast |198| `sonos_add_device` | Manually add a Sonos device by IP address (useful when SSDP discovery fails) |199| `sonos_list_devices` | List all discovered/registered devices |200201### Playback Control Tools202| Tool | Description |203|------|-------------|204| `sonos_play` | Start playback |205| `sonos_pause` | Pause playback |206| `sonos_stop` | Stop playback |207| `sonos_next` | Skip to next track |208| `sonos_previous` | Skip to previous track |209210### Volume Control Tools211| Tool | Description |212|------|-------------|213| `sonos_set_volume` | Set volume (0-100) |214| `sonos_get_volume` | Get current volume |215| `sonos_set_mute` | Mute or unmute |216217### Queue Management Tools218| Tool | Description |219|------|-------------|220| `sonos_get_queue` | Get the current playback queue |221| `sonos_add_to_queue` | Add a URI to the queue |222| `sonos_remove_from_queue` | Remove a track from the queue |223| `sonos_clear_queue` | Remove all tracks from the queue |224| `sonos_play_from_queue` | Play from a specific queue position |225| `sonos_save_queue` | Save the queue as a Sonos playlist |226227### Playback Properties Tools228| Tool | Description |229|------|-------------|230| `sonos_set_shuffle` | Enable or disable shuffle mode |231| `sonos_set_repeat` | Set repeat mode (off, all, one) |232| `sonos_set_crossfade` | Enable or disable crossfade |233| `sonos_get_playback_state` | Get shuffle, repeat, crossfade, and playback state |234235### Group Management Tools236| Tool | Description |237|------|-------------|238| `sonos_join_group` | Join a device to another device's group |239| `sonos_unjoin` | Remove a device from its group |240| `sonos_party_mode` | Join all devices at once |241242### Music Library Tools243| Tool | Description |244|------|-------------|245| `sonos_browse_artists` | Browse all artists in the music library |246| `sonos_browse_albums` | Browse all albums in the music library |247| `sonos_browse_tracks` | Browse all tracks in the music library |248| `sonos_browse_genres` | Browse all genres in the music library |249| `sonos_browse_playlists` | Browse Sonos playlists |250| `sonos_get_favorite_radio_stations` | Get favorite radio stations from Sonos favorites |251| `sonos_search_library` | Search the music library |252| `sonos_browse_item` | Browse subcategories (e.g., albums for an artist) |253254### Music Services Tools255| Tool | Description |256|------|-------------|257| `sonos_list_music_services` | List available music services (Sonos Radio, TuneIn, Spotify, etc.) |258| `sonos_browse_music_service` | Browse content from a music service (categories, stations, playlists) |259| `sonos_search_music_service` | Search for content within a music service |260| `sonos_play_music_service_item` | Play an item from a music service (radio station, track, album) |261| `sonos_get_music_service_item_uri` | Get the streaming URI for a music service item |262263### Audio/EQ Control Tools264| Tool | Description |265|------|-------------|266| `sonos_set_bass` | Set bass level (-10 to 10) |267| `sonos_set_treble` | Set treble level (-10 to 10) |268| `sonos_set_loudness` | Enable/disable loudness compensation |269| `sonos_get_eq` | Get all EQ settings |270| `sonos_set_night_mode` | Enable/disable night mode (home theater) |271| `sonos_set_dialog_mode` | Enable/disable dialog enhancement (home theater) |272273### Sleep Timer Tools274| Tool | Description |275|------|-------------|276| `sonos_set_sleep_timer` | Set automatic playback stop timer |277| `sonos_get_sleep_timer` | Get remaining timer |278| `sonos_cancel_sleep_timer` | Cancel sleep timer |279280### Alarm Management Tools281| Tool | Description |282|------|-------------|283| `sonos_list_alarms` | List all alarms |284| `sonos_create_alarm` | Create a new alarm |285| `sonos_update_alarm` | Update an existing alarm |286| `sonos_delete_alarm` | Delete an alarm |287288### State Management Tools289| Tool | Description |290|------|-------------|291| `sonos_snapshot` | Take a snapshot of device state |292| `sonos_restore_snapshot` | Restore from snapshot |293294### Event Subscription Tools295| Tool | Description |296|------|-------------|297| `sonos_subscribe_events` | Subscribe to real-time device events (AVTransport, RenderingControl, Queue, ZoneGroupTopology, AlarmClock) |298| `sonos_unsubscribe_events` | Unsubscribe from a specific subscription |299| `sonos_unsubscribe_all` | Unsubscribe from all device subscriptions |300| `sonos_list_subscriptions` | List active event subscriptions |301302### Information Tools303| Tool | Description |304|------|-------------|305| `sonos_get_transport_info` | Get playback state |306| `sonos_get_position_info` | Get current track details |307| `sonos_get_zone_groups` | Get zone topology |308309## Development and Installation310311```bash312npm install313npm run build314```315316### Test Discovery317318After installation, you can test if your Sonos devices can be discovered:319320```bash321npm run test:discovery322```323324This will perform an SSDP multicast search and display any Sonos devices found on your network.325326### Test Favorite Radio Stations327328You can test the favorite radio stations feature:329330```bash331npm run test:radio332```333334This will query your Sonos device for saved radio stations and display them. If no stations are found, it will provide instructions on how to add some using the Sonos app.335336### Test Agent Tool337338You can test the AI-powered agent tool (requires AI API keys):339340```bash341# Set up your API key first342export OPENAI_API_KEY=sk-...343# or344export GOOGLE_GENERATIVE_AI_API_KEY=...345346# Run the test347npm run test:agent-tool348```349350This will verify that the agent tool is properly configured and can execute natural language instructions. See the [Agent Tool Documentation](./docs/agent-tool.md) for more details.351352353## Usage354355### As MCP Server356357The server supports two transport modes:358359#### Stdio Mode (Default)360361Stdio mode is the standard way to run MCP servers, communicating over standard input/output. This is the mode used by most MCP clients.362363Add to your MCP client configuration:364365```json366{367 "mcpServers": {368 "sonos": {369 "command": "node",370 "args": ["path/to/sonos-ts-mcp/dist/index.js"]371 }372 }373}374```375376Or run directly:377378```bash379node dist/index.js380```381382You can also use the convenience script:383384```bash385npm run start:stdio386# or387tsx scripts/start-mcp-stdio.ts388```389390#### CLI Agent391392The project includes a CLI agent powered by Mastra that allows you to control your Sonos system using natural language.393394```bash395# Run with default model (gpt-4o-mini)396npx sonos-agent-cli "Play jazz in the living room"397398# Run with a specific model399npx sonos-agent-cli "Play jazz in the living room" --model gpt-4o400401# Run with Gemini 3402npx sonos-agent-cli "Play jazz in the living room" --model gemini-3-pro-preview403```404405**Environment Variables:**406407- `OPENAI_API_KEY`: Required for OpenAI models (default)408- `GOOGLE_GENERATIVE_AI_API_KEY`: Required for Gemini models409- `SONOS_AGENT_MODEL`: Set the default model (optional, e.g., `gemini-3-pro-preview`)410411**Note on Telemetry**: The Mastra framework's built-in telemetry has been disabled in this implementation. Telemetry warnings are suppressed by setting `globalThis.___MASTRA_TELEMETRY___ = true` before Mastra initialization. This is set automatically in the CLI agent.412413#### SSE Mode (HTTP Server)414415SSE (Server-Sent Events) mode runs the MCP server as an HTTP server, useful for web-based clients or remote access.416417Set the `MCP_TRANSPORT` environment variable to `sse`:418419```bash420MCP_TRANSPORT=sse node dist/index.js421```422423Or with custom port (default is 3000):424425```bash426MCP_TRANSPORT=sse MCP_PORT=8080 node dist/index.js427```428429You can also use the convenience script:430431```bash432npm run start:sse433# or434tsx scripts/start-mcp-sse.ts435```436437With custom port:438439```bash440MCP_PORT=8080 npm run start:sse441```442443The server will start an HTTP endpoint at `http://localhost:3000/sse` (or your configured port) that clients can connect to.444445### Development446447```bash448npm run dev # Run with tsx (hot reload)449npm run build # Compile TypeScript450npm run typecheck # Type checking only451npm run lint # ESLint452npm run format # Prettier453npm test # Run tests454npm run test:discovery # Test Sonos device discovery455npm run test:phase1 # Test Phase 1 APIs (Queue, Playback)456npm run test:phase2 # Test Phase 2 APIs (Groups, Library)457npm run test:phase3 # Test Phase 3 APIs (Audio, Alarms)458npm run test:phase4 # Test Phase 4 APIs (Events)459npm run test:all-phases # Run all phase tests460```461462### Testing463464Comprehensive API test scripts are available for all implemented features:465466```bash467# Run all tests468npm run test:all-phases469470# Or run individual phase tests471npm run test:phase1 # Queue, DIDL, Playback Properties472npm run test:phase2 # Groups & Music Library Browsing473npm run test:phase3 # Audio, Alarms, Snapshots474npm run test:phase4 # Event Subscriptions475476# Run Phase 2 tests in mock mode (no physical devices required)477npm run test:phase2 -- --mock478479# Run integration tests (uses AI validation)480npm test481```482483**Note**: Phase 2 tests support a mock mode for testing without physical Sonos devices. Use `--mock` flag or set `MOCK_DEVICES=true` environment variable.484485**AI-Powered Integration Tests**: The integration test suite uses Gemini 2.5 Flash AI to intelligently validate agent outputs instead of brittle string matching. This provides semantic understanding of test results and adapts to different output formats. Requires `GOOGLE_GENERATIVE_AI_API_KEY` environment variable.486487See the [API Testing Guide](./docs/api-testing-guide.md) and [AI-Powered Testing Guide](./docs/ai-powered-testing.md) for detailed documentation on the test suite.488489## Architecture490491```492src/493├── discovery/ # SSDP device discovery494│ ├── ssdp-client.ts495│ └── device-registry.ts496├── didl/ # DIDL-Lite metadata handling497│ ├── didl-object.ts498│ ├── didl-resource.ts499│ ├── didl-item.ts500│ ├── didl-container.ts501│ ├── didl-serializer.ts502│ ├── didl-parser.ts503│ └── index.ts504├── soap/ # SOAP/UPnP transport layer505│ ├── client.ts506│ ├── request-builder.ts507│ └── response-parser.ts508├── services/ # Sonos service wrappers509│ ├── base-service.ts510│ ├── av-transport.ts # Playback, queue, sleep timer511│ ├── rendering-control.ts # Volume, EQ, audio enhancements512│ ├── zone-topology.ts # Groups, party mode513│ ├── content-directory.ts # Music library browsing514│ ├── alarm-clock.ts # ✨ NEW: Alarm management515│ └── snapshot.ts # ✨ NEW: State snapshot/restore516├── mcp/ # MCP server implementation517│ └── server.ts518└── types/ # TypeScript definitions519 ├── sonos.ts520 └── queue.ts521```522523## Protocol Details524525### Discovery (SSDP)526- Sends UDP multicast to `239.255.255.250:1900`527- Searches for `urn:schemas-upnp-org:device:ZonePlayer:1`528- Parses response headers to extract device location529530**Note on Discovery**: SSDP multicast discovery may not work in all network environments due to:531- Windows Firewall blocking UDP port 1900532- Network switches not properly forwarding multicast traffic533- VPN interference with multicast routing534- Corporate network policies535536If automatic discovery fails, use the `sonos_add_device` tool to manually register devices by IP address. The server will verify connectivity before registering the device.537538### Manual Device Registration539540When SSDP discovery doesn't work, you can manually add devices:541542```typescript543// Using the MCP tool544sonos_add_device({545 ip: "192.168.1.100",546 port: 1400, // optional, defaults to 1400547 name: "Kitchen" // optional, defaults to "Sonos at {ip}"548})549```550551The server will test connectivity to the device before adding it to the registry.552553### Control (SOAP/UPnP)554- HTTP POST to `http://{ip}:1400/...`555- XML-based SOAP envelopes556- Supports all standard Sonos UPnP services557558## Documentation559560- 🤖 **[Agent Tool Guide](./docs/agent-tool.md)** - AI-powered natural language control ✨ NEW561- 📚 **[Comprehensive Tool Descriptions](./docs/TOOL_DESCRIPTIONS.md)** - Detailed guide for coding agents with use cases, workflows, and best practices for all 50+ tools562- 📦 [Installation Guide](./docs/installation-guide.md) - Detailed installation and configuration instructions563- 💾 [Topology Persistence Guide](./docs/topology-persistence.md) - Device topology storage and management ✨ NEW564- 🎯 [Device Resolution Guide](./docs/device-resolution.md) - Using friendly device names ✨ NEW565- 🧪 [API Testing Guide](./docs/api-testing-guide.md) - Comprehensive test suite documentation566- 📘 [Implementation Guide](./docs/implementation-guide.md) - Tool usage and examples567- 🏗️ [Technical Architecture](./docs/technical-architecture.md) - System design details568- 📚 [Phase Completion Docs](./docs/) - PHASE-1-COMPLETE.md through PHASE-4-COMPLETE.md569570## Contributing571572Contributions are welcome! This project is expanding to provide comprehensive Sonos control. See the [roadmap](./docs/implementation-roadmap.md) for planned features.573574Areas where contributions are especially valuable:575- Implementing additional UPnP services576- Adding DIDL-Lite object model577- Event subscription system578- Test coverage expansion579- Documentation improvements580581## License582583MIT584
Full transparency — inspect the skill content before installing.