Skip to main content
Glama
igorgarbuz

Spotify MCP Node Server

by igorgarbuz

searchSpotify

Search Spotify music and content using keywords and filters for artists, tracks, albums, playlists, genres, years, or popularity tags to find specific items.

Instructions

Search Spotify by keyword and field filters (e.g. artist, track, playlist, tag:new, tag:hipster) and return items of the given type

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesFull Spotify search string combining: - free-text keywords (e.g. “remaster”), - field filters: artist:<name>, track:<name>, album:<name>, year:<YYYY> or <YYYY-YYYY>, genre:<name>. The album, artist and year filters can be used for album and track types. The genre filter can only be used for track type. Special filter tag:hipster (bottom 10% popularity) can be used with track and album types. All separated by spaces. Example: "tag:hipster artist:Queen remaster".
typeYesWhich item type to return: track, album or playlist
limitNoMax number of results to return (1-50)
offsetNoThe index of the first item to return. Defaults to 0

Implementation Reference

  • The core handler function for searchSpotify tool. It takes query, type (track/album/playlist), limit, offset; calls Spotify search API via handleSpotifyRequest; formats results into numbered list with artists, duration/ID; returns markdown text or error.
    handler: async (args, extra: SpotifyHandlerExtra) => {
      const { query, type, limit = 20, offset = 0 } = args;
    
      try {
        const results = await handleSpotifyRequest(async (spotifyApi) => {
          return await spotifyApi.search(
            query,
            [type],
            undefined,
            limit as MaxInt<50>,
            offset,
          );
        });
    
        let formattedResults = '';
    
        if (type === 'track' && results.tracks) {
          formattedResults = results.tracks.items
            .map((track, i) => {
              const artists = track.artists.map((a) => a.name).join(', ');
              const duration = formatDuration(track.duration_ms);
              return `${i + 1}. "${
                track.name
              }" by ${artists} (${duration}) - ID: ${track.id}`;
            })
            .join('\n');
        } else if (type === 'album' && results.albums) {
          formattedResults = results.albums.items
            .map((album, i) => {
              const artists = album.artists.map((a) => a.name).join(', ');
              return `${i + 1}. "${album.name}" by ${artists} - ID: ${album.id}`;
            })
            .join('\n');
        } else if (type === 'playlist' && results.playlists) {
          formattedResults = results.playlists.items
            .map((playlist, i) => {
              return `${i + 1}. "${playlist?.name ?? 'Unknown Playlist'} (${
                playlist?.description ?? 'No description'
              } tracks)" by ${playlist?.owner?.display_name} - ID: ${
                playlist?.id
              }`;
            })
            .join('\n');
        }
    
        return {
          content: [
            {
              type: 'text',
              text:
                formattedResults.length > 0
                  ? `# Search results for "${query}" (type: ${type})\n\n${formattedResults}`
                  : `No ${type} results found for "${query}"`,
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error searching for ${type}s: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
        };
      }
    },
  • Input schema using Zod for validation: query (string with search syntax), type (enum track/album/playlist), optional limit (1-50), offset (0-1000). Includes detailed descriptions.
    name: 'searchSpotify',
    description:
      'Search Spotify by keyword and field filters (e.g. artist, track, playlist, tag:new, tag:hipster) and return items of the given type',
    schema: {
      query: z
        .string()
        .describe(
          [
            'Full Spotify search string combining:',
            '- free-text keywords (e.g. “remaster”),',
            '- field filters: artist:<name>, track:<name>, album:<name>,',
            '  year:<YYYY> or <YYYY-YYYY>, genre:<name>.',
            'The album, artist and year filters can be used for album and track types.',
            'The genre filter can only be used for track type.',
            'Special filter tag:hipster (bottom 10% popularity) can be used with track and album types.',
            'All separated by spaces. Example: "tag:hipster artist:Queen remaster".',
          ].join(' '),
        ),
      type: z
        .enum(['track', 'album', 'playlist'])
        .describe('Which item type to return: track, album or playlist'),
      limit: z
        .number()
        .min(1)
        .max(50)
        .optional()
        .describe('Max number of results to return (1-50)'),
      offset: z
        .number()
        .min(0)
        .max(1000)
        .optional()
        .describe('The index of the first item to return. Defaults to 0'),
    },
  • src/index.ts:12-14 (registration)
    Registers the searchSpotify tool (included in readTools) with the MCP server by calling server.tool() for each tool in the combined list from playTools, readTools, writeTools.
    [...playTools, ...readTools, ...writeTools].forEach((tool) => {
      server.tool(tool.name, tool.description, tool.schema, tool.handler);
    });
  • src/read.ts:521-522 (registration)
    Adds searchSpotify to the readTools array which is later imported and registered in index.ts.
    export const readTools = [
      searchSpotify,
  • Helper function used in the handler to execute Spotify API calls with automatic access token refresh on expiry or 401 errors.
    export async function handleSpotifyRequest<T>(
      action: (spotifyApi: SpotifyApi) => Promise<T>,
    ): Promise<T> {
      let config = loadSpotifyConfig();
      let spotifyApi: SpotifyApi;
      try {
        // If token is expired, refresh first
        if (
          config.accessTokenExpiresAt &&
          config.accessTokenExpiresAt - Date.now() < 60 * 1000
        ) {
          config = await refreshAccessToken(config);
        }
        spotifyApi = createSpotifyApi();
        return await action(spotifyApi);
      } catch (error: any) {
        // If 401, try refresh once
        if (error?.status === 401 || /401|unauthorized/i.test(error?.message)) {
          config = await refreshAccessToken(config);
          cachedSpotifyApi = null;
          spotifyApi = createSpotifyApi();
          return await action(spotifyApi);
        }
        // Skip JSON parsing errors as these are actually successful operations
        const errorMessage = error instanceof Error ? error.message : String(error);
        if (
          errorMessage.includes('Unexpected token') ||
          errorMessage.includes('Unexpected non-whitespace character') ||
          errorMessage.includes('Exponent part is missing a number in JSON')
        ) {
          return undefined as T;
        }
        // Rethrow other errors
        throw error;
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions returning items but doesn't describe the response format, pagination behavior, rate limits, authentication requirements, or error conditions. For a search tool with no annotation coverage, this leaves significant gaps in understanding how the tool behaves beyond basic functionality.

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 a single, efficient sentence that communicates the core functionality without unnecessary words. It's appropriately sized for the tool's complexity and front-loads the essential information about searching with filters and returning typed results.

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

Completeness3/5

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

Given the tool's moderate complexity (4 parameters, 100% schema coverage, no output schema, no annotations), the description provides basic context but lacks details about response format, error handling, and behavioral constraints. It's adequate as a minimum viable description but has clear gaps in completeness for a search tool that likely returns structured data.

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 already documents all parameters thoroughly. The description adds minimal value beyond the schema, mentioning 'keyword and field filters' and 'return items of the given type' which are already covered in the schema's parameter descriptions. 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 tool searches Spotify using keyword and field filters and returns items of a specified type. It specifies the verb 'search' and resource 'Spotify', but doesn't explicitly differentiate from sibling tools like 'getUserPlaylists' or 'getRecentlyPlayed' which also retrieve Spotify content. The purpose is clear but lacks sibling differentiation.

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 searching across multiple content types (tracks, albums, playlists) with flexible filtering, suggesting it's for general discovery rather than retrieving specific user data like 'getUserPlaylists'. However, it doesn't explicitly state when to use this tool versus alternatives or mention any exclusions, leaving some ambiguity about its specific use cases.

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

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