jadilson12/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 henry@mcphub.com.
Spotipy MCP Server integrates Spotify music control with Model Context Protocol (MCP) for enhanced music management.
Spotipy MCP Server
MCP (Model Context Protocol) Server with Spotipy integration for music control via Spotify.
๐ Features
- โ Playback control (play, pause, next, previous)
- โ Volume adjustment
- โ Music search
- โ Get current track
- โ Playlist management
- โ Complete REST API
- โ Automatic documentation (Swagger)
- โ Complete MCP integration with tools and resources
๐ Prerequisites
- Python 3.12+
- Spotify Developer account
- Registered application in Spotify Developer Dashboard
๐ ๏ธ Installation
- Clone the repository:
git clone https://github.com/jadilson12/spotify-mcp-server
cd spotify-mcp-server
- Install dependencies:
make install
- Configure environment variables:
cp env.example .env
Edit the .env
file with your Spotify credentials:
SPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_client_secret_here
SPOTIFY_REDIRECT_URI=http://localhost:8888/callback
๐ต Spotify Configuration
๐ Step-by-Step Tutorial: Getting Spotify Credentials
Step 1: Access Spotify Developer Dashboard
- Go to Spotify Developer Dashboard
- Log in with your Spotify account (or create one if you don't have it)
Step 2: Create a New Application
- Click "Create App" button
- Fill in the application details:
- App name:
Spotify MCP Server
(or any name you prefer) - App description:
MCP Server for Spotify music control
- Website:
http://localhost:8000
(optional) - Redirect URI:
http://localhost:8888/callback
- API/SDKs: Select "Web API"
- App name:
- Click "Save"
Step 3: Get Your Credentials
- After creating the app, you'll be redirected to your app dashboard
- Copy the Client ID (visible on the main page)
- Click "Show Client Secret" and copy the Client Secret
- โ ๏ธ Keep these credentials secure! Never share them publicly.
Step 4: Configure Redirect URIs
- In your app dashboard, go to "Edit Settings"
- Under "Redirect URIs", add:
http://localhost:8888/callback
- Click "Add" and then "Save"
Step 5: Configure Required Scopes
- In your app dashboard, go to "Edit Settings"
- Under "User Management", you'll see the scopes section
- Important: The following scopes will be requested during authentication:
user-read-playback-state
- Read playback stateuser-modify-playback-state
- Control playbackuser-read-currently-playing
- Current trackplaylist-read-private
- Private playlistsuser-library-read
- User libraryuser-top-read
- Top artists and tracksuser-read-recently-played
- Recently played tracksuser-follow-read
- Followed artistsuser-read-email
- User emailuser-read-private
- Private information
Step 6: Update Your .env File
- Copy the
env.example
file to.env
- Replace the placeholder values with your actual credentials:
SPOTIFY_CLIENT_ID=your_actual_client_id_here
SPOTIFY_CLIENT_SECRET=your_actual_client_secret_here
SPOTIFY_REDIRECT_URI=http://localhost:8888/callback
Step 7: Test Your Configuration
- Start the server:
make dev
- The first time you use the API, you'll be redirected to Spotify for authentication
- Accept the permissions requested by Spotify
- You should now be able to control your Spotify music!
๐ Security Tips
- Never commit your
.env
file to version control - Keep your credentials private and secure
- Use different apps for development and production
- Regularly rotate your client secret if needed
๐ Usage
Start the server:
make dev
The server will be available at:
- API: http://localhost:8000
- Documentation: http://localhost:8000/docs
- Health Check: http://localhost:8000/health
๐ ๏ธ Development Guide
๐ Essential Commands
# Complete server restart
pkill -f "python.*mcp-server" && sleep 2 && make dev
# Kill MCP ports (REQUIRED before run-inspector)
lsof -ti:6274 | xargs kill -9 && lsof -ti:6277 | xargs kill -9
# Check ports in use
lsof -i:6274 && lsof -i:6277
โ ๏ธ IMPORTANT: Always Kill Ports!
BEFORE running make run-inspector
, ALWAYS execute:
# Kill MCP ports (REQUIRED)
lsof -ti:6274 | xargs kill -9 && lsof -ti:6277 | xargs kill -9
Why is this necessary?
- MCP Inspector uses ports 6274 (UI) and 6277 (Proxy)
- If ports are occupied, Inspector cannot start
- Previous processes may have left ports in use
๐ฏ Development Workflow
- After Modifying Code:
pkill -f "python.*mcp-server" && sleep 2 && make dev
- To Test with MCP Inspector:
lsof -ti:6274 | xargs kill -9 && lsof -ti:6277 | xargs kill -9
make run-inspector
Available commands:
make dev # Start development server
make install # Install dependencies
make clean # Clean temporary files
make test # Run tests
make lint # Check code quality
make format # Format code
make run-inspector # Run MCP Inspector
make help # Show help
๐ต MCP Features
Available Tools:
play_music
- Play musicsearch_tracks
- Search tracksget_current_track
- Current trackget_playlists
- List playlistsget_recommendations
- Recommendationsget_user_profile
- User profileget_devices
- Available devicesget_queue
- Playback queueget_genres
- Music genresget_audio_features
- Audio characteristics
Available Resources:
spotify://playback/current
- Current playbackspotify://playlists
- User playlistsspotify://devices
- Devicesspotify://genres
- Genresspotify://profile
- User profilespotify://playback/queue
- Playback queue
Resource Templates:
spotify://playlist/{playlist_id}
- Specific playlistspotify://track/{track_id}
- Specific trackspotify://artist/{artist_id}
- Specific artistspotify://album/{album_id}
- Specific albumspotify://search/{query}
- Search results
๐ API Endpoints
Authentication
POST /auth
- Authenticate with SpotifyPOST /auth/reauth
- Re-authenticate with configured credentials
Playback
GET /current-track
- Get current trackPOST /play
- Play musicPOST /pause
- Pause musicPOST /next
- Next trackPOST /previous
- Previous trackPOST /volume/{volume}
- Adjust volume (0-100)POST /seek/{position_ms}
- Seek to specific positionPOST /shuffle
- Toggle shuffle modePOST /repeat
- Toggle repeat mode
Playlists and Albums
GET /playlists
- Get user playlistsGET /playlist/{playlist_id}
- Get playlist tracksGET /albums
- Get user saved albumsGET /tracks
- Get user saved tracks
Artists and Top Tracks
GET /artists
- Get user favorite artistsGET /tracks/top
- Get most played tracks
Playback Queue
GET /queue
- Get current playback queuePOST /queue/add
- Add track to queue
Devices
GET /devices
- Get available devicesPOST /devices/{device_id}/transfer
- Transfer playback
Search and Recommendations
GET /search/{query}
- Search tracksGET /recommendations
- Get personalized recommendationsGET /genres
- Get available music genres
User and Analysis
GET /user/profile
- Get user profileGET /audio-features/{track_id}
- Get audio features
System
GET /
- Server statusGET /health
- Health check
๐ง Usage Examples
Play a specific track:
curl -X POST "http://localhost:8000/play" \
-H "Content-Type: application/json" \
-d '{"track_uri": "spotify:track:4iV5W9uYEdYUVa79Axb7Rh"}'
Search tracks:
curl "http://localhost:8000/search/bohemian%20rhapsody?limit=5"
Adjust volume:
curl -X POST "http://localhost:8000/volume/50"
Get current track:
curl "http://localhost:8000/current-track"
Get user playlists:
curl "http://localhost:8000/playlists"
Get tracks from a specific playlist:
curl "http://localhost:8000/playlist/37i9dQZF1DXcBWIGoYBM5M"
Get saved tracks:
curl "http://localhost:8000/tracks"
Get favorite artists:
curl "http://localhost:8000/artists"
Get recommendations based on artists:
curl "http://localhost:8000/recommendations?seed_artists=4gzpq5DPGxSnKTe4SA8HAU&limit=10"
Toggle shuffle:
curl -X POST "http://localhost:8000/shuffle"
Add track to queue:
curl -X POST "http://localhost:8000/queue/add?track_uri=spotify:track:4iV5W9uYEdYUVa79Axb7Rh"
Get available devices:
curl "http://localhost:8000/devices"
Seek to specific position (30 seconds):
curl -X POST "http://localhost:8000/seek/30000"
Re-authenticate with Spotify:
curl -X POST "http://localhost:8000/auth/reauth"
๐ CI/CD Pipeline
๐ Pipeline Status
Our CI/CD pipeline ensures code quality and security:
- โ Tests: 60 tests passing on Python 3.12 & 3.13
- โ Linting: Code quality checks with flake8
- โ Formatting: Black and isort formatting validation
- โ Security: Secrets detection and .env file validation
- โ Build: Package building and artifact generation
๐ Pipeline Jobs
Job | Description | Status |
---|---|---|
Test | Run all tests on Python 3.12 & 3.13 | |
Lint | Code quality and formatting checks | |
Security | Secrets detection and security validation | |
Build | Package building and distribution |
๐ก๏ธ Security Checks
The pipeline includes comprehensive security validation:
- ๐ TruffleHog: Advanced secret scanner for detecting credentials
- ๐ต๏ธ detect-secrets: Multi-pattern secret detection with baseline
- ๐ Pattern Matching: Custom regex patterns for sensitive data
- ๐ File Validation: Checks for committed sensitive files (.env, .key, .pem)
- โ๏ธ Gitignore Validation: Ensures sensitive file patterns are ignored
- ๐ URL Scanning: Detects hardcoded cloud service URLs
- ๐ Security Reports: Generates detailed security scan artifacts
Protected Patterns:
- API keys and tokens
- Passwords and secrets
- Base64/Hex encoded strings
- AWS, Google, Azure credentials
- Private keys and certificates
- Spotify client credentials
๐ Local Pipeline Testing
Test the pipeline locally before pushing:
# Run all pipeline checks locally
make test-pytest # Tests
make lint # Linting
make format # Formatting
make security # Security checks
๐ Security Commands
# Run security checks
make security # Basic security validation
# Full security scan (requires tools)
pip install detect-secrets truffleHog3
detect-secrets scan --all-files
trufflehog3 --format json .
๐งช Tests
โ 60 tests PASSING | โฑ๏ธ ~0.38s | ๐ง 100% Functional
๐ Run Tests
# Run all tests (recommended)
make test-pytest
# Or use pytest directly
python -m pytest tests/ -v --tb=short --color=yes
๐ Test Coverage
๐ง MCP Tools Tests (36 tests)
- โ
Playback control (
play_music
,pause_music
,next_track
,previous_track
) - โ
Volume management (
set_volume
) - โ
Search and discovery (
search_tracks
,search_artists
,search_albums
,search_playlists
) - โ
Playlists and albums (
get_playlists
,get_playlist_tracks
,get_album_tracks
) - โ
Profile and preferences (
get_user_profile
,get_top_tracks
,get_top_artists
) - โ
Personal library (
get_saved_tracks
,get_saved_albums
,get_followed_artists
) - โ
Devices and queue (
get_devices
,get_queue
,add_to_queue
) - โ
Recommendations (
get_recommendations
,get_genres
,get_audio_features
) - โ
Navigation (
skip_to_next
,skip_to_previous
,seek_to_position
) - โ
History (
get_recently_played
) - โ
Related artists (
get_related_artists
,get_artist_top_tracks
,get_artist_albums
)
๐ฌ MCP Prompts Tests (6 tests)
- โ
spotify_assistant
- Intelligent music assistant - โ
spotify_usage_guide
- Feature usage guide - โ
spotify_troubleshooting
- Problem solving
๐ MCP Resources Tests (12 tests)
- โ
spotify://playback/current
- Current playback state - โ
spotify://playlists/user
- User playlists - โ
spotify://devices/available
- Available devices - โ
spotify://genres/available
- Music genres - โ
spotify://user/profile
- User profile - โ
spotify://playback/queue
- Playback queue - โ
spotify://user/top-tracks
- Top tracks - โ
spotify://user/top-artists
- Top artists - โ
spotify://user/recently-played
- Recently played - โ
spotify://user/saved-tracks
- Saved tracks - โ
spotify://user/saved-albums
- Saved albums - โ
spotify://user/followed-artists
- Followed artists
๐ง Functionality Tests (3 tests)
- โ Correct tool structure
- โ Valid descriptions in all tools
- โ Error handling implemented
๐ Validation Tests (2 tests)
- โ Volume request validation
- โ Search request validation
๐ Integration Test (1 test)
- โ Server completeness (tools, prompts, resources)
๐ฏ Available Test Commands
# Run all tests
make test-pytest # Using pytest (recommended)
# Specific tests (future)
make test-tools # Tools tests only
make test-prompts # Prompts tests only
make test-resources # Resources tests only
make test-integration # Integration tests only
make test-coverage # Check coverage
# Test with detailed output
python -m pytest tests/ -v -s --tb=long
๐ Latest Test Results
===================================== test session starts =====================================
collected 60 items
TestMCPServerBasics โ
(4/4)
TestMCPTools โ
(36/36)
TestMCPPrompts โ
(6/6)
TestMCPResources โ
(12/12)
TestToolFunctionality โ
(2/2)
TestErrorHandling โ
(1/1)
TestDataValidation โ
(2/2)
TestIntegration โ
(1/1)
===================================== 60 passed in 0.38s ======================================
๐ Test Structure
tests/
โโโ test_main.py # All MCP server tests
โโโ __init__.py # Module initialization
โโโ README.md # Test documentation
๐งช How to Add New Tests
- For new tool:
@pytest.mark.asyncio
async def test_new_tool_exists(self):
"""Test if new tool exists"""
tools = await app.get_tools()
assert 'new_tool' in tools
- For new resource:
@pytest.mark.asyncio
async def test_new_resource_exists(self):
"""Test if new resource exists"""
resources = await app.get_resources()
assert 'spotify://new/resource' in resources
โ ๏ธ Important for Tests
- ALWAYS run tests after modifying code
- Use
make test-pytest
for fast and reliable execution - Tests don't require real Spotify authentication
- Tests focus on structure and feature availability
๐ Linting and Formatting
make lint # Check code quality
make format # Format code automatically
๐ Project Structure
mcp-server/
โโโ src/
โ โโโ mcp-server.py # Main MCP server
โ โโโ service.py # Spotify logic
โ โโโ server.py # FastAPI server
โ โโโ config.py # Configuration
โโโ tests/ # Tests
โโโ makefile # Development commands
โโโ pyproject.toml # Project configuration
โโโ env.example # Environment variables example
โโโ README.md # This file
โ ๏ธ Common Issues
Error: "PORT IS IN USE"
# Quick solution
lsof -ti:6274 | xargs kill -9
lsof -ti:6277 | xargs kill -9
Error: "ModuleNotFoundError"
# Reinstall dependencies
make install
Server not responding
# Complete restart
pkill -f "python.*mcp-server" && sleep 2 && make dev
Error 403 - Insufficient Permission
If you receive error 403 with message "Insufficient client scope":
- Verify all required scopes are configured
- Re-authenticate with Spotify using
/auth
endpoint - Make sure you accepted all requested permissions
Endpoints Requiring Specific Permissions
/artists
and/tracks/top
- Requireuser-top-read
/recommendations
- Require at least one valid seed/user/profile
- Requireuser-read-email
anduser-read-private
Known Issues
- Recommendations (404): The recommendations API may return 404 in some cases. This can be due to:
- Temporary Spotify API issues
- Invalid or not found seeds
- Authentication problems
- Solution: Use
/auth/reauth
endpoint to re-authenticate if necessary
๐ง Important Tips
- ALWAYS restart server after modifying
mcp-server.py
- ALWAYS kill ports before running Inspector (6274 and 6277)
- ALWAYS verify ports are free before running
make run-inspector
- Check logs to identify problems
- Use
make dev
for local development - Keep
.env
properly configured
๐ค Contributing
We welcome contributions! Please follow these steps:
๐ Development Workflow
- Fork the project
- Create a feature branch:
git checkout -b feature/AmazingFeature
- Make your changes and test locally:
make test-pytest # Run tests make lint # Check code quality make format # Format code
- Commit your changes:
git commit -m 'Add some AmazingFeature'
- Push to your branch:
git push origin feature/AmazingFeature
- Open a Pull Request
โ CI/CD Requirements
All contributions must pass our CI/CD pipeline:
- Tests: All 60 tests must pass
- Linting: Code must pass flake8 checks
- Formatting: Code must be properly formatted with Black
- Security: No secrets or sensitive files committed
- Build: Package must build successfully
๐ก๏ธ Security Guidelines
- Never commit
.env
files or credentials - Use placeholders in examples (e.g.,
your_client_id_here
) - Follow the security checklist in
SECURITY.md
- Test locally before pushing
๐ Code Quality Standards
- Python 3.12+ compatibility
- Type hints for all functions
- Docstrings for all public functions
- Error handling for all external API calls
- Tests for new functionality
๐ License
This project is under MIT license. See the LICENSE
file for more details.
๐ Support
If you encounter any problems or have questions:
- Check if Spotify credentials are correct
- Make sure Spotify is running on some device
- Check server logs for more details
- Open an issue in the repository
๐ Useful Links
๐ต Music is life! Let's make an amazing MCP server! ๐