Skip to main content
Glama
raulpetruta

Spotify MCP Server

by raulpetruta
README.md
# Spotify MCP Server

A comprehensive Model Context Protocol (MCP) server that provides seamless integration with Spotify's Web API. This server enables AI assistants and other MCP clients to interact with Spotify for music search, playback control, playlist management, library operations, and user profile access.

## Features

### ๐ŸŽต Search Capabilities

- **Track Search**: Find songs by title, artist, album, or lyrics
- **Artist Search**: Discover artists and explore their discography
- **Album Search**: Browse albums and compilations
- **Playlist Search**: Find public and collaborative playlists

### ๐ŸŽฎ Playback Control

- **Play/Pause**: Control music playback on any connected device
- **Track Navigation**: Skip to next/previous tracks
- **Volume Control**: Adjust playback volume (0-100%)
- **Playback Status**: Get current track and device information

### ๐Ÿ“ Playlist Management

- **Create Playlists**: Build new playlists with custom names and descriptions
- **Modify Playlists**: Add or remove tracks from existing playlists
- **List Playlists**: View user's personal and followed playlists
- **Playlist Details**: Access track listings and metadata

### ๐Ÿ“š Library Management

- **Saved Tracks**: Manage user's liked/saved music library
- **Save/Unsave**: Add or remove tracks from personal library
- **Library Browse**: Paginated access to saved music collection

### ๐Ÿ‘ค User Profile & Analytics

- **Top Tracks**: Get user's most played songs (short/medium/long term)
- **Top Artists**: Discover favorite artists over different time periods
- **Recent History**: Access recently played tracks with timestamps
- **Listening Insights**: Understand music preferences and patterns

## Quick Start

### Prerequisites

