Skip to main content
Glama
kylestratis

Spotify Playlist MCP Server

by kylestratis

spotify_get_recommendations

Read-onlyIdempotent

Generate personalized Spotify track recommendations using seed tracks, artists, or genres with tunable audio features like energy, danceability, and tempo.

Instructions

Get track recommendations from Spotify based on seed tracks, artists, or genres.

Generates personalized recommendations using up to 5 seeds (any combination) with
tunable audio features (energy, danceability, valence, tempo).

Args:
    - seed_tracks/seed_artists/seed_genres: Up to 5 total seeds (track IDs, artist IDs, or genre names)
    - limit: Results to return, 1-100 (default: 20)
    - min/max/target audio features: Energy, danceability, valence (0.0-1.0), tempo (BPM)
    - response_format: 'markdown' (formatted) or 'json' (structured data)

Returns:
    Markdown: Numbered list with track details (name, artists, album, duration, ID, popularity)
    JSON: {"total": N, "tracks": [{id, name, artists, album, duration_ms, popularity, uri, external_urls}]}

Examples:
    - "Find energetic workout music" -> seed_genres=['electronic'], target_energy=0.9
    - "Songs like this track" -> seed_tracks=['track_id']
    - "Happy danceable songs" -> target_valence=0.8, target_danceability=0.8

Errors: Returns error for no seeds, >5 seeds, auth failure (401), rate limits (429), or no results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • server.py:57-66 (registration)
    Tool registration decorator defining the name, description annotations, and hints for the spotify_get_recommendations tool.
    @mcp.tool(
        name="spotify_get_recommendations",
        annotations={
            "title": "Get Spotify Track Recommendations",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True,
        },
    )
  • The core handler function that validates inputs, constructs Spotify recommendations API request, fetches data, formats output as markdown or JSON, and handles errors.
    async def spotify_get_recommendations(params: GetRecommendationsInput) -> str:
        """Get track recommendations from Spotify based on seed tracks, artists, or genres.
    
        Generates personalized recommendations using up to 5 seeds (any combination) with
        tunable audio features (energy, danceability, valence, tempo).
    
        Args:
            - seed_tracks/seed_artists/seed_genres: Up to 5 total seeds (track IDs, artist IDs, or genre names)
            - limit: Results to return, 1-100 (default: 20)
            - min/max/target audio features: Energy, danceability, valence (0.0-1.0), tempo (BPM)
            - response_format: 'markdown' (formatted) or 'json' (structured data)
    
        Returns:
            Markdown: Numbered list with track details (name, artists, album, duration, ID, popularity)
            JSON: {"total": N, "tracks": [{id, name, artists, album, duration_ms, popularity, uri, external_urls}]}
    
        Examples:
            - "Find energetic workout music" -> seed_genres=['electronic'], target_energy=0.9
            - "Songs like this track" -> seed_tracks=['track_id']
            - "Happy danceable songs" -> target_valence=0.8, target_danceability=0.8
    
        Errors: Returns error for no seeds, >5 seeds, auth failure (401), rate limits (429), or no results.
        """
        try:
            # Validate at least one seed is provided
            total_seeds = (
                len(params.seed_tracks or [])
                + len(params.seed_artists or [])
                + len(params.seed_genres or [])
            )
            if total_seeds == 0:
                return (
                    "Error: At least one seed (track, artist, or genre) must be provided."
                )
            if total_seeds > 5:
                return "Error: Maximum of 5 seeds total allowed across all seed types."
    
            # Build query parameters
            query_params: dict = {"limit": params.limit}
    
            if params.seed_tracks:
                query_params["seed_tracks"] = ",".join(params.seed_tracks)
            if params.seed_artists:
                query_params["seed_artists"] = ",".join(params.seed_artists)
            if params.seed_genres:
                query_params["seed_genres"] = ",".join(params.seed_genres)
    
            # Add tunable attributes
            for attr in [
                "min_energy",
                "max_energy",
                "target_energy",
                "min_danceability",
                "max_danceability",
                "target_danceability",
                "min_valence",
                "max_valence",
                "target_valence",
                "min_tempo",
                "max_tempo",
                "target_tempo",
            ]:
                value = getattr(params, attr)
                if value is not None:
                    query_params[attr] = value
    
            # Make API request
            data = await make_spotify_request("recommendations", params=query_params)
    
            tracks = data.get("tracks", [])
    
            if not tracks:
                return "No recommendations found for the provided seeds and parameters."
    
            # Format response
            if params.response_format == ResponseFormat.MARKDOWN:
                lines = ["# Spotify Track Recommendations\n"]
    
                for i, track in enumerate(tracks, 1):
                    lines.append(f"## {i}. {format_track_markdown(track)}\n")
    
                result = "\n".join(lines)
                truncation_msg = check_character_limit(result, tracks)
                if truncation_msg:
                    tracks = tracks[: len(tracks) // 2]
                    lines = ["# Spotify Track Recommendations\n", truncation_msg]
                    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": len(tracks), "tracks": tracks},
                    indent=2,
                )
    
        except Exception as e:
            return handle_spotify_error(e)
  • Pydantic BaseModel defining the input schema for the tool, with fields for seeds (tracks/artists/genres), limit, tunable audio features (energy, danceability, valence, tempo), response format, and seed validation.
    class GetRecommendationsInput(BaseModel):
        """Input model for getting track recommendations."""
    
        model_config = ConfigDict(str_strip_whitespace=True, validate_assignment=True)
    
        seed_tracks: list[str] | None = Field(
            default=None,
            description="List of Spotify track IDs to use as seeds (e.g., ['3n3Ppam7vgaVa1iaRUc9Lp'])",
            max_length=5,
        )
        seed_artists: list[str] | None = Field(
            default=None,
            description="List of Spotify artist IDs to use as seeds (e.g., ['4NHQUGzhtTLFvgF5SZesLK'])",
            max_length=5,
        )
        seed_genres: list[str] | None = Field(
            default=None,
            description="List of genre names to use as seeds (e.g., ['pop', 'rock'])",
            max_length=5,
        )
        limit: int | None = Field(
            default=20,
            description="Number of recommendations to return",
            ge=1,
            le=100,
        )
        min_energy: float | None = Field(
            default=None, description="Minimum energy (0.0-1.0)", ge=0.0, le=1.0
        )
        max_energy: float | None = Field(
            default=None, description="Maximum energy (0.0-1.0)", ge=0.0, le=1.0
        )
        target_energy: float | None = Field(
            default=None, description="Target energy (0.0-1.0)", ge=0.0, le=1.0
        )
        min_danceability: float | None = Field(
            default=None, description="Minimum danceability (0.0-1.0)", ge=0.0, le=1.0
        )
        max_danceability: float | None = Field(
            default=None, description="Maximum danceability (0.0-1.0)", ge=0.0, le=1.0
        )
        target_danceability: float | None = Field(
            default=None, description="Target danceability (0.0-1.0)", ge=0.0, le=1.0
        )
        min_valence: float | None = Field(
            default=None, description="Minimum valence/positivity (0.0-1.0)", ge=0.0, le=1.0
        )
        max_valence: float | None = Field(
            default=None, description="Maximum valence/positivity (0.0-1.0)", ge=0.0, le=1.0
        )
        target_valence: float | None = Field(
            default=None, description="Target valence/positivity (0.0-1.0)", ge=0.0, le=1.0
        )
        min_tempo: float | None = Field(
            default=None, description="Minimum tempo in BPM", ge=0.0
        )
        max_tempo: float | None = Field(
            default=None, description="Maximum tempo in BPM", ge=0.0
        )
        target_tempo: float | None = Field(
            default=None, description="Target tempo in BPM", ge=0.0
        )
        response_format: ResponseFormat = Field(
            default=ResponseFormat.MARKDOWN,
            description="Output format: 'markdown' for human-readable or 'json' for machine-readable",
        )
    
        @field_validator("seed_tracks", "seed_artists", "seed_genres")
        @classmethod
        def validate_seeds(cls, v: list[str] | None) -> list[str] | None:
            """Validate seed lists."""
            if v is not None and len(v) > 5:
                raise ValueError("Maximum 5 seeds allowed per type")
            return v
Behavior4/5

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

Annotations already indicate read-only, open-world, idempotent, and non-destructive behavior, but the description adds valuable context beyond this: it specifies error conditions (e.g., no seeds, >5 seeds, auth failure, rate limits), output formats, and example use cases, enhancing the agent's understanding without contradicting annotations.

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 sections for purpose, args, returns, examples, and errors, making it easy to scan. It is appropriately sized, but could be slightly more concise by avoiding repetition of parameter lists that are partially covered in the schema.

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, rich input schema, annotations, and output schema, the description is complete: it covers purpose, usage, parameters, return formats, examples, and errors, providing all necessary context for an agent to invoke the tool correctly without needing to rely solely on structured fields.

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?

The input schema has 0% description coverage, but the description compensates by explaining key parameters like seed types, limit, audio features, and response_format with examples. However, it does not cover all parameters (e.g., min/max/target for each audio feature are listed but not fully detailed), leaving some gaps in semantics.

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 ('Get track recommendations') and resources ('from Spotify'), and distinguishes it from siblings by focusing on personalized recommendations based on seeds and audio features, unlike search or playlist tools.

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 for when to use this tool (e.g., 'Find energetic workout music' or 'Songs like this track'), but does not explicitly state when not to use it or name alternatives among sibling tools, such as spotify_find_similar_tracks or spotify_search_tracks.

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