Skip to main content
Glama
boristopalov

Spotify MCP Server

by boristopalov

SpotifySearch

Search Spotify for tracks, albums, artists, or playlists using query terms and filters to find specific music content.

Instructions

Search for tracks, albums, artists, or playlists on Spotify.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesquery term
qtypeNoType of items to search for (track, album, artist, playlist, or comma-separated combination)track
limitNoMaximum number of items to return

Implementation Reference

  • Pydantic model defining the input schema for the SpotifySearch tool.
    class Search(ToolModel):
        """Search for tracks, albums, artists, or playlists on Spotify."""
        query: str = Field(description="query term")
        qtype: Optional[str] = Field(default="track", description="Type of items to search for (track, album, artist, playlist, or comma-separated combination)")
        limit: Optional[int] = Field(default=10, description="Maximum number of items to return")
  • Registers the SpotifySearch tool by including it in the list returned by list_tools().
    @server.list_tools()
    async def handle_list_tools() -> list[types.Tool]:
        """List available tools."""
        logger.info("Listing available tools")
        tools = [
            Playback.as_tool(),
            Search.as_tool(),
            Queue.as_tool(),
            GetInfo.as_tool(),
        ]
        logger.info(f"Available tools: {[tool.name for tool in tools]}")
        return tools
  • MCP handler for SpotifySearch: parses arguments, calls Spotify client search, and returns results as JSON.
    case "Search":
        logger.info(f"Performing search with arguments: {arguments}")
        search_results = spotify_client.search(
            query=arguments.get("query", ""),
            qtype=arguments.get("qtype", "track"),
            limit=arguments.get("limit", 10)
        )
        logger.info("Search completed successfully")
        return [types.TextContent(
            type="text",
            text=json.dumps(search_results, indent=2)
        )]
  • Core implementation of the search functionality using Spotipy client.
    def search(self, query: str, qtype: str = 'track', limit=10):
        """
        Searches based of query term.
        - query: query term
        - qtype: the types of items to return. One or more of 'artist', 'album',  'track', 'playlist'.
                 If multiple types are desired, pass in a comma separated string; e.g. 'track,album'
        - limit: max # items to return
        """
        results = self.sp.search(q=query, limit=limit, type=qtype)
        return utils.parse_search_results(results, qtype)
  • Helper function to parse and format Spotify search results into a structured dictionary.
    def parse_search_results(results: Dict, qtype: str):
        _results = defaultdict(list)
    
        for q in qtype.split(","):
            match q:
                case "track":
                    for idx, item in enumerate(results['tracks']['items']):
                        if not item: continue
                        _results['tracks'].append(parse_track(item))
                case "artist":
                    for idx, item in enumerate(results['artists']['items']):
                        if not item: continue
                        _results['artists'].append(parse_artist(item))
                case "playlist":
                    for idx, item in enumerate(results['playlists']['items']):
                        if not item: continue
                        _results['playlists'].append(parse_playlist(item))
                case "album":
                    for idx, item in enumerate(results['albums']['items']):
                        if not item: continue
                        _results['albums'].append(parse_album(item))
                case _:
                    raise ValueError(f"uknown qtype {qtype}")
    
        return dict(_results)

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv1.0.0
    • addedInput schema / description
      Added value: +"Search for tracks, albums, artists, or playlists on Spotify."
    • addedInput schema / title
      Added value: +"Search"
  2. First observed

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries burden. It mentions search types and parameters but omits behavior like response structure, pagination, error handling, auth needs, or rate limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single clear sentence, front-loaded with action verb. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 3 parameters, no output schema, and no annotations, the description is too brief. Lacks guidance on output format, pagination, or effective usage compared to sibling tools.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 100% coverage with descriptions for all 3 parameters. Description adds minimal context beyond schema (e.g., hinting at qtype values already documented). Baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states it searches for tracks, albums, artists, or playlists on Spotify. Distinct from sibling tools like SpotifyGetInfo (specific item info), SpotifyPlayback (playback control), SpotifyQueue (queue management).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Description implies usage for searching Spotify content, but no explicit when-to-use vs alternatives, no when-not or exclusions provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.