Skip to main content
Glama
kylestratis

Spotify Playlist MCP Server

by kylestratis

spotify_search_tracks

Read-onlyIdempotent

Search Spotify's catalog for tracks using names, artists, albums, or keywords. Get detailed results with track information in markdown or JSON format.

Instructions

Search for tracks on Spotify by name, artist, album, or keywords.

Searches Spotify's entire catalog using intelligent matching. Results ranked by relevance.

Args:
    - query: Search text, 1-200 chars (e.g., "Bohemian Rhapsody", "artist:Queen", "album:...", or keywords)
    - limit: Results to return, 1-50 (default: 20)
    - offset: Starting position for pagination (default: 0)
    - response_format: 'markdown' or 'json'

Returns:
    Markdown: Search results with track details (name, artists, album, duration, ID, URI, popularity)
    JSON: {"total": N, "count": N, "offset": N, "tracks": [{id, name, artists, album, duration_ms, popularity, uri, external_urls}], "has_more": bool}

Examples:
    - "Find Bohemian Rhapsody by Queen" -> query="Bohemian Rhapsody Queen"
    - "Search for songs by Taylor Swift" -> query="artist:Taylor Swift"
    - "Look for indie rock songs" -> query="indie rock"

Errors: Returns "No tracks found" if no results, or error for auth failure (401), rate limits (429). Truncates if exceeds character limit.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The @mcp.tool decorator registers the spotify_search_tracks handler function, which implements the core logic: validates input, calls Spotify's search API via make_spotify_request, formats results in markdown or JSON, handles pagination, truncation, and errors.
    @mcp.tool(
        name="spotify_search_tracks",
        annotations={
            "title": "Search Spotify Tracks",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True,
        },
    )
    async def spotify_search_tracks(params: SearchTracksInput) -> str:
        """Search for tracks on Spotify by name, artist, album, or keywords.
    
        Searches Spotify's entire catalog using intelligent matching. Results ranked by relevance.
    
        Args:
            - query: Search text, 1-200 chars (e.g., "Bohemian Rhapsody", "artist:Queen", "album:...", or keywords)
            - limit: Results to return, 1-50 (default: 20)
            - offset: Starting position for pagination (default: 0)
            - response_format: 'markdown' or 'json'
    
        Returns:
            Markdown: Search results with track details (name, artists, album, duration, ID, URI, popularity)
            JSON: {"total": N, "count": N, "offset": N, "tracks": [{id, name, artists, album, duration_ms, popularity, uri, external_urls}], "has_more": bool}
    
        Examples:
            - "Find Bohemian Rhapsody by Queen" -> query="Bohemian Rhapsody Queen"
            - "Search for songs by Taylor Swift" -> query="artist:Taylor Swift"
            - "Look for indie rock songs" -> query="indie rock"
    
        Errors: Returns "No tracks found" if no results, or error for auth failure (401), rate limits (429). Truncates if exceeds character limit.
        """
        try:
            query_params = {
                "q": params.query,
                "type": "track",
                "limit": params.limit,
                "offset": params.offset,
            }
    
            data = await make_spotify_request("search", params=query_params)
    
            tracks = data.get("tracks", {}).get("items", [])
            total = data.get("tracks", {}).get("total", 0)
    
            if not tracks:
                return f"No tracks found matching '{params.query}'"
    
            # Format response
            if params.response_format == ResponseFormat.MARKDOWN:
                lines = [
                    f"# Search Results: '{params.query}'\n",
                    f"Found {total} tracks (showing {len(tracks)})\n",
                ]
    
                for i, track in enumerate(tracks, 1):
                    lines.append(f"## {i}. {format_track_markdown(track)}\n")
    
                has_more = total > params.offset + len(tracks)
                if has_more:
                    next_offset = params.offset + len(tracks)
                    lines.append(
                        f"\n*More results available. Use offset={next_offset} to see more.*"
                    )
    
                result = "\n".join(lines)
                truncation_msg = check_character_limit(result, tracks)
                if truncation_msg:
                    tracks = tracks[: len(tracks) // 2]
                    lines = [
                        f"# Search Results: '{params.query}'\n",
                        truncation_msg,
                        f"Found {total} tracks (showing {len(tracks)})\n",
                    ]
                    for i, track in enumerate(tracks, 1):
                        lines.append(f"## {i}. {format_track_markdown(track)}\n")
                    result = "\n".join(lines)
    
                return result
            else:
                # JSON format
                return json.dumps(
                    {
                        "total": total,
                        "count": len(tracks),
                        "offset": params.offset,
                        "tracks": tracks,
                        "has_more": total > params.offset + len(tracks),
                    },
                    indent=2,
                )
    
        except Exception as e:
            return handle_spotify_error(e)
  • Pydantic model defining the input parameters for the spotify_search_tracks tool: required query (1-200 chars), optional limit (1-50), offset (>=0), and response_format.
    class SearchTracksInput(BaseModel):
        """Input model for searching tracks."""
    
        model_config = ConfigDict(str_strip_whitespace=True, validate_assignment=True)
    
        query: str = Field(
            ..., description="Search query for tracks", min_length=1, max_length=200
        )
        limit: int | None = Field(
            default=20, description="Number of results to return", ge=1, le=50
        )
        offset: int | None = Field(default=0, description="Offset for pagination", ge=0)
        response_format: ResponseFormat = Field(
            default=ResponseFormat.MARKDOWN,
            description="Output format: 'markdown' or 'json'",
        )
Behavior4/5

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

The description adds valuable behavioral context beyond what annotations provide. While annotations cover read-only, open-world, and idempotent properties, the description adds specific details about result ranking ('ranked by relevance'), error conditions (auth failure, rate limits, 'No tracks found'), character truncation, and response format differences. This enhances the agent's understanding of how the tool behaves in practice.

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 clear sections (purpose, args, returns, examples, errors) and front-loaded key information. While comprehensive, it could be slightly more concise by integrating some details more tightly, but every sentence adds meaningful value without redundancy.

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

Completeness5/5

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

Given the tool's complexity (search functionality with multiple parameters and output formats), the description provides complete context. It covers purpose, parameters with semantics, return formats with examples, error handling, and behavioral details. With annotations covering safety properties and an output schema presumably detailing the return structure, the description fills all necessary gaps effectively.

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

Parameters5/5

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

The description provides extensive parameter semantics despite 0% schema description coverage. It explains each parameter's purpose, constraints, and defaults (query with examples and length limits, limit with range, offset for pagination, response_format with options). It also clarifies the relationship between parameters and output formats, adding significant value beyond the bare schema.

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 the tool's purpose with specific verbs ('Search for tracks') and resources ('Spotify's entire catalog'), distinguishing it from siblings like spotify_get_track (single track) or spotify_get_playlist_tracks (playlist-specific). It explicitly mentions searching by name, artist, album, or keywords.

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

Usage Guidelines4/5

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

The description provides clear context about when to use this tool (searching Spotify's catalog with various query types) and includes examples that illustrate different use cases. However, it doesn't explicitly state when NOT to use it or mention specific alternatives among the sibling tools, such as spotify_find_similar_tracks for related tracks instead of keyword searches.

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

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