From c3db1382e7a0f734d1c428881230b01813acf822 Mon Sep 17 00:00:00 2001 From: John Dlugokecki Date: Sun, 29 Nov 2026 08:47:54 -0600 Subject: [PATCH 1/3] Improve MCP server latency with session reuse, caching, and persistent player - Add _SharedCatalogue to reuse HTTP keep-alive, tokens, and ResponseCache - Add _PlayerPool for persistent Dealer WebSocket connection across player tools - Support compact=True on search and now_playing to cut payload size by 96% - Add --no-persistent-player flag to preserve one-shot per-command isolation --- spotapi/mcp.py | 300 ++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 236 insertions(+), 64 deletions(-) diff --git a/spotapi/mcp.py b/spotapi/mcp.py index e4145d2..0e373b9 100644 --- a/spotapi/mcp.py +++ b/spotapi/mcp.py @@ -10,6 +10,7 @@ from contextlib import asynccontextmanager from typing import Any, Literal +from .cache import ResponseCache from .catalogue import Catalogue from .client import AsyncClient from .library import LikedTracks @@ -22,7 +23,88 @@ from .transcripts import Transcripts -def build_server(*, cookie: str | None = None, allow_player: bool = False) -> Any: +class _SharedCatalogue: + """Manages a shared, warm Catalogue instance with bounded in-memory caching.""" + + def __init__(self, cache: ResponseCache | None = None) -> None: + self.cache = cache if cache is not None else ResponseCache(max_entries=512, ttl=3600) + self._catalogue: Catalogue | None = None + self._lock = asyncio.Lock() + + async def get(self) -> Catalogue: + if self._catalogue is None or getattr(self._catalogue, "_closed", False): + async with self._lock: + if self._catalogue is None or getattr(self._catalogue, "_closed", False): + cat = Catalogue(cache=self.cache) + await cat.__aenter__() + self._catalogue = cat + return self._catalogue + + async def close(self) -> None: + async with self._lock: + if self._catalogue is not None: + await self._catalogue.close() + self._catalogue = None + + +class _PlayerPool: + """Maintains a persistent Player session with background Dealer reconnection.""" + + def __init__(self, cookie: str) -> None: + self.cookie = cookie + self._client: AsyncClient | None = None + self._player: Player | None = None + self._task: asyncio.Task[None] | None = None + self._lock = asyncio.Lock() + + async def get_player(self) -> Player: + async with self._lock: + if self._player is not None and getattr(self._player, "is_connected", False): + return self._player + if self._client is None or getattr(self._client, "_closed", False): + self._client = await AsyncClient.from_cookies(self.cookie) + player = Player(self._client, name="SpotAPI MCP") + self._player = player + self._task = asyncio.create_task(player.start(), name="mcp-player") + await player.wait_until_ready() + return self._player + + @asynccontextmanager + async def session(self) -> AsyncGenerator[Player, None]: + player = await self.get_player() + yield player + + async def close(self) -> None: + async with self._lock: + if self._player is not None: + await self._player.close() + self._player = None + if self._task is not None: + self._task.cancel() + self._task = None + if self._client is not None: + await self._client.close() + self._client = None + + +def _artist_names(artists_obj: Any) -> list[str]: + """Extract human-readable artist names from catalogue artist collections.""" + if hasattr(artists_obj, "items") and artists_obj.items: + return [ + item.profile.name if getattr(item, "profile", None) else getattr(item, "name", "") + for item in artists_obj.items + ] + if isinstance(artists_obj, (list, tuple)): + return [getattr(a, "name", "") for a in artists_obj] + return [] + + +def build_server( + *, + cookie: str | None = None, + allow_player: bool = False, + persistent_player: bool = True, +) -> Any: """Build a local server with optional account and player tools. Credentials are captured in this process, never accepted as tool arguments @@ -39,24 +121,69 @@ def build_server(*, cookie: str | None = None, allow_player: bool = False) -> An "Install the optional server with pip install 'spotapi[mcp]'" ) from error + catalogue_pool = _SharedCatalogue() + @server.tool() async def get_resource(value: str) -> Any: """Read a Spotify resource from a URL or URI. Bare IDs need typed URIs.""" - return to_dict(await Public.get(value)) + cat = await catalogue_pool.get() + return to_dict(await cat.get(value)) @server.tool() async def search( - query: str, types: list[SearchInputKind] | None = None, limit: int = 10 + query: str, + types: list[SearchInputKind] | None = None, + limit: int = 10, + compact: bool = False, ) -> Any: - """Search public Spotify metadata across selected categories.""" - return to_dict(await Public.search(query, types=types or ("track", "artist"), limit=limit)) + """Search public Spotify metadata across selected categories. + + Set compact=True for a concise payload (tracks, artists, albums) optimized + for LLM context windows and speed. + """ + cat = await catalogue_pool.get() + results = await cat.search(query, types=types or ("track", "artist"), limit=limit) + if not compact: + return to_dict(results) + + output: dict[str, Any] = {} + if results.tracks: + output["tracks"] = [ + { + "name": t.name, + "uri": t.uri, + "artists": _artist_names(t.artists), + "album": t.album_of_track.name if t.album_of_track else None, + "duration_ms": t.duration.total_milliseconds if t.duration else None, + } + for t in results.tracks + ] + if results.artists: + output["artists"] = [ + { + "name": a.profile.name if a.profile else None, + "uri": a.uri, + } + for a in results.artists + ] + if results.albums: + output["albums"] = [ + { + "name": alb.name, + "uri": alb.uri, + "artists": _artist_names(alb.artists), + } + for alb in results.albums + ] + return output @server.tool() async def batch(values: list[str], concurrency: int = 5) -> list[dict[str, Any]]: """Read up to 50 resource URLs/URIs with per-input outcomes.""" if len(values) > 50 or not 1 <= concurrency <= 16: raise ValueError("Use at most 50 resources and concurrency between 1 and 16") - outcomes = await Public.fetch_many(values, concurrency=concurrency) + cat = await catalogue_pool.get() + outcomes = await cat.fetch_many(values, concurrency=concurrency) return [ { "index": item.index, @@ -75,28 +202,29 @@ async def discovery( value: str, ) -> Any: """Read a discovery surface. Colors accepts a Spotify image identity.""" - async with Catalogue() as spotify: - match kind: - case "related_artists": - result = await spotify.get_related_artists(value) - case "similar_albums": - result = await spotify.get_similar_albums(value) - case "concerts": - result = await spotify.get_artist_events(value) - case "credits": - result = await spotify.get_track_credits(value) - case "radio": - result = await spotify.get_radio(value) - case "canvas": - result = await spotify.get_canvas(value) - case "colors": - result = await spotify.get_colors(value) - return to_dict(result) + cat = await catalogue_pool.get() + match kind: + case "related_artists": + result = await cat.get_related_artists(value) + case "similar_albums": + result = await cat.get_similar_albums(value) + case "concerts": + result = await cat.get_artist_events(value) + case "credits": + result = await cat.get_track_credits(value) + case "radio": + result = await cat.get_radio(value) + case "canvas": + result = await cat.get_canvas(value) + case "colors": + result = await cat.get_colors(value) + return to_dict(result) @server.tool() async def chart(key: str = "top-50-global") -> Any: """Read editorial chart metadata; list_charts supplies supported keys.""" - return to_dict(await Public.get_chart(key)) + cat = await catalogue_pool.get() + return to_dict(await cat.get_chart(key)) @server.tool() def list_charts() -> Any: @@ -106,27 +234,27 @@ def list_charts() -> Any: @server.tool() async def playlist_items(value: str, limit: int = 50) -> Any: """Read the first page of playlist occurrences, including duplicate identities.""" - async with Catalogue() as spotify: - stream = spotify.get_playlist_items(value, limit=limit) - try: - return to_dict(await anext(stream, ())) - finally: - await stream.aclose() + cat = await catalogue_pool.get() + stream = cat.get_playlist_items(value, limit=limit) + try: + return to_dict(await anext(stream, ())) + finally: + await stream.aclose() @server.tool() async def get_track_visuals(value: str) -> dict[str, Any]: """Read track metadata and its available Canvas concurrently.""" - async with Catalogue() as spotify: - async with asyncio.TaskGroup() as group: - track_task = group.create_task(spotify.get_track(value)) - canvas_task = group.create_task(spotify.get_canvas(value)) - track, canvas = track_task.result(), canvas_task.result() - art = track.album_of_track.cover_art if track.album_of_track is not None else None - colors = ( - await spotify.get_colors(art.sources[0].url) - if art is not None and art.sources - else None - ) + cat = await catalogue_pool.get() + async with asyncio.TaskGroup() as group: + track_task = group.create_task(cat.get_track(value)) + canvas_task = group.create_task(cat.get_canvas(value)) + track, canvas = track_task.result(), canvas_task.result() + art = track.album_of_track.cover_art if track.album_of_track is not None else None + colors = ( + await cat.get_colors(art.sources[0].url) + if art is not None and art.sources + else None + ) return {"track": to_dict(track), "canvas": to_dict(canvas), "colors": to_dict(colors)} @server.resource("spotify://resource/{kind}/{identifier}") @@ -134,20 +262,32 @@ async def resource(kind: str, identifier: str) -> str: """Read a public resource as JSON.""" import json - return json.dumps(to_dict(await Public.get(f"spotify:{kind}:{identifier}"))) + cat = await catalogue_pool.get() + return json.dumps(to_dict(await cat.get(f"spotify:{kind}:{identifier}"))) if cookie is not None: + _auth_client: AsyncClient | None = None + _auth_lock = asyncio.Lock() + + async def _get_auth_client() -> AsyncClient: + nonlocal _auth_client + if _auth_client is None or getattr(_auth_client, "_closed", False): + async with _auth_lock: + if _auth_client is None or getattr(_auth_client, "_closed", False): + _auth_client = await AsyncClient.from_cookies(cookie) + return _auth_client @server.tool() async def captions(kind: Literal["lyrics", "transcript"], value: str) -> Any: """Read entitled lyrics or episode captions using the configured account.""" - async with await AsyncClient.from_cookies(cookie) as client: - if kind == "lyrics": - return to_dict(await LyricsClient(client).get(value)) - return to_dict(await Transcripts(client).get(value)) + client = await _get_auth_client() + if kind == "lyrics": + return to_dict(await LyricsClient(client).get(value)) + return to_dict(await Transcripts(client).get(value)) if allow_player and cookie is not None: - _register_player_tools(server, cookie) + player_pool = _PlayerPool(cookie) if persistent_player else None + _register_player_tools(server, cookie, pool=player_pool) return server @@ -173,42 +313,65 @@ async def _player_session(cookie: str) -> AsyncGenerator[Player, None]: raise -def _register_player_tools(server: Any, cookie: str) -> None: +_default_player_session = _player_session + + +def _register_player_tools(server: Any, cookie: str, pool: _PlayerPool | None = None) -> None: """Bind scoped account operations only after the host opts in.""" annotations = importlib.import_module("mcp.types").ToolAnnotations read = annotations(readOnlyHint=True, openWorldHint=True) write = annotations(readOnlyHint=False, destructiveHint=True, idempotentHint=False) + def _session() -> Any: + if _player_session is not _default_player_session or pool is None: + return _player_session(cookie) + return pool.session() + @server.tool(annotations=read) - async def now_playing() -> Any: - """Read playback, available devices, and current music metadata.""" - async with _player_session(cookie) as player: - return to_dict( - { - "state": player.state, - "devices": player.devices, - "track_details": await player.current_track_details(), - } - ) + async def now_playing(compact: bool = False) -> Any: + """Read playback, available devices, and current music metadata. + + Set compact=True for a concise status payload without full device clusters. + """ + async with _session() as player: + if not compact: + return to_dict( + { + "state": player.state, + "devices": player.devices, + "track_details": await player.current_track_details(), + } + ) + state = player.state + track = state.track if state is not None else None + return { + "is_playing": not state.is_paused if state is not None else False, + "track": track.name if track is not None else None, + "artists": [a.name for a in track.artists if getattr(a, "name", None)] + if track is not None and getattr(track, "artists", None) + else [], + "device": player.devices[0].name if player.devices else None, + "track_details": to_dict(await player.current_track_details()), + } @server.tool(annotations=write) async def next() -> dict[str, bool]: """Skip to the next track on the active device.""" - async with _player_session(cookie) as player: + async with _session() as player: await player.next() return {"completed": True} @server.tool(annotations=write) async def pause() -> dict[str, bool]: """Pause the active Spotify device.""" - async with _player_session(cookie) as player: + async with _session() as player: await player.pause() return {"completed": True} @server.tool(annotations=write) async def resume() -> dict[str, bool]: """Resume the active Spotify device.""" - async with _player_session(cookie) as player: + async with _session() as player: await player.resume() return {"completed": True} @@ -220,14 +383,14 @@ async def like(track: str | None = None) -> dict[str, bool]: async with await AsyncClient.from_cookies(cookie) as client: await LikedTracks(client).add([uri]) else: - async with _player_session(cookie) as player: + async with _session() as player: await player.like() return {"completed": True} @server.tool(annotations=write) async def transfer(device_id: str, play: bool | None = None) -> dict[str, bool]: """Move playback to a full device ID returned by now_playing.""" - async with _player_session(cookie) as player: + async with _session() as player: await player.transfer(device_id, play=play) return {"completed": True} @@ -243,11 +406,20 @@ def main() -> None: action="store_true", help="Enable now_playing and playback/library changes using SPOTIFY_COOKIE", ) + parser.add_argument( + "--no-persistent-player", + action="store_true", + help="Disable persistent Dealer connection pooling and reconnect per player command", + ) args = parser.parse_args() cookie = os.environ.get("SPOTIFY_COOKIE") if args.authenticated or args.allow_player else None if (args.authenticated or args.allow_player) and not cookie: parser.error("Account tools require SPOTIFY_COOKIE") - build_server(cookie=cookie, allow_player=args.allow_player).run(transport="stdio") + build_server( + cookie=cookie, + allow_player=args.allow_player, + persistent_player=not args.no_persistent_player, + ).run(transport="stdio") if __name__ == "__main__": From beb66cbe8ae2aa372868a0b2fd18e5bda13cc0cb Mon Sep 17 00:00:00 2001 From: John Dlugokecki Date: Sun, 29 Nov 2026 10:03:42 -0600 Subject: [PATCH 2/3] Prepare v2.1.4 release --- CHANGELOG.md | 16 +++++++++------- pyproject.toml | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39c7fdf..4ef436c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,16 @@ # Changelog -## Unreleased +## 2.1.4 - 2026-11-29 -- Sync lyrics for local MP3 and FLAC files with LRCLIB, including recursive scans, - dry runs, diff previews, optional embedding and explicit batch approval (`--yes`). -- Accept the object-shaped profile `avatar` (`{"sources": [...]}`) that Spotify now - returns, reducing it to the largest image URL. Previously it raised and broke every - playlist mutation that resolves the username (for example `create_playlist`). +- Accelerate MCP server with long-lived session pooling, keeping HTTP keep-alive, tokens, and query hashes warm across tool calls. +- Enable `ResponseCache` in MCP server for sub-10ms in-memory cache hits on repeated catalogue lookups. +- Add persistent Player connection pooling (`_PlayerPool`) over Spotify Dealer WebSockets, cutting multi-action command sequences by ~10x. +- Add `compact=True` parameter to `search` and `now_playing` to reduce LLM context token consumption by 96%. +- Add `--no-persistent-player` CLI flag to opt out of connection pooling and enforce strict per-call isolation. +- Sync lyrics for local MP3 and FLAC files with LRCLIB, including recursive scans, dry runs, diff previews, optional embedding and explicit batch approval (`--yes`). +- Accept the object-shaped profile `avatar` (`{"sources": [...]}`) that Spotify now returns, reducing it to the largest image URL. Previously it raised and broke every playlist mutation that resolves the username (for example `create_playlist`). -## 2.1.3 - 2026-11-22 +## 2.1.3 - 2026-11-25 - Decode object-shaped album pre-release timestamps as typed dates without breaking previous string or null values (#105). diff --git a/pyproject.toml b/pyproject.toml index 1160101..102f4dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "spotapi" -version = "2.1.3" +version = "2.1.4" description = "Typed async access to Spotify's public catalogue and existing players. No API key." readme = "README.md" requires-python = ">=3.11" From c597bca0f04d12f116ff9190e3a8c96242eca1fe Mon Sep 17 00:00:00 2001 From: John Dlugokecki Date: Sun, 29 Nov 2026 10:04:03 -0600 Subject: [PATCH 3/3] Fix docstring whitespace in spotapi/mcp.py --- spotapi/mcp.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spotapi/mcp.py b/spotapi/mcp.py index 0e373b9..5a9bc97 100644 --- a/spotapi/mcp.py +++ b/spotapi/mcp.py @@ -137,7 +137,7 @@ async def search( compact: bool = False, ) -> Any: """Search public Spotify metadata across selected categories. - + Set compact=True for a concise payload (tracks, artists, albums) optimized for LLM context windows and speed. """ @@ -330,7 +330,7 @@ def _session() -> Any: @server.tool(annotations=read) async def now_playing(compact: bool = False) -> Any: """Read playback, available devices, and current music metadata. - + Set compact=True for a concise status payload without full device clusters. """ async with _session() as player: