Skip to main content
Glama
jamiew

Spotify MCP Server

search_tracks

Search Spotify for tracks, albums, artists, or playlists using keywords, genre, year, and other filters. Get paginated results to browse through large collections.

Instructions

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

Args:
    query: Search query
    qtype: Type ('track', 'album', 'artist', 'playlist')
    limit: Max results per page (1-50, default 10)
    offset: Number of results to skip for pagination (default 0)
    year: Filter by year (e.g., '2024')
    year_range: Filter by year range (e.g., '2020-2024')
    genre: Filter by genre (e.g., 'electronic', 'hip-hop')
    artist: Filter by artist name
    album: Filter by album name

Returns:
    Dict with 'items' (list of tracks) and pagination info ('total', 'limit', 'offset')

Note: Filters use Spotify's search syntax. For large result sets, use offset to paginate.
Example: query='love', year='2024', genre='pop' searches for 'love year:2024 genre:pop'

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
qtypeNotrack
limitNo
offsetNo
yearNo
year_rangeNo
genreNo
artistNo
albumNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Main handler function for the search_tracks tool. Decorated with @mcp.tool() and @log_tool_execution. Accepts query, qtype, limit, offset, year, year_range, genre, artist, album parameters. Builds filtered query using Spotify search syntax, calls spotify_client.search(), parses results using parse_track() for tracks or constructs Track objects for other types, and returns paginated results.
    @mcp.tool()
    @log_tool_execution
    def search_tracks(
        query: str,
        qtype: str = "track",
        limit: int = 10,
        offset: int = 0,
        year: str | None = None,
        year_range: str | None = None,
        genre: str | None = None,
        artist: str | None = None,
        album: str | None = None,
    ) -> dict[str, Any]:
        """Search Spotify for tracks, albums, artists, or playlists.
    
        Args:
            query: Search query
            qtype: Type ('track', 'album', 'artist', 'playlist')
            limit: Max results per page (1-50, default 10)
            offset: Number of results to skip for pagination (default 0)
            year: Filter by year (e.g., '2024')
            year_range: Filter by year range (e.g., '2020-2024')
            genre: Filter by genre (e.g., 'electronic', 'hip-hop')
            artist: Filter by artist name
            album: Filter by album name
    
        Returns:
            Dict with 'items' (list of tracks) and pagination info ('total', 'limit', 'offset')
    
        Note: Filters use Spotify's search syntax. For large result sets, use offset to paginate.
        Example: query='love', year='2024', genre='pop' searches for 'love year:2024 genre:pop'
        """
        try:
            limit = max(1, min(50, limit))
    
            # Build filtered query
            filters = []
            if artist:
                filters.append(f"artist:{artist}")
            if album:
                filters.append(f"album:{album}")
            if year:
                filters.append(f"year:{year}")
            if year_range:
                filters.append(f"year:{year_range}")
            if genre:
                filters.append(f"genre:{genre}")
    
            full_query = " ".join([query] + filters) if filters else query
    
            logger.info(
                f"🔍 Searching {qtype}s: '{full_query}' (limit={limit}, offset={offset})"
            )
            result = spotify_client.search(q=full_query, type=qtype, limit=limit, offset=offset)
    
            tracks = []
            items_key = f"{qtype}s"
            result_section = result.get(items_key, {})
            if qtype == "track" and result_section.get("items"):
                tracks = [parse_track(item) for item in result_section["items"]]
            else:
                # Convert other types to track-like format for consistency
                if result_section.get("items"):
                    for item in result_section["items"]:
                        track = Track(
                            name=item["name"],
                            id=item["id"],
                            artist=item.get("artists", [{}])[0].get("name", "Unknown")
                            if qtype != "artist"
                            else item["name"],
                            external_urls=item.get("external_urls"),
                        )
                        tracks.append(track)
    
            total_results = result_section.get("total", 0)
            logger.info(
                f"🔍 Search returned {len(tracks)} items (total available: {total_results})"
            )
            log_pagination_info("search_tracks", total_results, limit, offset)
    
            return {
                "items": tracks,
                "total": total_results,
                "limit": result_section.get("limit", limit),
                "offset": result_section.get("offset", offset),
                "next": result_section.get("next"),
                "previous": result_section.get("previous"),
            }
        except SpotifyException as e:
            raise convert_spotify_error(e) from e
  • Pydantic model defining the output schema for track data returned by search_tracks.
    class Track(BaseModel):
        """A Spotify track with metadata."""
    
        name: str
        id: str
        artist: str
        artists: list[str] | None = None
        album: str | None = None
        album_id: str | None = None
        release_date: str | None = None
        duration_ms: int | None = None
        popularity: int | None = None
        external_urls: dict[str, str] | None = None
  • Registration via the @mcp.tool() decorator on the FastMCP instance, which automatically registers search_tracks as an MCP tool.
    @mcp.tool()
  • Helper function used by search_tracks to parse raw Spotify track data into the Track Pydantic model.
    def parse_track(item: dict[str, Any]) -> Track:
        """Parse Spotify track data into Track model."""
        album_data = item.get("album", {})
        return Track(
            name=item["name"],
            id=item["id"],
            artist=item["artists"][0]["name"] if item.get("artists") else "Unknown",
            artists=[a["name"] for a in item.get("artists", [])],
            album=album_data.get("name"),
            album_id=album_data.get("id"),
            release_date=album_data.get("release_date"),
            duration_ms=item.get("duration_ms"),
            popularity=item.get("popularity"),
            external_urls=item.get("external_urls"),
        )
Behavior3/5

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

With no annotations, the description carries the burden of behavioral disclosure. It explains parameters, return structure, and filter syntax via Spotify's search syntax. However, it does not mention side effects (none expected for search), rate limits, or authentication requirements, leaving minor gaps.

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

Conciseness4/5

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

The description is well-structured with an opening sentence, a list of arguments, a return description, and a usage note with an example. While slightly long, each section serves a purpose and the information is front-loaded.

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

Completeness4/5

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

Given the tool's complexity (9 parameters, output schema exists), the description covers parameter semantics, pagination, filter syntax, and return format. It does not discuss error scenarios or performance considerations, but for a search tool it is largely complete.

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

Parameters4/5

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

Despite 0% schema coverage in context signals, the description provides detailed explanations for all 9 parameters, including ranges for limit (1-50), defaults, and filter combination examples. This adds significant meaning beyond the schema's type-only definitions.

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?

The description clearly states it searches Spotify for multiple content types (tracks, albums, artists, or playlists). This specific verb-resource combination distinguishes it from sibling tools like get_track_info or get_album_info, which are retrieval-focused.

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?

The description implies usage for search queries but does not explicitly state when to use this tool versus alternatives (e.g., dedicated info tools for specific entities). There is no guidance on when not to use it or how it compares to other search-like methods.

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/jamiew/spotify-mcp'

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