Skip to main content
Glama
hrishi0102

Spotify MCP Server

by hrishi0102

search-tracks

Search and retrieve Spotify tracks by entering a query, with options to limit the number of results returned, enabling targeted music discovery and access.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoNumber of results to return
queryYesSearch query for tracks

Implementation Reference

  • The handler function for the 'search-tracks' tool. It retrieves a valid Spotify access token, performs a search query to the Spotify API for tracks, processes the response to extract relevant track information (id, name, artist, album, uri), and returns the results as a formatted JSON string in the MCP response format. Handles errors appropriately.
    async ({ query, limit }) => {
      try {
        const accessToken = await getValidAccessToken();
    
        const response = await fetch(
          `https://api.spotify.com/v1/search?q=${encodeURIComponent(
            query
          )}&type=track&limit=${limit}`,
          {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          }
        );
    
        const data = (await response.json()) as any;
    
        if (!response.ok) {
          return {
            content: [
              {
                type: "text",
                text: `Error searching tracks: ${JSON.stringify(data)}`,
              },
            ],
            isError: true,
          };
        }
    
        const tracks = data.tracks.items.map((track: any) => ({
          id: track.id,
          name: track.name,
          artist: track.artists.map((artist: any) => artist.name).join(", "),
          album: track.album.name,
          uri: track.uri,
        }));
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(tracks, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Failed to search tracks: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema defining the input parameters for the search-tracks tool: a required 'query' string and an optional 'limit' number (1-50, default 10).
    {
      query: z.string().describe("Search query for tracks"),
      limit: z
        .number()
        .min(1)
        .max(50)
        .default(10)
        .describe("Number of results to return"),
    },
  • Registration of the 'search-tracks' tool on the MCP server using server.tool(), including name, input schema, and handler function.
    server.tool(
      "search-tracks",
      {
        query: z.string().describe("Search query for tracks"),
        limit: z
          .number()
          .min(1)
          .max(50)
          .default(10)
          .describe("Number of results to return"),
      },
      async ({ query, limit }) => {
        try {
          const accessToken = await getValidAccessToken();
    
          const response = await fetch(
            `https://api.spotify.com/v1/search?q=${encodeURIComponent(
              query
            )}&type=track&limit=${limit}`,
            {
              headers: {
                Authorization: `Bearer ${accessToken}`,
              },
            }
          );
    
          const data = (await response.json()) as any;
    
          if (!response.ok) {
            return {
              content: [
                {
                  type: "text",
                  text: `Error searching tracks: ${JSON.stringify(data)}`,
                },
              ],
              isError: true,
            };
          }
    
          const tracks = data.tracks.items.map((track: any) => ({
            id: track.id,
            name: track.name,
            artist: track.artists.map((artist: any) => artist.name).join(", "),
            album: track.album.name,
            uri: track.uri,
          }));
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(tracks, null, 2),
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to search tracks: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • Helper function to obtain a valid Spotify access token, checking current token validity and refreshing it if expired using the refresh token.
    async function getValidAccessToken() {
      if (!spotifyAuthInfo.accessToken || !spotifyAuthInfo.refreshToken) {
        throw new Error(
          "No access token available. Please set credentials first using the set-spotify-credentials tool."
        );
      }
    
      try {
        // Try using current token
        const response = await fetch("https://api.spotify.com/v1/me", {
          headers: {
            Authorization: `Bearer ${spotifyAuthInfo.accessToken}`,
          },
        });
    
        // If token works, return it
        if (response.ok) {
          return spotifyAuthInfo.accessToken;
        }
    
        console.error("Access token expired, refreshing...");
    
        // If token doesn't work, refresh it
        const refreshResponse = await fetch(
          "https://accounts.spotify.com/api/token",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              Authorization:
                "Basic " +
                Buffer.from(
                  spotifyAuthInfo.clientId + ":" + spotifyAuthInfo.clientSecret
                ).toString("base64"),
            },
            body: new URLSearchParams({
              grant_type: "refresh_token",
              refresh_token: spotifyAuthInfo.refreshToken,
            }),
          }
        );
    
        const data = (await refreshResponse.json()) as any;
    
        if (data.access_token) {
          console.error("Successfully refreshed access token");
          spotifyAuthInfo.accessToken = data.access_token;
          return spotifyAuthInfo.accessToken;
        }
    
        throw new Error("Failed to refresh access token");
      } catch (error) {
        throw new Error(
          "Error with access token: " +
            (error instanceof Error ? error.message : String(error))
        );
      }
    }
  • Identical handler implementation for 'search-tracks' in the stdio transport version of the server.
    async ({ query, limit }) => {
      try {
        const accessToken = await getValidAccessToken();
    
        const response = await fetch(
          `https://api.spotify.com/v1/search?q=${encodeURIComponent(
            query
          )}&type=track&limit=${limit}`,
          {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          }
        );
    
        const data = (await response.json()) as any;
    
        if (!response.ok) {
          return {
            content: [
              {
                type: "text",
                text: `Error searching tracks: ${JSON.stringify(data)}`,
              },
            ],
            isError: true,
          };
        }
    
        const tracks = data.tracks.items.map((track: any) => ({
          id: track.id,
          name: track.name,
          artist: track.artists.map((artist: any) => artist.name).join(", "),
          album: track.album.name,
          uri: track.uri,
        }));
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(tracks, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Failed to search tracks: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

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

Parameters1/5

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

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

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

Usage Guidelines1/5

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

Tool has no description.

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

Related 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/hrishi0102/spotifyyy-mcp'

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