Skip to content
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ All settings come from environment variables; see [`.env.example`](.env.example)

- **The MCP endpoint has no authentication of its own.** Anyone who can reach port 8000 can control the connected account's playback. Run it behind a gateway that checks API keys or OAuth (e.g. [agentgateway](https://agentgateway.dev)), and restrict the port (the chart has an optional NetworkPolicy).
- **Least privilege at Spotify:** the server asks only for `user-read-playback-state`, `user-modify-playback-state` and `user-read-currently-playing`. It can't read playlists, the library or the e-mail address.
- **Tokens:** the refresh token lives in `DATA_DIR/tokens/<profile>.json` with mode 0600. When Spotify rotates it, the new one is written before it's used, so restarts keep working. Nothing is logged.
- **Tokens:** the refresh token lives in `DATA_DIR/tokens/<profile>.json` with mode 0600. A refresh reads, refreshes and writes the token under one lock (a mutex plus `flock`, which also covers the `invite` command's process), so a rotated refresh token is on disk before it's used and a login during a refresh is never overwritten. Nothing is logged.
- **Invites** are 256-bit random codes. Only their SHA-256 is stored; each works once and expires.
- **Login:** OAuth authorization code flow with PKCE and a `state` tied to the browser by a cookie, so a leaked callback URL can't be replayed in another browser. Cross-site form posts are rejected, and pages send no `Referer`.
- **Container:** static binary on `scratch`, non-root, read-only root filesystem, no capabilities, no Kubernetes API token.
Expand All @@ -106,6 +106,22 @@ Found a security problem? Please open a private security advisory on GitHub rath

## Development

The code is layered so the rules can be tested without HTTP, files or Spotify:

```mermaid
flowchart LR
main["cmd/spotify-mcp (wiring)"] --> mcpserver & web & config
mcpserver -- "Player interface" --> playback
web -- "Connector interface" --> account
playback -- "Spotify port" --> spotify
account -- "Tokens / Invites ports" --> filestore
account -- "OAuth / Identity ports" --> spotify
```

- `internal/playback` and `internal/account` are the domain: each has a `Service` with the use cases, the rules, and the ports (interfaces) it needs. Values and entities (`URI`, `DeviceID`, `ProfileID`, `InviteCode`, `Token`, …) are exported interfaces with unexported implementations, created only through constructors that validate (`ParseX`, `NewX`, `RestoreX` for stored data). The time comes from an injected `Clock`.
- `internal/spotify` (Web API + OAuth) and `internal/filestore` (JSON files) implement the ports. Wire and file formats stay unexported in them.
- `internal/mcpserver` and `internal/web` are the transports. Each depends on a small interface it defines itself.

```bash
go test -race ./...
go vet ./...
Expand Down
174 changes: 67 additions & 107 deletions cmd/spotify-mcp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//
// spotify-mcp [serve] run the MCP server and the connect page
// spotify-mcp invite [-ttl] print a one-time link that connects an account
// spotify-mcp version
package main

import (
Expand All @@ -14,89 +15,30 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"

"github.com/modelcontextprotocol/go-sdk/mcp"
"golang.org/x/oauth2"

"github.com/subpathdev/spotify-mcp/internal/account"
"github.com/subpathdev/spotify-mcp/internal/config"
"github.com/subpathdev/spotify-mcp/internal/filestore"
"github.com/subpathdev/spotify-mcp/internal/mcpserver"
"github.com/subpathdev/spotify-mcp/internal/playback"
"github.com/subpathdev/spotify-mcp/internal/spotify"
"github.com/subpathdev/spotify-mcp/internal/store"
"github.com/subpathdev/spotify-mcp/internal/tools"
"github.com/subpathdev/spotify-mcp/internal/web"
)

// version is set at build time.
var version = "dev"

type config struct {
clientID string
clientSecret string
redirectURI string
publicURL string
dataDir string
profile string
mcpAddr string
webAddr string
}

func env(key, def string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return def
}

func loadConfig(needSecrets bool) (config, error) {
c := config{
clientID: env("SPOTIFY_CLIENT_ID", ""),
clientSecret: env("SPOTIFY_CLIENT_SECRET", ""),
redirectURI: env("SPOTIFY_REDIRECT_URI", ""),
publicURL: env("PUBLIC_URL", ""),
dataDir: env("DATA_DIR", "/data"),
profile: env("PROFILE", "default"),
mcpAddr: env("MCP_ADDR", ":8000"),
webAddr: env("WEB_ADDR", ":8080"),
}
var missing []string
if c.redirectURI == "" {
missing = append(missing, "SPOTIFY_REDIRECT_URI")
}
if needSecrets {
if c.clientID == "" {
missing = append(missing, "SPOTIFY_CLIENT_ID")
}
if c.clientSecret == "" {
missing = append(missing, "SPOTIFY_CLIENT_SECRET")
}
}
if len(missing) > 0 {
return c, fmt.Errorf("missing environment variables: %s (see .env.example)", strings.Join(missing, ", "))
}
if !strings.HasSuffix(c.redirectURI, "/callback") {
return c, errors.New("SPOTIFY_REDIRECT_URI must end in /callback, e.g. https://spotify.example.com/callback")
}
if c.publicURL == "" {
c.publicURL = strings.TrimSuffix(c.redirectURI, "/callback")
}
c.publicURL = strings.TrimRight(c.publicURL, "/")
if !store.ValidProfile(c.profile) {
return c, fmt.Errorf("PROFILE %q: use lower-case letters, digits and dashes", c.profile)
}
return c, nil
}

func main() {
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
cmd := "serve"
args := os.Args[1:]
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
cmd, args := "serve", os.Args[1:]
if len(args) > 0 && args[0] != "" && args[0][0] != '-' {
cmd, args = args[0], args[1:]
}
var err error
switch cmd {
case "serve":
err = serve(log)
err = serve(slog.New(slog.NewJSONHandler(os.Stderr, nil)))
case "invite":
err = invite(args)
case "version":
Expand All @@ -116,87 +58,105 @@ func invite(args []string) error {
if err := fs.Parse(args); err != nil {
return err
}
c, err := loadConfig(false)
cfg, err := config.Load(os.Getenv)
if err != nil {
return err
}
st, err := store.Open(c.dataDir)
store, err := filestore.Open(cfg.DataDir())
if err != nil {
return err
}
code, err := st.CreateInvite(c.profile, *ttl)
// Creating an invite never calls Spotify, so the credentials may be
// missing here; the OAuth and API adapters are only wired up.
oauth := spotify.NewOAuth(spotify.OAuthConfig{
ClientID: cfg.ClientID(), ClientSecret: cfg.ClientSecret(), RedirectURL: cfg.RedirectURL(),
})
api := spotify.NewAPI(spotify.DefaultAPIURL, nil)
accounts := account.NewService(store, store, oauth, api, account.SystemClock())
code, expires, err := accounts.CreateInvite(context.Background(), cfg.ProfileID(), *ttl)
if err != nil {
return err
}
fmt.Printf("%s/connect?invite=%s\n", c.publicURL, code)
fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", c.profile, time.Now().Add(*ttl).Format("2006-01-02 15:04 MST"))
fmt.Println(cfg.InviteURL(code))
fmt.Fprintf(os.Stderr, "One-time link for profile %q, valid until %s.\n", cfg.ProfileID(), expires.Format("2006-01-02 15:04 MST"))
return nil
}

func serve(log *slog.Logger) error {
c, err := loadConfig(true)
cfg, err := config.Load(os.Getenv)
if err != nil {
return err
}
st, err := store.Open(c.dataDir)
if err != nil {
if err := cfg.RequireCredentials(); err != nil {
return err
}
oc := &oauth2.Config{
ClientID: c.clientID,
ClientSecret: c.clientSecret,
Endpoint: spotify.Endpoint,
RedirectURL: c.redirectURI,
Scopes: spotify.Scopes,
}
client := spotify.NewClient(oc, st, c.profile, nil)
if _, err := st.Token(c.profile); errors.Is(err, store.ErrNotFound) {
log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", c.profile)
store, err := filestore.Open(cfg.DataDir())
if err != nil {
return err
}

srv := mcp.NewServer(&mcp.Implementation{Name: "spotify-mcp", Title: "Spotify", Version: version}, &mcp.ServerOptions{
Instructions: "Controls Spotify playback on the user's devices (Spotify Connect). Use devices to find a device name, search for URIs, and play/pause/resume/next/previous/transfer to control playback.",
oauth := spotify.NewOAuth(spotify.OAuthConfig{
ClientID: cfg.ClientID(), ClientSecret: cfg.ClientSecret(), RedirectURL: cfg.RedirectURL(),
})
tools.Register(srv, client)
mcpMux := http.NewServeMux()
mcpMux.Handle("/mcp", mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, &mcp.StreamableHTTPOptions{
Logger: log,
SessionTimeout: 30 * time.Minute,
}))
mcpMux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok\n")) })
api := spotify.NewAPI(spotify.DefaultAPIURL, nil)
clock := account.SystemClock()
tokens := account.NewTokenSource(store, oauth, cfg.ProfileID(), clock)
player := playback.NewService(spotify.NewPlayer(api, tokens))
accounts := account.NewService(store, store, oauth, api, clock)

wh := &web.Handler{
OAuth: oc,
Store: st,
Log: log,
MeURL: "https://api.spotify.com/v1/me",
OnConnect: func(string) { client.Forget() },
// Only for the log: a broken token file shouldn't stop the server, the
// tools report it when they need the token.
prof, err := account.NewProfiles(store).Profile(context.Background(), cfg.ProfileID())
if err != nil {
log.Warn("can't read the connected account", "profile", cfg.ProfileID().String(), "err", err)
} else if acc, ok := prof.Account(); ok {
log.Info("spotify account connected", "profile", prof.ID().String(), "spotify_user", acc.ID())
} else {
log.Warn("no Spotify account connected yet; run 'spotify-mcp invite' and open the link", "profile", prof.ID().String())
}

servers := []*http.Server{
{Addr: c.mcpAddr, Handler: mcpMux, ReadHeaderTimeout: 10 * time.Second},
{Addr: c.webAddr, Handler: wh.Routes(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second},
}
{
Addr: cfg.MCPAddr(),
Handler: mcpserver.Handler(mcpserver.NewServer(player, version), log),
ReadHeaderTimeout: 10 * time.Second,
},
{
Addr: cfg.WebAddr(),
Handler: web.NewHandler(accounts, log),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
},
}
log.Info("spotify-mcp started", "version", version, "profile", cfg.ProfileID().String(), "connect_url", cfg.ConnectURL())
return run(log, servers)
}

// run serves until SIGINT/SIGTERM or a server fails, then shuts all down.
func run(log *slog.Logger, servers []*http.Server) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
errc := make(chan error, len(servers))
for _, s := range servers {
go func() {
log.Info("listening", "addr", s.Addr)
if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errc <- err
errc <- fmt.Errorf("serve %s: %w", s.Addr, err)
}
}()
}
log.Info("spotify-mcp started", "version", version, "profile", c.profile, "connect_url", c.publicURL+"/connect")
var err error
select {
case <-ctx.Done():
case err = <-errc:
}
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for _, s := range servers {
_ = s.Shutdown(shutdown)
if serr := s.Shutdown(shutdown); serr != nil {
log.Warn("shutdown", "addr", s.Addr, "err", serr)
}
}
return err
}
Loading
Loading