Skip to main content
Glama
thejaredchapman

spotify-direct-mcp

README.md
# spotify-direct-mcp

A [FastMCP](https://github.com/jlowin/fastmcp) server that exposes Spotify as a set of tools for Claude.

Ask Claude things like:
- *"What's the full discography of Sade?"*
- *"What key and BPM is 'Isn't She Lovely' in?"*
- *"Recommend 20 tracks with the same vibe as Stevie Wonder — high energy, soulful"*
- *"What am I listening to right now?"*
- *"Create a private playlist called 'Late Night Drive' from those recommendations"*

---

## Tools

| Tool | Description | Auth required |
|------|-------------|---------------|
| `search_tracks` | Search the Spotify catalog | No |
| `get_track_details` | Audio features (BPM, key, energy, danceability) + metadata | No |
| `get_artist_discography` | Full album/track list for an artist | No |
| `get_recommendations` | Mood/seed-based track recommendations | No |
| `get_currently_playing` | What's playing on your account right now | **Yes** |
| `create_playlist` | Create a playlist in your account | **Yes** |

> **Note:** As of late 2024, Spotify restricts the `audio-features` and `recommendations`
> endpoints to apps approved for "Extended Quota Mode". If your app doesn't have that
> approval, `get_track_details` will still return track metadata but `audio_features`
> will contain an explanatory message instead of BPM/key data, and
> `get_recommendations` will return an `error` field with the same explanation. Request
> access at https://developer.spotify.com/documentation/web-api/concepts/quota-modes.

---

## Prerequisites

- **Python 3.10+** (required by FastMCP and the underlying MCP SDK — see below if you're not sure what you have)
- A Spotify account (free or premium)
- A Spotify Developer app ([developer.spotify.com/dashboard](https://developer.spotify.com/dashboard))

### Checking your Python version

```bash
python3 --version
```

If this prints `3.10.x`, `3.11.x`, `3.12.x`, or `3.13.x`, you're good — skip to Step 1.

If it prints `3.9.x` or lower (common on macOS, which ships an old system Python),
you need to install a newer Python **before** creating the virtual environment in
Step 2. `pip install -r requirements.txt` will fail with
`Could not find a version that satisfies the requirement fastmcp>=2.0` if you try to
use Python 3.9 or earlier.

#### Installing Python 3.10+

**macOS (Homebrew):**
```bash
brew install python@3.12
```
This installs a separate `python3.12` binary alongside your system Python — it won't
replace or break anything else. Verify with:
```bash
python3.12 --version
```

**macOS (no Homebrew):** Download the installer from
[python.org/downloads](https://www.python.org/downloads/) and run it. After
installing, use `python3.12` (or whichever version you installed) in place of
`python3` below.

**Windows:** Download the installer from
[python.org/downloads](https://www.python.org/downloads/), run it, and check
**"Add python.exe to PATH"** during install. Verify with:
```powershell
python --version
```

**Linux (Debian/Ubuntu):**
```bash
sudo apt update
sudo apt install python3.12 python3.12-venv
```

**Using pyenv (any OS, if you manage multiple Python versions):**
```bash
pyenv install 3.12.7
pyenv local 3.12.7   # sets this version for the spotify-direct-mcp directory
```

Once you have a 3.10+ interpreter available, use **that** binary (e.g. `python3.12`)
instead of `python3` when creating the virtual environment in Step 2.

---

## Step 1: Spotify Developer Setup

1. Go to [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard)
2. Click **Create app**
3. Fill in:
   - App name: `spotify-direct-mcp`
   - App description: anything
   - Redirect URI: `http://localhost:8888/callback`
   - Check: **Web API**
4. Click **Save**
5. Copy your **Client ID** and **Client Secret** from the app settings

---

## Step 2: Local Setup

```bash
# Clone or copy the project
cd spotify-direct-mcp

# Create virtual environment using Python 3.10+
# If `python3 --version` showed 3.10+, use python3 below.
# Otherwise, substitute the 3.10+ binary you installed above (e.g. python3.12).
python3 -m venv .venv
source .venv/bin/activate        # Mac/Linux
# .venv\Scripts\activate         # Windows

# Confirm the venv is using Python 3.10+
python --version

# Install dependencies
pip install -r requirements.txt

# Copy env template and fill in your credentials
cp .env.example .env
```

If `pip install -r requirements.txt` fails with
`Could not find a version that satisfies the requirement fastmcp>=2.0`, your venv was
created with Python <3.10. Delete it and recreate using a 3.10+ binary:

```bash
rm -rf .venv
python3.12 -m venv .venv   # use whichever 3.10+ binary you installed
source .venv/bin/activate
pip install -r requirements.txt
```

Edit `.env`:
```env
SPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_client_secret_here
SPOTIFY_REDIRECT_URI=http://localhost:8888/callback
```

---

## Step 3: OAuth Setup (one-time)

Tools that access your personal account (`get_currently_playing`, `create_playlist`) require
a one-time OAuth authorization:

```bash
python oauth_setup.py
```

This will:
1. Open a browser window to Spotify's auth page
2. Ask you to authorize the app
3. Redirect you to `localhost:8888/callback` (the page won't load — that's fine)
4. Ask you to paste the full redirect URL
5. Cache your token to `.spotify_cache`

You only need to do this once. The token auto-refreshes.

---

## Step 4: Run Locally

### Option A: stdio (for Claude Desktop)
```bash
python server.py
# or explicitly:
python server.py stdio
```

### Option B: SSE (for Railway / remote clients)
```bash
python server.py sse
# Server starts on http://localhost:8000
```

---

## Step 5: Connect to Claude Desktop

Add this to your Claude Desktop config file:

**Mac:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "spotify-direct-mcp": {
      "command": "/absolute/path/to/.venv/bin/python",
      "args": ["/absolute/path/to/spotify-direct-mcp/server.py"],
      "env": {
        "SPOTIFY_CLIENT_ID": "your_client_id_here",
        "SPOTIFY_CLIENT_SECRET": "your_client_secret_here",
        "SPOTIFY_REDIRECT_URI": "http://localhost:8888/callback"
      }
    }
  }
}
```

Replace `/absolute/path/to/` with your actual paths.

Restart Claude Desktop after saving. You should see `spotify-direct-mcp` in the tools list.

---

## Step 6: Deploy to Railway

### First-time setup
```bash
# Install Railway CLI
npm install -g @railway/cli

# Login
railway login

# Initialize project
railway init

# Set environment variables
railway variables set SPOTIFY_CLIENT_ID=your_client_id_here
railway variables set SPOTIFY_CLIENT_SECRET=your_client_secret_here
railway variables set SPOTIFY_REDIRECT_URI=https://your-app.railway.app/callback
```

### Update Redirect URI on Spotify
Before deploying, add your Railway URL as an allowed redirect URI in your Spotify app settings:
1. Go to [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard)
2. Click your app → Edit Settings
3. Add `https://your-app.railway.app/callback` to Redirect URIs
4. Save

### Deploy
```bash
railway up
```

Railway reads `railway.toml` and automatically:
- Detects Python via Nixpacks
- Installs `requirements.txt`
- Runs `python server.py sse`
- Sets `PORT` environment variable

### Get your deployed URL
```bash
railway domain
# Returns something like: https://spotify-direct-mcp-production.up.railway.app
```

### Connect Claude to your Railway deployment
Once deployed, your MCP server is accessible via SSE at:
```
https://your-app.railway.app/sse
```

Add this to your Claude Desktop config:
```json
{
  "mcpServers": {
    "spotify-direct-mcp": {
      "url": "https://your-app.railway.app/sse"
    }
  }
}
```

---

## Important: OAuth on Railway

`get_currently_playing` and `create_playlist` require an OAuth token tied to your Spotify account.

The `.spotify_cache` file generated locally is not automatically available on Railway. You have two options:

**Option A (Recommended for personal use):** Complete OAuth locally, then set the token contents as a Railway environment variable:

```bash
# After running oauth_setup.py locally:
cat .spotify_cache

# Copy the JSON output, then:
railway variables set SPOTIFY_TOKEN_CACHE='{"access_token": "...", ...}'
```

Then update `server.py` to read from this env var if the cache file doesn't exist — or simply use the server for catalog tools only (search, details, discography, recommendations) which don't need user auth.

**Option B:** Use a token refresh endpoint pattern (more complex, not scaffolded here).

For the interview demo, Option A or catalog-only is perfectly sufficient.

---

## Project Structure

```
spotify-direct-mcp/
├── server.py          # FastMCP server — all tools live here
├── oauth_setup.py     # One-time OAuth flow helper
├── requirements.txt   # Python dependencies
├── railway.toml       # Railway deployment config
├── .env.example       # Environment variable template
├── .env               # Your actual credentials (gitignored)
├── .spotify_cache     # OAuth token cache (gitignored)
└── README.md          # This file
```

---

## Example Prompts for Claude

Once connected, try these:

```
Search for "Isn't She Lovely" and give me the BPM and musical key.

What's Sade's full discography sorted by year?

Recommend 15 tracks similar to Anita Ward with high danceability and moderate energy.

What am I currently listening to? What key is it in?

Create a private playlist called "Sunday Morning Soul" from these track URIs: [paste URIs]

Search for top tracks by Stevie Wonder from the 1970s.
```

---

## Architecture Notes

- **Client Credentials flow** is used for all catalog tools (no user login required)
- **OAuth PKCE flow** is used for user-context tools (currently playing, create playlist)
- FastMCP handles the MCP protocol — all tools are decorated with `@mcp.tool()`
- Transport is switchable: `stdio` for local/Claude Desktop, `sse` for Railway/remote
- Railway auto-detects Python via Nixpacks — no Dockerfile needed

---

## Built With

- [FastMCP](https://github.com/jlowin/fastmcp) — MCP server framework
- [Spotipy](https://spotipy.readthedocs.io/) — Spotify Web API client
- [Railway](https://railway.app) — deployment platform