Skip to main content
Glama
hrishi0102

Spotify MCP Server

by hrishi0102

create-playlist

Use this feature to design and manage personalized playlists on Spotify. Input a name and optional description to generate a custom playlist tailored to your music preferences.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionNoDescription of the playlist
nameYesName of the playlist

Implementation Reference

  • The handler function that implements the create-playlist tool logic by calling Spotify API to create a new playlist.
      async ({ name, description = "" }) => {
        try {
          const accessToken = await getValidAccessToken();
    
          // Get user ID
          const userResponse = await fetch("https://api.spotify.com/v1/me", {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          });
    
          const userData = (await userResponse.json()) as any;
          const userId = userData.id;
    
          // Create playlist
          const response = await fetch(
            `https://api.spotify.com/v1/users/${userId}/playlists`,
            {
              method: "POST",
              headers: {
                Authorization: `Bearer ${accessToken}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                name,
                description,
                public: false,
              }),
            }
          );
    
          const data = (await response.json()) as any;
    
          if (!response.ok) {
            return {
              content: [
                {
                  type: "text",
                  text: `Error creating playlist: ${JSON.stringify(data)}`,
                },
              ],
              isError: true,
            };
          }
    
          return {
            content: [
              {
                type: "text",
                text: `Playlist created successfully!\nName: ${data.name}\nID: ${data.id}\nURL: ${data.external_urls.spotify}`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to create playlist: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • Zod schema defining input parameters for the create-playlist tool: name (required string) and optional description.
    {
      name: z.string().describe("Name of the playlist"),
      description: z.string().optional().describe("Description of the playlist"),
    },
  • Registration of the create-playlist tool with McpServer using server.tool, including schema and inline handler.
    server.tool(
      "create-playlist",
      {
        name: z.string().describe("Name of the playlist"),
        description: z.string().optional().describe("Description of the playlist"),
      },
      async ({ name, description = "" }) => {
        try {
          const accessToken = await getValidAccessToken();
    
          // Get user ID
          const userResponse = await fetch("https://api.spotify.com/v1/me", {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          });
    
          const userData = (await userResponse.json()) as any;
          const userId = userData.id;
    
          // Create playlist
          const response = await fetch(
            `https://api.spotify.com/v1/users/${userId}/playlists`,
            {
              method: "POST",
              headers: {
                Authorization: `Bearer ${accessToken}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                name,
                description,
                public: false,
              }),
            }
          );
    
          const data = (await response.json()) as any;
    
          if (!response.ok) {
            return {
              content: [
                {
                  type: "text",
                  text: `Error creating playlist: ${JSON.stringify(data)}`,
                },
              ],
              isError: true,
            };
          }
    
          return {
            content: [
              {
                type: "text",
                text: `Playlist created successfully!\nName: ${data.name}\nID: ${data.id}\nURL: ${data.external_urls.spotify}`,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Failed to create playlist: ${
                  error instanceof Error ? error.message : String(error)
                }`,
              },
            ],
            isError: true,
          };
        }
      }
    );
    
    // Add tracks to playlist
  • Helper function to obtain a valid Spotify access token, refreshing if necessary.
    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))
        );
      }
    }
  • Variant handler for create-playlist in OAuth HTTP server, supports public playlist option and uses handleSpotifyTool for token management.
    async ({ name, description = "", public: isPublic }) => {
      return await handleSpotifyTool(sessionId, async (accessToken) => {
        // Get user ID first
        const userResponse = await fetch("https://api.spotify.com/v1/me", {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        });
    
        const userData = await userResponse.json();
        const userId = userData.id;
    
        // Create playlist
        const response = await fetch(
          `https://api.spotify.com/v1/users/${userId}/playlists`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${accessToken}`,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              name,
              description,
              public: isPublic,
            }),
          }
        );
    
        const data = await response.json();
    
        if (!response.ok) {
          throw new Error(
            `Spotify API error: ${data.error?.message || "Unknown error"}`
          );
        }
    
        return {
          content: [
            {
              type: "text",
              text: `✅ Playlist created successfully!\n\n**${data.name}**\nID: ${data.id}\n🔗 [Open in Spotify](${data.external_urls.spotify})`,
            },
          ],
        };
      });
    }
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/spotify-mcp'

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