1. **Spotify Developer Account**: Create a free account at [Spotify for Developers](https://developer.spotify.com/)
2. **Spotify Application**: Register a new app to obtain Client ID and Client Secret
3. **Docker** (for containerized deployment) or **Python 3.11+** (for local development)

### Spotify App Configuration

1. Go to [Spotify Developer Dashboard](https://developer.spotify.com/dashboard/applications)
2. Click "Create an App"
3. Fill in app details:
   - **App Name**: Your app name (e.g., "My MCP Server")
   - **App Description**: Brief description of your use case
4. After creation, note your **Client ID** and **Client Secret**
5. Add redirect URI: `http://localhost:8080` (for local OAuth flow)

### Docker Deployment (Recommended)

1. **Clone and Setup**:

   ```bash
   git clone <repository-url>
   cd spotify-mcp-server

   # Copy environment template
   cp .env.example .env
   ```

2. **Configure Environment**:
   Edit `.env` file with your Spotify credentials:

   ```bash
   SPOTIFY_CLIENT_ID=your_actual_client_id
   SPOTIFY_CLIENT_SECRET=your_actual_client_secret
   ```

3. **Build and Run**:

   ```bash
   # Build the Docker image
   docker-compose build

   # Start the server
   docker-compose up -d

   # View logs
   docker-compose logs -f spotify-mcp-server
   ```

### Local Development

1. **Setup Python Environment**:

   ```bash
   # Clone repository
   git clone <repository-url>
   cd spotify-mcp-server

   # Create virtual environment
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\\Scripts\\activate

   # Install dependencies
   pip install -r requirements.txt
   ```

2. **Configure Environment Variables**:

   ```bash
   export SPOTIFY_CLIENT_ID="your_client_id"
   export SPOTIFY_CLIENT_SECRET="your_client_secret"
   ```

3. **Run Server**:

   ```bash
   # Direct execution
   python run_server.py

   # Or as module
   python -m src.server
   ```

## MCP Client Integration

### Claude Desktop Configuration

Add to your Claude Desktop configuration (`~/AppData/Roaming/Claude/config.json` on Windows or `~/Library/Application Support/Claude/config.json` on macOS):

```json
{
  "mcpServers": {
    "spotify": {
      "command": "python",
      "args": ["/path/to/spotify-mcp-server/run_server.py"],
      "env": {
        "SPOTIFY_CLIENT_ID": "your_client_id",
        "SPOTIFY_CLIENT_SECRET": "your_client_secret"
      }
    }
  }
}
```

### Docker Integration

```json
{
  "mcpServers": {
    "spotify": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "-e",
        "SPOTIFY_CLIENT_ID=your_client_id",
        "-e",
        "SPOTIFY_CLIENT_SECRET=your_client_secret",
        "spotify-mcp-server"
      ]
    }
  }
}
```

## Available Tools

### Search Tools

#### `search_tracks`

Search for music tracks

- **query** (string, required): Search terms
- **limit** (integer, optional): Results limit (1-50, default: 20)

#### `search_artists`

Find artists and bands

- **query** (string, required): Artist search terms
- **limit** (integer, optional): Results limit (1-50, default: 20)

#### `search_albums`

Discover albums and compilations

- **query** (string, required): Album search terms
- **limit** (integer, optional): Results limit (1-50, default: 20)

#### `search_playlists`

Find public playlists

- **query** (string, required): Playlist search terms
- **limit** (integer, optional): Results limit (1-50, default: 20)

### Playback Control Tools

#### `get_current_playback`

Get current playback status and track information

#### `play_music`

Start or resume playback

- **device_id** (string, optional): Target device ID
- **context_uri** (string, optional): Album/playlist URI to play
- **track_uris** (array, optional): Specific track URIs to play

#### `pause_music`

Pause current playback

- **device_id** (string, optional): Target device ID

#### `next_track`

Skip to next track

- **device_id** (string, optional): Target device ID

#### `previous_track`

Skip to previous track

- **device_id** (string, optional): Target device ID

#### `set_volume`

Control playback volume

- **volume** (integer, required): Volume percentage (0-100)
- **device_id** (string, optional): Target device ID

### Playlist Management Tools

#### `get_user_playlists`

List user's playlists

- **limit** (integer, optional): Number of playlists (1-50, default: 20)

#### `create_playlist`

Create a new playlist

- **name** (string, required): Playlist name
- **description** (string, optional): Playlist description
- **public** (boolean, optional): Public visibility (default: false)

#### `add_tracks_to_playlist`

Add tracks to a playlist

- **playlist_id** (string, required): Target playlist ID
- **track_uris** (array, required): Track URIs to add

#### `remove_tracks_from_playlist`

Remove tracks from a playlist

- **playlist_id** (string, required): Target playlist ID
- **track_uris** (array, required): Track URIs to remove

### Library Management Tools

#### `get_saved_tracks`

Get user's saved/liked tracks

- **limit** (integer, optional): Results limit (1-50, default: 20)
- **offset** (integer, optional): Pagination offset (default: 0)

#### `save_tracks`

Save tracks to user's library

- **track_ids** (array, required): Track IDs to save

#### `remove_saved_tracks`

Remove tracks from user's library

- **track_ids** (array, required): Track IDs to remove

### User Profile Tools

#### `get_top_tracks`

Get user's most played tracks

- **limit** (integer, optional): Results limit (1-50, default: 20)
- **time_range** (string, optional): Time period ("short_term", "medium_term", "long_term")

#### `get_top_artists`

Get user's favorite artists

- **limit** (integer, optional): Results limit (1-50, default: 20)
- **time_range** (string, optional): Time period ("short_term", "medium_term", "long_term")

#### `get_recently_played`

Get recently played tracks

- **limit** (integer, optional): Results limit (1-50, default: 20)

## Example Usage

### Search and Play Music

```bash
# Search for tracks
search_tracks(query="bohemian rhapsody queen")

# Play specific track
play_music(track_uris=["spotify:track:4u7EnebtmKWzUH433cf5Qv"])

# Control playback
pause_music()
next_track()
set_volume(volume=75)
```

### Playlist Management

```bash
# Create new playlist
create_playlist(name="My AI Playlist", description="Created by AI assistant")

# Add tracks to playlist
add_tracks_to_playlist(
    playlist_id="37i9dQZF1DX0XUsuxWHRQd",
    track_uris=["spotify:track:4u7EnebtmKWzUH433cf5Qv"]
)
```

### Discover User Preferences

```bash
# Get top tracks
get_top_tracks(limit=10, time_range="short_term")

# Get recent history
get_recently_played(limit=20)

# Get favorite artists
get_top_artists(limit=5, time_range="long_term")
```

## Authentication Flow

The server uses Spotify's Authorization Code Flow with PKCE for secure authentication:

1. **Initial Setup**: Server generates authorization URL
2. **User Consent**: User visits URL and grants permissions
3. **Token Exchange**: Server exchanges authorization code for access/refresh tokens
4. **Token Management**: Automatic token refresh when expired
5. **Persistent Session**: Tokens cached locally for seamless experience

### Required Spotify Scopes

The server requests these OAuth scopes for full functionality:

- `user-read-private` - User profile access
- `user-read-email` - User email (for identification)
- `user-read-playback-state` - Current playback information
- `user-modify-playback-state` - Playback control
- `user-read-currently-playing` - Now playing track
- `user-read-recently-played` - Listen history
- `user-top-read` - Top tracks and artists
- `user-library-read` - Access saved music
- `user-library-modify` - Modify saved music
- `playlist-read-private` - Private playlists
- `playlist-read-collaborative` - Collaborative playlists
- `playlist-modify-private` - Edit private playlists
- `playlist-modify-public` - Edit public playlists
- `streaming` - Playback control

## Architecture

### Component Overview

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   MCP Client    โ”‚โ”€โ”€โ”€โ”€โ”‚  Spotify MCP     โ”‚โ”€โ”€โ”€โ”€โ”‚  Spotify Web    โ”‚
โ”‚   (Claude AI)   โ”‚    โ”‚     Server       โ”‚    โ”‚      API        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”
                         โ”‚   Tools &   โ”‚
                         โ”‚ Capabilitiesโ”‚
                         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Key Components

- **`server.py`**: Main MCP server implementation with stdio transport
- **`spotify_client.py`**: Spotify Web API wrapper with OAuth2 authentication
- **`tools.py`**: MCP tool definitions and request handlers
- **`run_server.py`**: Entry point script for easy execution

### Error Handling

- **Authentication Errors**: Graceful handling of expired/invalid tokens
- **API Rate Limits**: Automatic retry with exponential backoff
- **Network Issues**: Robust error reporting and recovery
- **Invalid Requests**: Comprehensive input validation and error messages

## Troubleshooting

### Common Issues

#### Authentication Problems

```bash
# Error: "Authentication failed"
# Solution: Check credentials and redirect URI
export SPOTIFY_CLIENT_ID="correct_client_id"
export SPOTIFY_CLIENT_SECRET="correct_client_secret"
```

#### Permission Errors

```bash
# Error: "Insufficient scope"
# Solution: Ensure all required scopes are approved
# Check your Spotify app settings and re-authenticate
```

#### Playback Issues

```bash
# Error: "No active device"
# Solution: Start Spotify on any device before controlling playback
# The device must be active for remote control
```

### Debug Mode

Enable verbose logging:

```bash
# Set environment variable
export LOG_LEVEL=DEBUG

# Or modify server.py logging level
logging.basicConfig(level=logging.DEBUG)
```

### Docker Troubleshooting

```bash
# Check container logs
docker-compose logs spotify-mcp-server

# Interactive container debugging
docker-compose exec spotify-mcp-server bash

# Rebuild after changes
docker-compose build --no-cache
```

## Development

### Local Development Setup

1. **Install Development Dependencies**:

   ```bash
   pip install -r requirements.txt
   pip install pytest black flake8 mypy
   ```

2. **Run Tests**:

   ```bash
   pytest tests/
   ```

3. **Code Formatting**:
   ```bash
   black src/
   flake8 src/
   mypy src/
   ```

### Project Structure

```
spotify-mcp-server/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ server.py          # Main MCP server
โ”‚   โ”œโ”€โ”€ spotify_client.py  # Spotify API wrapper
โ”‚   โ””โ”€โ”€ tools.py          # MCP tool definitions
โ”œโ”€โ”€ tests/                # Test suite
โ”œโ”€โ”€ requirements.txt      # Python dependencies
โ”œโ”€โ”€ Dockerfile           # Container definition
โ”œโ”€โ”€ docker-compose.yml   # Container orchestration
โ”œโ”€โ”€ run_server.py       # Entry point script
โ”œโ”€โ”€ .env.example        # Environment template
โ””โ”€โ”€ README.md          # Documentation
```

## Security Considerations

- **Credentials**: Never commit API keys to version control
- **Token Storage**: Tokens are cached locally - secure your environment
- **Network**: Use HTTPS in production environments
- **Permissions**: Request minimal necessary OAuth scopes
- **Container Security**: Run as non-root user in Docker

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Acknowledgments

- [Spotify Web API](https://developer.spotify.com/documentation/web-api/) for comprehensive music data access
- [Spotipy](https://spotipy.readthedocs.io/) for Python Spotify API integration
- [Model Context Protocol](https://modelcontextprotocol.io/) for standardized AI tool integration
- [Anthropic](https://www.anthropic.com/) for MCP development and Claude integration

---

**Happy Music Discovery! ๐ŸŽต**

For support and questions, please open an issue in the repository or consult the Spotify Developer documentation.

Maintenance

ActivityInactive
ResponsivenessNo issues