add_to_playlist
Add Spotify tracks to playlists using track URIs and playlist IDs for music organization and management.
Instructions
Add tracks to a playlist
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| playlist_id | Yes | Spotify playlist ID | |
| track_uris | Yes | Array of Spotify track URIs to add |
Implementation Reference
- src/index.ts:501-518 (handler)Handler for add_to_playlist tool - makes POST request to Spotify API to add tracks to a playlist using playlist_id and track_uris parameters
case "add_to_playlist": { await spotifyRequest( `/playlists/${args.playlist_id}/tracks`, "POST", { uris: args.track_uris, } ); return { content: [ { type: "text", text: `➕ Added ${(args.track_uris as string[]).length} track(s) to playlist!`, }, ], }; } - src/index.ts:220-239 (schema)Schema definition for add_to_playlist tool - defines input parameters: playlist_id (string, required) and track_uris (array of strings, required)
name: "add_to_playlist", description: "Add tracks to a playlist", inputSchema: { type: "object", properties: { playlist_id: { type: "string", description: "Spotify playlist ID", }, track_uris: { type: "array", items: { type: "string", }, description: "Array of Spotify track URIs to add", }, }, required: ["playlist_id", "track_uris"], }, }, - src/index.ts:54-74 (helper)Helper function spotifyRequest that handles authentication and makes HTTP requests to Spotify API endpoints
async function spotifyRequest(endpoint: string, method = "GET", data?: any) { const token = await getAccessToken(); try { const response = await axios({ method, url: `https://api.spotify.com/v1${endpoint}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data, }); return response.data; } catch (error: any) { if (error.response) { throw new Error(`Spotify API Error: ${error.response.data.error?.message || error.response.statusText}`); } throw new Error(`Network Error: ${error.message}`); } } - src/index.ts:24-51 (helper)Helper function getAccessToken that manages OAuth token refresh for Spotify API authentication
async function getAccessToken(): Promise<string> { if (accessToken && Date.now() < tokenExpiresAt) { return accessToken; } try { const params = new URLSearchParams(); params.append("grant_type", "refresh_token"); params.append("refresh_token", REFRESH_TOKEN!); const response = await axios.post( "https://accounts.spotify.com/api/token", params, { headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`, }, } ); accessToken = response.data.access_token; tokenExpiresAt = Date.now() + response.data.expires_in * 1000; return accessToken; } catch (error: any) { throw new Error(`Failed to get access token: ${error.message}`); } }