raulpetruta/spotify-mcp-server
If you are the rightful owner of spotify-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
A comprehensive Model Context Protocol (MCP) server that provides seamless integration with Spotify's Web API.
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
- Spotify Developer Account: Create a free account at Spotify for Developers
- Spotify Application: Register a new app to obtain Client ID and Client Secret
- Docker (for containerized deployment) or Python 3.11+ (for local development)
Spotify App Configuration
- Go to Spotify Developer Dashboard
- Click "Create an App"
- Fill in app details:
- App Name: Your app name (e.g., "My MCP Server")
- App Description: Brief description of your use case
- After creation, note your Client ID and Client Secret
- Add redirect URI:
http://localhost:8080(for local OAuth flow)
Docker Deployment (Recommended)
-
Clone and Setup:
git clone <repository-url> cd spotify-mcp-server # Copy environment template cp .env.example .env -
Configure Environment: Edit
.envfile with your Spotify credentials:SPOTIFY_CLIENT_ID=your_actual_client_id SPOTIFY_CLIENT_SECRET=your_actual_client_secret -
Build and Run:
# 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
-
Setup Python Environment:
# 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 -
Configure Environment Variables:
export SPOTIFY_CLIENT_ID="your_client_id" export SPOTIFY_CLIENT_SECRET="your_client_secret" -
Run Server:
# 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):
{
"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
{
"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
# 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
# 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
# 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:
- Initial Setup: Server generates authorization URL
- User Consent: User visits URL and grants permissions
- Token Exchange: Server exchanges authorization code for access/refresh tokens
- Token Management: Automatic token refresh when expired
- 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 accessuser-read-email- User email (for identification)user-read-playback-state- Current playback informationuser-modify-playback-state- Playback controluser-read-currently-playing- Now playing trackuser-read-recently-played- Listen historyuser-top-read- Top tracks and artistsuser-library-read- Access saved musicuser-library-modify- Modify saved musicplaylist-read-private- Private playlistsplaylist-read-collaborative- Collaborative playlistsplaylist-modify-private- Edit private playlistsplaylist-modify-public- Edit public playlistsstreaming- 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 transportspotify_client.py: Spotify Web API wrapper with OAuth2 authenticationtools.py: MCP tool definitions and request handlersrun_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
# 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
# Error: "Insufficient scope"
# Solution: Ensure all required scopes are approved
# Check your Spotify app settings and re-authenticate
Playback Issues
# 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:
# Set environment variable
export LOG_LEVEL=DEBUG
# Or modify server.py logging level
logging.basicConfig(level=logging.DEBUG)
Docker Troubleshooting
# 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
-
Install Development Dependencies:
pip install -r requirements.txt pip install pytest black flake8 mypy -
Run Tests:
pytest tests/ -
Code Formatting:
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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Spotify Web API for comprehensive music data access
- Spotipy for Python Spotify API integration
- Model Context Protocol for standardized AI tool integration
- Anthropic 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.