Skip to main content
Glama
varunneal

Spotify MCP Server

by varunneal

SpotifySearch

Search Spotify for tracks, albums, artists, or playlists using specific queries and filters to find 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

  • Core implementation of the Spotify search functionality, calling spotipy.search and parsing results with utils.parse_search_results.
    def search(self, query: str, qtype: str = 'track', limit=10, device=None):
        """
        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
        """
        if self.username is None:
            self.set_username()
        results = self.sp.search(q=query, limit=limit, type=qtype)
        if not results:
            raise ValueError("No search results found.")
        return utils.parse_search_results(results, qtype, self.username)
  • Tool dispatcher handler case for 'SpotifySearch', invokes spotify_client.search with parsed arguments and returns JSON results.
    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)
        )]
  • Pydantic schema defining the input parameters 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 (as 'SpotifySearch') by including Search.as_tool() in the list of available tools.
    @server.list_tools()
    async def handle_list_tools() -> list[types.Tool]:
        """List available tools."""
        logger.info("Listing available tools")
        # await server.request_context.session.send_notification("are you recieving this notification?")
        tools = [
            Playback.as_tool(),
            Search.as_tool(),
            Queue.as_tool(),
            GetInfo.as_tool(),
            Playlist.as_tool(),
        ]
        logger.info(f"Available tools: {[tool.name for tool in tools]}")
        return tools
  • Helper function to parse and structure search results from spotipy into a standardized dictionary format.
    def parse_search_results(results: Dict, qtype: str, username: Optional[str] = None):
        _results = defaultdict(list)
        # potential
        # if username:
        #     _results['User Spotify URI'] = username
    
        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, username))
                case "album":
                    for idx, item in enumerate(results['albums']['items']):
                        if not item: continue
                        _results['albums'].append(parse_album(item))
                case _:
                    raise ValueError(f"Unknown qtype {qtype}")
    
        return dict(_results)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action ('Search') but doesn't cover critical aspects like authentication requirements, rate limits, pagination behavior, or error handling. For a search tool interacting with an external API, this lack of behavioral context is a significant gap.

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?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded with the core action and resources, making it easy to parse quickly.

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?

For a search tool with no annotations and no output schema, the description is incomplete. It doesn't explain what the search returns (e.g., list of items with metadata), how results are formatted, or any limitations (e.g., maximum query length). Given the complexity of interacting with Spotify's API, more context is needed for effective use.

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 description coverage is 100%, so the schema fully documents all three parameters (query, qtype, limit). The description doesn't add any parameter-specific details beyond what's in the schema, such as query syntax examples or qtype combination nuances. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the verb ('Search') and resources ('tracks, albums, artists, or playlists on Spotify'), making the purpose immediately understandable. However, it doesn't explicitly differentiate this search tool from sibling tools like SpotifyGetInfo or SpotifyPlaylist, which might also involve searching or retrieving content.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like SpotifyGetInfo (which might retrieve specific items) or SpotifyPlaylist (which might handle playlist-specific operations), leaving the agent to infer usage context without explicit direction.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/varunneal/spotify-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server