Skip to main content
Glama
igorgarbuz

Spotify MCP Node Server

by igorgarbuz

playMusic

Play Spotify tracks, albums, artists, or playlists by providing a URI, ID, or specifying the content type to initiate music playback on your device.

Instructions

Start playing a Spotify track, album, artist, or playlist

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
uriNoThe Spotify URI to play (overrides type and id)
typeNoThe type of item to play
idNoThe Spotify ID of the item to play
deviceIdNoThe Spotify device ID to play on

Implementation Reference

  • The handler function that destructures input args, validates them, constructs Spotify URI if needed, and uses handleSpotifyRequest to interact with Spotify player API for playback.
    handler: async (args, extra: SpotifyHandlerExtra) => {
      const { uri, type, id, deviceId } = args;
    
      if (!uri && (!type || !id)) {
        return {
          content: [
            {
              type: 'text',
              text: 'Error: Must provide either a URI or both a type and ID',
              isError: true,
            },
          ],
        };
      }
    
      let spotifyUri = uri;
      if (!spotifyUri && type && id) {
        spotifyUri = `spotify:${type}:${id}`;
      }
    
      await handleSpotifyRequest(async (spotifyApi) => {
        const device = deviceId || '';
    
        if (!spotifyUri) {
          await spotifyApi.player.startResumePlayback(device);
          return;
        }
    
        if (type === 'track') {
          await spotifyApi.player.startResumePlayback(device, undefined, [
            spotifyUri,
          ]);
        } else {
          await spotifyApi.player.startResumePlayback(device, spotifyUri);
        }
      });
    
      return {
        content: [
          {
            type: 'text',
            text: `Started playing ${type || 'music'} ${id ? `(ID: ${id})` : ''}`,
          },
        ],
      };
    },
  • Zod schema for playMusic tool inputs: optional uri, type (track/album/artist/playlist), id, and deviceId.
    schema: {
      uri: z
        .string()
        .optional()
        .describe('The Spotify URI to play (overrides type and id)'),
      type: z
        .enum(['track', 'album', 'artist', 'playlist'])
        .optional()
        .describe('The type of item to play'),
      id: z.string().optional().describe('The Spotify ID of the item to play'),
      deviceId: z
        .string()
        .optional()
        .describe('The Spotify device ID to play on'),
    },
  • src/index.ts:12-14 (registration)
    Registers all tools (including playMusic from playTools) to the MCP server by calling server.tool() for each.
    [...playTools, ...readTools, ...writeTools].forEach((tool) => {
      server.tool(tool.name, tool.description, tool.schema, tool.handler);
    });
  • src/player.ts:130-130 (registration)
    Exports playTools array containing the playMusic tool for use in main server registration.
    export const playTools = [playMusic, playbackAction];
  • Helper utility wrapped around Spotify API calls in the playMusic handler; manages authentication, token refresh, and error retry.
    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 the full burden of behavioral disclosure. It states the tool starts playback but doesn't mention whether it requires specific permissions (e.g., Spotify Premium), what happens if no device is active, or if it overrides current playback. This leaves significant gaps for a mutation tool.

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 front-loads the core purpose without unnecessary words. Every part of the sentence directly contributes to understanding what the tool does.

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 mutation tool with no annotations and no output schema, the description is incomplete. It doesn't cover behavioral aspects like error conditions, authentication needs, or what the response looks like (e.g., success confirmation or playback state). Given the complexity of media playback, more context is needed.

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 description mentions playing 'track, album, artist, or playlist', which aligns with the 'type' parameter's enum values. However, with 100% schema description coverage, the input schema already fully documents all 4 parameters, so the description adds minimal value beyond reinforcing the 'type' options.

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 action ('Start playing') and the resource ('a Spotify track, album, artist, or playlist'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'playbackAction' or 'addToQueue', which could handle similar playback scenarios.

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 like 'playbackAction' for other playback controls or 'addToQueue' for queuing without immediate playback. It also doesn't mention prerequisites such as needing an active Spotify device or authentication context.

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