Spotify MCP Server

Spotify MCP Server

Enables AI assistants to control Spotify playback, search music, manage playlists and library, and access user listening insights via the Spotify Web API.

Category
访问服务器

README

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
  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
  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:

    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:

    SPOTIFY_CLIENT_ID=your_actual_client_id
    SPOTIFY_CLIENT_SECRET=your_actual_client_secret
    
  3. 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

  1. 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
    
  2. Configure Environment Variables:

    export SPOTIFY_CLIENT_ID="your_client_id"
    export SPOTIFY_CLIENT_SECRET="your_client_secret"
    
  3. 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:

  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

# 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

  1. Install Development Dependencies:

    pip install -r requirements.txt
    pip install pytest black flake8 mypy
    
  2. Run Tests:

    pytest tests/
    
  3. 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

  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


Happy Music Discovery! 🎵

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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选