Skip to content
Back to search

apple-music

Apple Music integration — AppleScript (local Music.app) and the Apple Music API / web player (cross-platform library, playlists, playback, and queue)

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/epheterson--applemusic-mcp/badge.svg)](/listings/epheterson--applemusic-mcp)

HTML

<a href="/listings/epheterson--applemusic-mcp"><img src="/api/listings/epheterson--applemusic-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Requirements:** Python 3.10+, plus a Mac or an Apple Music subscription. On a Mac nothing else is needed. The Chrome web player (Windows, Linux, or opt-in on a Mac) needs [Google Chrome](https://www.google.com/chrome/).

**Claude Code**, one line:

claude mcp add "Apple Music" -- uvx applemusic-mcp serve --level music

**Claude Desktop / Cursor / Cline / Windsurf**, install once, then add the config block:

pipx install applemusic-mcp        # or: pip install applemusic-mcp
playwright install chromium        # the Chrome web player: Windows/Linux, or a Mac with the [browser] extra
{
  "mcpServers": {
    "Apple Music": {
      "command": "applemusic-mcp",
      "args": ["serve", "--level", "music"]
    }
  }
}

Change `music` to `api` or `web` to [unlock more](#choose-how-much-it-can-reach); on Windows or Linux start at `api`, since `music` needs a Mac. Config file locations, the Chrome web player on a Mac, and source installs: [configuration](https://github.com/epheterson/applemusic-mcp/blob/main/docs/configuration.md).

Restart your client and try *"List my Apple Music playlists"* or *"Play my favorites."* On macOS the local library and playback work immediately. To add catalog music or run on any OS, sign in.

Sign in

Needed for `api` and `web`. Your password never touches this tool, and sign-in persists.

applemusic-mcp login            # Mac: reads your signed-in Safari. Windows/Linux: opens Chrome
applemusic-mcp status           # verify

On a Mac, sign in at [music.apple.com](https://music.apple.com) in Safari first and turn on Safari's **Develop → Allow JavaScript from Apple Events** once; `login` tells you exactly what's missing. For bulk work (playlist imports, library migrations), use your own Apple developer token to avoid the shared rate limit. Details, the Chrome and developer-token paths, and which API each write uses: [signing in](https://github.com/epheterson/applemusic-mcp/blob/main/docs/sign-in.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 923 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: apple-music
  3. version: 0.22.1
  4. description: Apple Music integration — AppleScript (local Music.app) and the Apple Music API / web player (cross-platform library, playlists, playback, and queue)
  5. ---
  6. # Apple Music Integration
  7. Guide for integrating with Apple Music. Three approaches: AppleScript (direct control), UI automation (catalog without API), and MusicKit API (cross-platform).
  8. ## When to Use
  9. Invoke when users ask to:
  10. - Manage playlists (create, add/remove tracks, list)
  11. - Control playback (play, pause, skip, volume)
  12. - Play an Apple Music URL (album, playlist, or song)
  13. - Search catalog or library
  14. - Add songs to library
  15. - Access listening history or recommendations
  16. ## Permission Levels (MCP server)
  17. The applemusic-mcp server runs at a level the user picks in their MCP client config: `music` (Music.app only), `api` (+ Apple's music APIs), `web` (+ web players), or `full` (everything), optionally with `--allow-ui` (Accessibility clicks). If the server refuses something because of its level, tell the user what it needs and where to change it. Don't work around the refusal with `osascript`, a browser, or anything in this guide: the user chose that limit.
  18. ## Critical Rule: Library-First Workflow
  19. **You CANNOT add catalog songs directly to playlists.**
  20. Songs must be in the user's library first:
  21. - ❌ Catalog ID → Playlist (fails)
  22. - ✅ Catalog ID → Library → Playlist (works)
  23. **Why:** Playlists use library IDs (`i.abc123`), not catalog IDs (`1234567890`).
  24. This applies to both AppleScript and API approaches.
  25. ---
  26. # AppleScript (macOS)
  27. Zero setup. Works immediately with the Music app.
  28. **Run via Bash:**
  29. ```bash
  30. osascript -e 'tell application "Music" to playpause'
  31. osascript -e 'tell application "Music" to return name of current track'
  32. ```
  33. **Multi-line scripts:**
  34. ```bash
  35. osascript <<'EOF'
  36. tell application "Music"
  37. set t to current track
  38. return {name of t, artist of t}
  39. end tell
  40. EOF
  41. ```
  42. ## Available Operations
  43. | Category | Operations |
  44. |----------|------------|
  45. | **Playback** | play, pause, stop, resume, next track, previous track, fast forward, rewind, play URL |
  46. | **Player State** | player position, player state, sound volume, mute, shuffle enabled/mode, song repeat |
  47. | **Current Track** | name, artist, album, duration, time, rating, loved, disliked, genre, year, track number |
  48. | **Library** | search, list tracks, get track properties, set ratings |
  49. | **Playlists** | list, create, delete, rename, add tracks, remove tracks, get tracks |
  50. | **AirPlay** | list devices, select device, current device |
  51. ## Track Properties (Read)
  52. ```applescript
  53. tell application "Music"
  54. set t to current track
  55. -- Basic info
  56. name of t -- "Hey Jude"
  57. artist of t -- "The Beatles"
  58. album of t -- "1 (Remastered)"
  59. album artist of t -- "The Beatles"
  60. composer of t -- "Lennon-McCartney"
  61. genre of t -- "Rock"
  62. year of t -- 1968
  63. -- Timing
  64. duration of t -- 431.0 (seconds)
  65. time of t -- "7:11" (formatted)
  66. start of t -- start time in seconds
  67. finish of t -- end time in seconds
  68. -- Track info
  69. track number of t -- 21
  70. track count of t -- 27
  71. disc number of t -- 1
  72. disc count of t -- 1
  73. -- Ratings
  74. rating of t -- 0-100 (20 per star)
  75. loved of t -- true/false
  76. disliked of t -- true/false
  77. -- Content rating. DO NOT trust this for filtering.
  78. -- On Apple Music (cloud) tracks this property is unset, and reading it
  79. -- RAISES "A descriptor type mismatch occurred" rather than returning
  80. -- false. Catching that and defaulting to false is what turns "I could
  81. -- not tell" into "this is clean": on a real 463-track playlist Music.app
  82. -- yielded zero explicit tracks where the catalog rated eight of them
  83. -- explicit. If a caller asked for clean content, resolve the rating
  84. -- against the catalog (`contentRating == "explicit"`, matching on name
  85. -- AND artist) and report anything you could not verify as unknown.
  86. explicit of t -- true/false, RAISES on most cloud tracks
  87. -- Playback
  88. played count of t -- 42
  89. played date of t -- date last played
  90. skipped count of t -- 3
  91. skipped date of t -- date last skipped
  92. -- IDs
  93. persistent ID of t -- "ABC123DEF456"
  94. database ID of t -- 12345
  95. end tell
  96. ```
  97. ## Track Properties (Writable)
  98. ```applescript
  99. tell application "Music"
  100. set t to current track
  101. set rating of t to 80 -- 4 stars
  102. set loved of t to true
  103. set disliked of t to false
  104. set name of t to "New Name" -- rename track
  105. set genre of t to "Alternative"
  106. set year of t to 1995
  107. end tell
  108. ```
  109. ## Player State Properties
  110. ```applescript
  111. tell application "Music"
  112. player state -- stopped, playing, paused, fast forwarding, rewinding
  113. player position -- current position in seconds (read/write)
  114. sound volume -- 0-100 (read/write)
  115. mute -- true/false (read/write)
  116. shuffle enabled -- true/false (read/write)
  117. shuffle mode -- songs, albums, groupings
  118. song repeat -- off, one, all (read/write)
  119. current track -- track object
  120. current playlist -- playlist object
  121. current stream URL -- URL if streaming
  122. end tell
  123. ```
  124. ## Playback Commands
  125. ```applescript
  126. tell application "Music"
  127. -- Play controls
  128. play -- play current selection
  129. pause
  130. stop
  131. resume
  132. playpause -- toggle play/pause
  133. next track
  134. previous track
  135. fast forward
  136. rewind
  137. -- Play specific content
  138. play (first track of library playlist 1 whose name contains "Hey Jude")
  139. play user playlist "Road Trip"
  140. -- Settings
  141. set player position to 60 -- seek to 1:00
  142. set sound volume to 50 -- 0-100
  143. set mute to true
  144. set shuffle enabled to true
  145. set song repeat to all -- off, one, all
  146. end tell
  147. ```
  148. ### Matching titles with typographic punctuation / accents
  149. `whose name contains "..."` is **glyph-exact** — unlike Music's native `search`
  150. command, it does *not* fold a straight apostrophe (U+0027) against the curly one
  151. (U+2019) Music often stores, nor accents. So `whose name contains "That's a No
  152. No"` misses a title stored as `That's a No No`. Two robust strategies:
  153. ```applescript
  154. -- 1. Match the quote-free fragments instead of the apostrophe itself.
  155. -- Works regardless of which apostrophe variant is stored or typed.
  156. play (first track of library playlist 1 whose ¬
  157. (name contains "That" and name contains "s a No No"))
  158. -- 2. For accents/ellipsis/anything: bulk-fetch names in ONE Apple Event and
  159. -- fold in-memory. `ignoring punctuation and diacriticals` uses Apple's
  160. -- Unicode tables (curly quotes, ellipses, café≈cafe). Do NOT access
  161. -- `name of t` per-iteration in a loop — that is one Apple Event per track
  162. -- (~17s on a 12k library); fetch the whole list at once (~instant).
  163. tell application "Music"
  164. set allNames to (get name of every track of library playlist 1)
  165. set idx to 0
  166. ignoring punctuation and diacriticals
  167. repeat with i from 1 to (count of allNames)
  168. if ((item i of allNames) as text) contains "Fur Elise" then
  169. set idx to i
  170. exit repeat
  171. end if
  172. end repeat
  173. end ignoring
  174. if idx > 0 then play (track idx of library playlist 1)
  175. end tell
  176. ```
  177. ## Library Queries
  178. ```applescript
  179. tell application "Music"
  180. -- All library tracks
  181. every track of library playlist 1
  182. -- Search by name
  183. tracks of library playlist 1 whose name contains "Beatles"
  184. -- Search by artist
  185. tracks of library playlist 1 whose artist contains "Beatles"
  186. -- Search by album
  187. tracks of library playlist 1 whose album contains "Abbey Road"
  188. -- Combined search
  189. tracks of library playlist 1 whose name contains "Hey" and artist contains "Beatles"
  190. -- By genre
  191. tracks of library playlist 1 whose genre is "Rock"
  192. -- By year
  193. tracks of library playlist 1 whose year is 1969
  194. -- By rating
  195. tracks of library playlist 1 whose rating > 60 -- 3+ stars
  196. -- Favorite (loved) tracks. Music.app renamed Loved -> Favorite and the
  197. -- property with it: newer versions use `favorited`, older use `loved`,
  198. -- and the unsupported name can fail INSIDE a whose-filter with "The
  199. -- variable loved is not defined". Try `whose favorited is true` first,
  200. -- fall back to `whose loved is true`, each wrapped in `try`.
  201. tracks of library playlist 1 whose favorited is true
  202. tracks of library playlist 1 whose loved is true -- legacy Music versions
  203. -- Recently played (sort by played date)
  204. tracks of library playlist 1 whose played date > (current date) - 7 * days
  205. end tell
  206. ```
  207. ## Playlist Operations
  208. ```applescript
  209. tell application "Music"
  210. -- List all playlists
  211. name of every user playlist
  212. -- Get playlist
  213. user playlist "Road Trip"
  214. first user playlist whose name contains "Road"
  215. -- Create playlist
  216. make new user playlist with properties {name:"New Playlist", description:"My playlist"}
  217. -- Delete playlist. Match the name EXACTLY; a `contains` fallback here
  218. -- turns "Work" into "Workout".
  219. delete user playlist "Old Playlist"
  220. -- Rename playlist
  221. set name of user playlist "Old Name" to "New Name"
  222. -- Get playlist tracks
  223. every track of user playlist "Road Trip"
  224. name of every track of user playlist "Road Trip"
  225. -- Get the FIRST N, one Apple Event per property. Read the range off the
  226. -- playlist itself. Do NOT stash the tracks in a variable first --
  227. -- `set t to tracks of pl` materializes a plain list, and a property of a
  228. -- plain list does not distribute: Music raises -1728 and names every
  229. -- track of the playlist in the error message.
  230. set pl to user playlist "Road Trip"
  231. set n to 25
  232. if n > (count of tracks of pl) then set n to (count of tracks of pl)
  233. if n < 1 then return {} -- `tracks 1 thru 0` errors
  234. get name of tracks 1 thru n of pl as list -- `as list`: n=1 returns a
  235. -- bare value, not a list
  236. -- Add track to playlist (must be library track)
  237. set targetPlaylist to user playlist "Road Trip"
  238. set targetTrack to first track of library playlist 1 whose name contains "Hey Jude"
  239. duplicate targetTrack to targetPlaylist
  240. -- Remove track from playlist. `contains` + `first` is a TRAP for anything
  241. -- destructive: it deletes whichever match sorts first, irreversibly.
  242. -- "Love" matches 376 tracks in a real library; "Alice" matches three
  243. -- playlists including a 467-track one. Enumerate first and act only when
  244. -- the target is unambiguous.
  245. set hits to (every track of user playlist "Road Trip" whose name contains "Hey Jude")
  246. if (count of hits) is 1 then
  247. delete (item 1 of hits)
  248. else
  249. -- report the candidates and let the user choose; do not guess
  250. end if
  251. -- Playlist properties
  252. duration of user playlist "Road Trip" -- total duration
  253. time of user playlist "Road Trip" -- formatted duration
  254. count of tracks of user playlist "Road Trip"
  255. end tell
  256. ```
  257. ## AirPlay
  258. ```applescript
  259. tell application "Music"
  260. -- List AirPlay devices
  261. name of every AirPlay device
  262. -- Get current device
  263. current AirPlay devices
  264. -- Set output device
  265. set current AirPlay devices to {AirPlay device "Living Room"}
  266. -- Multiple devices
  267. set current AirPlay devices to {AirPlay device "Living Room", AirPlay device "Kitchen"}
  268. -- Device properties
  269. set d to AirPlay device "Living Room"
  270. name of d
  271. kind of d -- computer, AirPort Express, Apple TV, AirPlay device, Bluetooth device
  272. active of d -- true if playing
  273. available of d -- true if reachable
  274. selected of d -- true if in current devices
  275. sound volume of d -- 0-100
  276. end tell
  277. ```
  278. ## String Escaping
  279. Always escape user input:
  280. ```python
  281. def escape_applescript(s):
  282. return s.replace('\\', '\\\\').replace('"', '\\"')
  283. safe_name = escape_applescript(user_input)
  284. script = f'tell application "Music" to play user playlist "{safe_name}"'
  285. ```
  286. ## Common Failures
  287. osascript stderr messages map to a small set of environmental states. When AppleScript fails, classify before deciding what to tell the user — surfacing the raw stderr is misleading; cascading silently to an API path leaks unrelated errors (e.g. "Developer token not found" when the real problem was Music.app being closed).
  288. | Stderr signal | What it means | What to tell the user |
  289. |---|---|---|
  290. | `(-609)`, `Connection is invalid`, `(-10810)`, `isn't running`, `Can't get application "Music"` | Music.app isn't running or has crashed mid-session | "Music.app isn't running. Open it and retry." |
  291. | `(-1743)`, `Not authorized`, `not allowed assistive access`, `assistive access` | The host process (Claude Desktop, Python CLI, Terminal) hasn't been granted Automation permission for Music | "Open System Settings → Privacy & Security → Automation, find the app running this code, enable the 'Music' toggle." |
  292. | `AppleScript timed out after 30 seconds` | The 30s subprocess timeout fired — Music.app stuck or still launching | "Music.app may be unresponsive — quit and reopen it." |
  293. | `syntax error`, `expected … but found …` | The script itself is malformed (developer bug) | Report the raw error — this is on us, not the user. |
  294. | Anything else | Logic-level error (track not found, playlist empty, etc.) | Surface the raw stderr; safe to cascade to API if a legitimate fallback exists. |
  295. **Don't bare-match `not allowed`** — Music.app emits "operation not allowed on smart playlists" and similar logic-level errors that should NOT classify as Automation-denial. Match the full `not allowed assistive` or `assistive access` phrase.
  296. **Don't gate on `is_available()` alone** — that only checks `darwin + osascript exists`. It can't tell you whether Music.app is running or whether Automation permissions have been granted. The error-categorization above is your only signal for those states.
  297. ## Limitations
  298. - **macOS only** — no Windows/Linux
  299. - **UI features require display** — UI automation won't work headless or with Music.app minimized
  300. - **Music.app must be running** — `is_available()` returns True as soon as `osascript` is on PATH, but every `tell application "Music"` block needs Music.app actually running. First call after a fresh boot may also trigger an Automation-permission prompt the user has to approve once.
  301. ---
  302. # UI Automation (macOS)
  303. > **Add-to-library/playlist UI automation was removed in 0.15.0.** Catalog
  304. > add-to-library and auto_add→playlist run over the **unified Apple Music API**
  305. > (developer token generated **or** sourced from Apple's public web player, plus a
  306. > `media-user-token`). The old UI add path was version-fragile (it broke across
  307. > macOS/Music.app releases, #37). To enable the API path: `applemusic-mcp login`
  308. > (or `login --dev` with a developer token). On **macOS** `login` defaults to reading the
  309. > media-user-token from a signed-in **Safari** — no Chrome/Playwright — provided
  310. > Safari → Settings → Advanced → Develop → "Allow JavaScript from Apple Events" is
  311. > enabled; `login --chrome` uses the Chrome web player instead (needs
  312. > `pip install 'applemusic-mcp[browser]'`). **Off macOS**, `login` opens Chrome
  313. > (Playwright ships by default there). The UI primitives below remain only for
  314. > **playback / play-from-URL** and catalog *search*, not for adding.
  315. >
  316. > **Engines (`mode` pref / per-call `engine=`):** `auto` (default — native Music.app
  317. > for playback, **Safari** for the Up Next queue, the API for data on macOS; Chrome
  318. > off-mac), `native`, `safari`, `chrome`, `api`. The **Safari** engine drives your
  319. > signed-in Safari's MusicKit through the same `do JavaScript` channel (DRM-native,
  320. > no Chrome) for play/control/now_playing/settings and the full queue — so on macOS
  321. > the whole web-player surface works without Playwright. Using the `queue` makes its
  322. > engine the active one, so `playback control` reaches it.
  323. The remaining UI automation controls Music.app through System Events (Accessibility API) and CoreGraphics (mouse events).
  324. **Requirements:** Display attached, Music.app visible, Accessibility permissions for System Events (System Settings → Privacy & Security → Accessibility).
  325. ## Key Concepts
  326. **System Events** reads and clicks UI elements by their accessibility hierarchy:
  327. ```applescript
  328. tell application "System Events" to tell process "Music"
  329. -- Main content area
  330. scroll area 2 of splitter group 1 of window "Music"
  331. -- Search field
  332. text field 1 of UI element 1 of row 1 of outline 1 of scroll area 1 of splitter group 1 of window "Music"
  333. end tell
  334. ```
  335. **CoreGraphics mouse events** (via JXA) generate real mouse input — hover, click, and double-click:
  336. ```javascript
  337. // osascript -l JavaScript
  338. ObjC.import("CoreGraphics");
  339. var point = $.CGPointMake(x, y);
  340. // hover (reveals hidden controls):
  341. $.CGEventPost($.kCGHIDEventTap, $.CGEventCreateMouseEvent($(), $.kCGEventMouseMoved, point, 0));
  342. // click: post LeftMouseDown then LeftMouseUp at the point.
  343. // double-click: post two down/up pairs with the click-state field (1) set to 1 then 2.
  344. ```
  345. > **Critical:** System Events `click` (AXPress) **does not fire** Music.app's
  346. > custom Play/Shuffle buttons or track rows — it returns success but nothing
  347. > plays. Read element rects with System Events, then click with **CoreGraphics**
  348. > mouse events at the element's screen coordinates. A single click only *selects*
  349. > a track row; **double-click** it to play.
  350. ## Playing a catalog (non-library) track natively
  351. AppleScript has no verb to play a non-library catalog track. Deep-link the page,
  352. then drive the UI with CoreGraphics:
  353. 1. `open "music://…/album/<id>"` (album/playlist) or `…?i=<songId>` (one track)
  354. 2. **Album/playlist:** locate the `Play` button, read its position+size, CoreGraphics-click its center.
  355. 3. **Single track:** match the track row by name in the track list, CoreGraphics **double-click** it (so only that track plays, not the whole album).
  356. ## The Hover Trick (per-row controls)
  357. Music.app hides per-track Play / "Add to Library" controls until the mouse hovers over a row:
  358. 1. Find the track's UI element position via System Events
  359. 2. Move the mouse there via CoreGraphics (generates real hover events)
  360. 3. The hidden `checkbox` (play) and `button` (Add to Library) appear in the accessibility tree
  361. 4. Click them via **CoreGraphics** at their coordinates (not System Events AXPress)
  362. ## Search via UI
  363. 1. Set the search field value: `set value of searchField to "query"`
  364. 2. Press Return: `key code 36`
  365. 3. Wait for results to load (~4 seconds)
  366. 4. Parse the "Top Results" list from `scroll area 2`
  367. 5. Each result is a `UI element` with `description` = name, static texts for type/artist
  368. **Note:** The type separator in results uses Unicode three-per-em space (U+2004) + middle dot (U+00B7): `Song꘎·꘎Radiohead`
  369. ## Window Recovery
  370. Music.app can run without a window. To ensure a window exists:
  371. ```applescript
  372. tell application "Music" to activate
  373. tell application "System Events" to tell process "Music"
  374. if (count of windows) is 0 then
  375. click menu item "Music" of menu "Window" of menu bar 1
  376. end if
  377. end tell
  378. ```
  379. ## Fragility
  380. UI paths break when Apple updates Music.app's layout. Centralize paths as constants and test after macOS updates. Use Accessibility Inspector.app to explore the current hierarchy.
  381. The search field location changed between macOS 15 (sidebar outline row) and macOS 26/Tahoe (toolbar group). The server probes for the toolbar element at runtime using an AppleScript `exists` check and falls back to the sidebar path — so both OS versions are supported without hardcoding. If UI search ever breaks on a new macOS version, inspect the search field path first.
  382. ## Tool routing (when to use which top-level action)
  383. When a user asks for something, the right MCP tool depends on whether they're searching their library or the catalog. Easy to confuse — gating wrong here leads users into "Developer token not found" rabbit holes when the operation could have worked tokenlessly.
  384. | Goal | Use | Notes |
  385. |---|---|---|
  386. | Find a song the user already has | `library(action='search', query='...')` | Local library only. AppleScript on macOS, API otherwise. |
  387. | Find a playlist by name | `playlist(action='list', filter='alice')` | Loose name match, returns matching playlists with IDs. Do **not** use `action='search'` for this — that searches the *tracks inside* a given playlist and needs a `playlist` param. |
  388. | List the user's tracks in a genre | `library(action='search', query='Rock', types='genre')` | Filters on the track's genre field — **macOS-only**. Do NOT route a genre name through plain full-text search: it never looks at the genre field, so "Rock" would false-match a song titled *"Rock Your Body."* Zero matches returns "No tracks found"; off macOS it reports genre filtering isn't available via the API. |
  389. | Find a song in Apple Music's full catalog | `catalog(action='search', query='...')` | Tries API first, falls back to Music.app UI search on tokenless macOS. |
  390. | Add a catalog song to the user's library | `library(action='add', track='...')` | API only — needs a developer token (generated or harvested) + a media-user-token (`signin`). The UI-automation fallback was removed in 0.15.0 (see note above). |
  391. | Add a song (in library OR catalog) to a playlist | `playlist(action='add', track='...', auto_add=True)` | `auto_add=True` is required to reach the catalog when the song isn't already in the library. Default is False to avoid unwanted library writes — set it to True for "fill this playlist" workflows. |
  392. | Browse charts / recommendations | `discover` | API only. No UI fallback for this one. |
  393. `library(action='search')` returns one page: `limit` (default 25) caps the results and `offset` pages through larger result sets. The text header shows `start-end of total`, so when `end < total` there are more results — bump `offset` by `limit` to fetch the next page (mirrors `action='browse'`).
  394. If `library(action='search')` returns "No songs found in library", it is **not** a hint to set up an API token — it's a hint to try `catalog(action='search')` or `playlist(action='add', auto_add=True)` instead. The tokenless macOS path covers all of these.
  395. ## Compound flows (no API)
  396. Recipes for replicating applemusic-mcp's catalog features without an API token. Gate each user request on "does this need catalog access?" — pure library and playback ops stay in AppleScript; only catalog lookups go through UI automation.
  397. ### Add a catalog song to the user's library
  398. If the user gave a single combined string like `"Silvera - GOJIRA"`, split on ` - ` before searching so the catalog query gets a clean name.
  399. **Step 0 — resolve the canonical title FIRST (do not skip this).** Hit the free, tokenless iTunes Search API (`https://itunes.apple.com/search?term=<name>+<artist>&entity=song&country=<storefront>`) and pick the best match, scoring **artist-primary**: when the user named an artist, a result by a *different* artist is the wrong track even if its title is an exact match — reject it rather than risk a silent wrong-add (e.g. "Lemons"/"Brye" must resolve to Brye's "LEMONS (feat. Cavetown)", **not** "Lemons" by Hairitage). Use the resolved **canonical title** for the UI query below. This matters because Apple's autocomplete is ranking-sensitive: a vague query ("Lemons") surfaces popular homonyms and misses obscure tracks, while the canonical title ("LEMONS (feat. Cavetown)") makes the exact row appear.
  400. Then, **version-dependent surface**:
  401. - **macOS 26 / new Music (Music ≥ 1.6.x):** the search autocomplete pop-over IS in the accessibility tree, and catalog deep-links no longer navigate. Use the pop-over:
  402. 1. UI search with the **canonical title** (§ Search via UI)
  403. 2. Pick the first `Song` result whose name + artist match — do not fall back to a non-Song result; fail cleanly if no Song matched. Stale search state can lead to wrong-result clicks otherwise.
  404. 3. Click the row → it navigates to the song detail page
  405. 4. Hover the track row via CoreGraphics — the hidden "Add to Library" button becomes reachable. **If you find a "Download" button instead, the track is already in the library** (that's success, not failure).
  406. 5. Click "Add to Library" via a real CoreGraphics click (SwiftUI buttons ignore AXPress)
  407. - **macOS 15 / old Music (Music ≤ 1.5.x):** the autocomplete pop-over is **not** in the accessibility tree, but `open`-ing the resolved `music://…?i=…` deep-link DOES navigate to the album page. Deep-link to the resolved URL, find the highlighted track row, hover, and click its "Add to Library" button there.
  408. Finally:
  409. 6. Clear the search field so the next call starts from fresh state
  410. 7. Verify the add. The pop-over UI is authoritative for the iCloud library — trust its success even if the next step lags. Poll `search_library` / a direct `library playlist 1` lookup until the track is visible locally (first appears ~3 s; iCloud can stall longer — cap at ~18 s). A verify miss after a UI-confirmed add means "still syncing," not "failed."
  411. ### Add a catalog song to a specific playlist
  412. Compose **"add to library"** (above) → then AppleScript `duplicate` the new library track into the target playlist:
  413. ```applescript
  414. tell application "Music"
  415. set targetTrack to first track of library playlist 1 ¬
  416. whose name contains "Silvera" and artist contains "GOJIRA"
  417. duplicate targetTrack to user playlist "Road Trip"
  418. end tell
  419. ```
  420. **Don't** click "Add to Playlist" menu items via UI — the AppleScript `duplicate` path is more reliable. Even if you have a dev token, **don't** hit `POST /v1/me/library/playlists/{id}/tracks` — it returns HTTP 500 for any playlist not originally created via API (the default for playlists made in Music.app). `duplicate` works for any playlist.
  421. ### Write routing (sanctioned-first)
  422. The server picks a write's path by **credential and capability, not the playback mode**:
  423. - **Sanctioned** — the official Apple Music API (`api.music.apple.com`) with a generated developer token. Preferred whenever a dev token is present and the op is supported.
  424. - **Web** — the web-player backend with a signed-in session token. Used only for the gaps the public API can't do (delete a playlist, add to a Music.app-created playlist, move out of a folder) or when there's no dev token.
  425. - **Native** — local Music.app via AppleScript on macOS (tokenless), the default writer on a Mac.
  426. So `mode=web` (a *playback* choice) does NOT force writes onto the web path — a dev-token holder still writes via the official API. Star ratings need AppleScript (macOS) regardless of mode. Each write reports the path it took (`via Apple Music API` / `via web player` / `via Music.app`); `config(action="status")` shows the resolved rail on its `Writes:` line.
  427. ### Post-add verification
  428. The UI path can silently click the wrong result under stale search state, and AppleScript state lags briefly after a fresh add. Always verify the expected track actually landed:
  429. ```applescript
  430. tell application "Music"
  431. set matches to (every track of user playlist "Road Trip" ¬
  432. whose name contains "Silvera" and artist contains "GOJIRA")
  433. return (count of matches) > 0
  434. end tell
  435. ```
  436. Retry once after a ~1 s sleep before failing. If the second verify still fails, trust it — the add did not land, surface the error instead of claiming false success.
  437. ---
  438. # MusicKit API
  439. Cross-platform but requires Apple Developer account ($99/year) and token setup.
  440. ## Authentication
  441. **Requirements:**
  442. 1. Apple Developer account
  443. 2. MusicKit key (.p8 file) from [developer portal](https://developer.apple.com/account/resources/authkeys/list)
  444. 3. Developer token (JWT, 180 day max)
  445. 4. User music token (browser OAuth)
  446. **Generate developer token:**
  447. ```python
  448. import jwt, datetime
  449. with open('AuthKey_XXXXXXXXXX.p8') as f:
  450. private_key = f.read()
  451. token = jwt.encode(
  452. {
  453. 'iss': 'TEAM_ID',
  454. 'iat': int(datetime.datetime.now().timestamp()),
  455. 'exp': int((datetime.datetime.now() + datetime.timedelta(days=180)).timestamp())
  456. },
  457. private_key,
  458. algorithm='ES256',
  459. headers={'alg': 'ES256', 'kid': 'KEY_ID'}
  460. )
  461. ```
  462. **Get user token:** Browser OAuth to `https://authorize.music.apple.com/woa`
  463. **Headers for all requests:**
  464. ```
  465. Authorization: Bearer {developer_token}
  466. Music-User-Token: {user_music_token}
  467. ```
  468. **Base URL:** `https://api.music.apple.com/v1`
  469. ## Rate Limits (read this before any bulk loop)
  470. Apple throttles with `HTTP 429` / code `42900` on a **rolling ~60-minute window**, and
  471. sends **no `Retry-After` and no `X-Rate-Limit` header** — remaining quota is unobservable,
  472. so you only find out by getting blocked.
  473. | Token | Practical ceiling | Notes |
  474. |---|---|---|
  475. | Your own developer token (`login --dev`, your `.p8`) | ~3600 requests/hour, Apple's documented figure | Your quota alone |
  476. | Apple's public web-player token (plain `login`, tokenless/Safari path) | a few hundred/hour, measured | Shared, not per-user — the ceiling is far lower and not yours to spend |
  477. Consequences that bite:
  478. - **Waiting briefly does nothing.** A 15-minute zero-traffic cooldown still 429s. It clears
  479. roughly an hour after the burst ends, then re-throttles after a few more requests.
  480. Every retry inside the window adds to the count keeping you blocked.
  481. - **A 429 can look like an empty result, not an error.** One search per track ("resolve
  482. title+artist → catalog id") is the standard import shape and the fastest way to hit this;
  483. if the caller treats an empty search as "song not found", a throttle silently produces
  484. false negatives. Treat empty-after-429 as *unknown*, never as *absent*, and never cache it.
  485. - **For bulk work, use `login --dev`.** Your own developer token gets its own, much larger
  486. quota. Reported and measured in [#42](https://github.com/epheterson/applemusic-mcp/issues/42).
  487. ### Batch-resolve by ISRC instead of searching per track
  488. Where the caller has ISRCs (Spotify / Rekordbox / Plex exports all carry them),
  489. `GET /v1/catalog/{storefront}/songs?filter[isrc]=ISRC1,ISRC2,…` resolves **25 per request**
  490. and matches **exactly** — ~25x fewer requests than a search per track, and no fuzzy-match
  491. errors. Via the tool: `catalog(action="resolve", isrcs="…", format="json")`.
  492. Two things to get right, because `filter[isrc]` is a *filter*, not a search:
  493. - **Misses are silent.** Apple returns only what it matched and omits the rest, so the
  494. unresolved ISRCs exist only as a diff of your request set against `attributes.isrc` on
  495. the responses. Compute that diff — don't assume a full response.
  496. - **Keep "asked and absent" separate from "never asked."** If a batch fails (429) the
  497. remaining ISRCs have *unknown* status, not "not in the catalog." Collapsing the two
  498. recreates the false-negative bug this section exists to warn about.
  499. One ISRC can map to several catalog songs (regional releases, remasters), so carry the
  500. match count rather than silently taking the first.
  501. **Without ISRCs, dry-run before you write.** Title matching is fuzzy, and its failures are
  502. silent: `Dont Let Me Down` with no artist resolves to The Chainsmokers, not The Beatles.
  503. Resolve the whole list first, show the proposed matches with a confidence marker (exact vs.
  504. fuzzy), and only write once they've been reviewed — never interleave "search, then add"
  505. per track. Via the tool: `catalog(action="resolve", tracks=..., format="json")`, which adds
  506. nothing and returns `ids` ready for `playlist(action="add")` — or
  507. `playlist(action="add", ..., dry_run=True)` to preview against a specific playlist,
  508. which also diffs against what's already in it. Note this costs one request
  509. per track (Apple has no batch title+artist endpoint), so it is *not* a rate-limit fix —
  510. use ISRCs for that.
  511. Manually:
  512. ```python
  513. resolved = {}
  514. for i in range(0, len(isrcs), 25):
  515. batch = isrcs[i : i + 25]
  516. r = requests.get(
  517. f"https://api.music.apple.com/v1/catalog/{storefront}/songs",
  518. headers=headers,
  519. params={"filter[isrc]": ",".join(batch)},
  520. )
  521. if r.status_code == 429:
  522. break # later batches only extend the window
  523. for song in r.json().get("data", []):
  524. resolved.setdefault(song["attributes"]["isrc"], song["id"])
  525. ```
  526. ## Available Endpoints
  527. ### Catalog (Public - dev token only)
  528. | Endpoint | Method | Description |
  529. |----------|--------|-------------|
  530. | `/catalog/{storefront}/search` | GET | Search songs, albums, artists, playlists |
  531. | `/catalog/{storefront}/songs/{id}` | GET | Song details |
  532. | `/catalog/{storefront}/albums/{id}` | GET | Album details |
  533. | `/catalog/{storefront}/albums/{id}/tracks` | GET | Album tracks |
  534. | `/catalog/{storefront}/artists/{id}` | GET | Artist details |
  535. | `/catalog/{storefront}/artists/{id}/albums` | GET | Artist's albums |
  536. | `/catalog/{storefront}/artists/{id}/songs` | GET | Artist's top songs |
  537. | `/catalog/{storefront}/artists/{id}/related-artists` | GET | Similar artists |
  538. | `/catalog/{storefront}/playlists/{id}` | GET | Playlist details |
  539. | `/catalog/{storefront}/charts` | GET | Top charts |
  540. | `/catalog/{storefront}/genres` | GET | All genres |
  541. | `/catalog/{storefront}/search/suggestions` | GET | Search autocomplete |
  542. | `/catalog/{storefront}/stations/{id}` | GET | Radio station |
  543. ### Library (Requires user token)
  544. | Endpoint | Method | Description |
  545. |----------|--------|-------------|
  546. | `/me/library/songs` | GET | All library songs |
  547. | `/me/library/albums` | GET | All library albums |
  548. | `/me/library/artists` | GET | All library artists |
  549. | `/me/library/playlists` | GET | All library playlists |
  550. | `/me/library/playlists/{id}` | GET | Playlist details |
  551. | `/me/library/playlists/{id}/tracks` | GET | Playlist tracks |
  552. | `/me/library/search` | GET | Search library |
  553. | `/me/library` | POST | Add to library |
  554. | `/catalog/{sf}/songs/{id}/library` | GET | Get library ID from catalog ID |
  555. ### Playlist Management
  556. | Endpoint | Method | Description |
  557. |----------|--------|-------------|
  558. | `/me/library/playlists` | POST | Create playlist |
  559. | `/me/library/playlists/{id}/tracks` | POST | Add tracks to playlist |
  560. ### Personalization
  561. | Endpoint | Method | Description |
  562. |----------|--------|-------------|
  563. | `/me/recommendations` | GET | Personalized recommendations |
  564. | `/me/history/heavy-rotation` | GET | Frequently played |
  565. | `/me/recent/played` | GET | Recently played |
  566. | `/me/recent/added` | GET | Recently added |
  567. ### Ratings
  568. | Endpoint | Method | Description |
  569. |----------|--------|-------------|
  570. | `/me/ratings/songs/{id}` | GET | Get song rating |
  571. | `/me/ratings/songs/{id}` | PUT | Set song rating |
  572. | `/me/ratings/songs/{id}` | DELETE | Remove rating |
  573. | `/me/ratings/albums/{id}` | GET/PUT/DELETE | Album ratings |
  574. | `/me/ratings/playlists/{id}` | GET/PUT/DELETE | Playlist ratings |
  575. ### Storefronts
  576. | Endpoint | Method | Description |
  577. |----------|--------|-------------|
  578. | `/storefronts` | GET | All storefronts |
  579. | `/storefronts/{id}` | GET | Storefront details |
  580. | `/me/storefront` | GET | User's storefront |
  581. ## Common Query Parameters
  582. | Parameter | Description | Example |
  583. |-----------|-------------|---------|
  584. | `term` | Search query | `term=beatles` |
  585. | `types` | Resource types | `types=songs,albums` |
  586. | `limit` | Results per page (max 25) | `limit=10` |
  587. | `offset` | Pagination offset | `offset=25` |
  588. | `include` | Related resources | `include=artists,albums` |
  589. | `extend` | Additional attributes | `extend=editorialNotes` |
  590. | `l` | Language code | `l=en-US` |
  591. ## Search Example
  592. ```bash
  593. GET /v1/catalog/us/search?term=wonderwall&types=songs&limit=10
  594. Response:
  595. {
  596. "results": {
  597. "songs": {
  598. "data": [{
  599. "id": "1234567890",
  600. "type": "songs",
  601. "attributes": {
  602. "name": "Wonderwall",
  603. "artistName": "Oasis",
  604. "albumName": "(What's the Story) Morning Glory?",
  605. "durationInMillis": 258773,
  606. "releaseDate": "1995-10-02",
  607. "genreNames": ["Alternative", "Music"]
  608. }
  609. }]
  610. }
  611. }
  612. }
  613. ```
  614. ## Library-First Workflow (Complete)
  615. Adding a catalog song to a playlist requires 4 API calls:
  616. ```python
  617. import requests
  618. headers = {
  619. "Authorization": f"Bearer {dev_token}",
  620. "Music-User-Token": user_token
  621. }
  622. # 1. Search catalog
  623. r = requests.get(
  624. "https://api.music.apple.com/v1/catalog/us/search",
  625. headers=headers,
  626. params={"term": "Wonderwall Oasis", "types": "songs", "limit": 1}
  627. )
  628. catalog_id = r.json()['results']['songs']['data'][0]['id']
  629. # 2. Add to library
  630. requests.post(
  631. "https://api.music.apple.com/v1/me/library",
  632. headers=headers,
  633. params={"ids[songs]": catalog_id}
  634. )
  635. # 3. Get library ID (catalog ID → library ID)
  636. r = requests.get(
  637. f"https://api.music.apple.com/v1/catalog/us/songs/{catalog_id}/library",
  638. headers=headers
  639. )
  640. library_id = r.json()['data'][0]['id']
  641. # 4. Add to playlist (library IDs only!)
  642. requests.post(
  643. f"https://api.music.apple.com/v1/me/library/playlists/{playlist_id}/tracks",
  644. headers={**headers, "Content-Type": "application/json"},
  645. json={"data": [{"id": library_id, "type": "library-songs"}]}
  646. )
  647. ```
  648. ## Create Playlist
  649. ```bash
  650. POST /v1/me/library/playlists
  651. Content-Type: application/json
  652. {
  653. "attributes": {
  654. "name": "Road Trip",
  655. "description": "Summer vibes"
  656. },
  657. "relationships": {
  658. "tracks": {
  659. "data": []
  660. }
  661. }
  662. }
  663. ```
  664. ## Ratings
  665. ```bash
  666. # Love a song (value: 1 = love, -1 = dislike)
  667. PUT /v1/me/ratings/songs/{id}
  668. Content-Type: application/json
  669. {"attributes": {"value": 1}}
  670. ```
  671. ## Limitations
  672. - **No playback control** - API cannot play/pause/skip
  673. - **Playlist editing** - can only modify API-created playlists
  674. - **Token management** - dev tokens expire every 180 days
  675. - **Rate limits** - Apple enforces request limits
  676. ---
  677. # Common Mistakes
  678. **❌ Using catalog IDs in playlists:**
  679. ```python
  680. # WRONG
  681. json={"data": [{"id": "1234567890", "type": "songs"}]}
  682. ```
  683. **Fix:** Add to library first, get library ID, then add.
  684. **❌ Playing catalog songs via AppleScript:**
  685. ```applescript
  686. # WRONG
  687. play track id "1234567890"
  688. ```
  689. **Fix:** Song must be in library.
  690. **❌ Unescaped AppleScript strings:**
  691. ```python
  692. # WRONG
  693. name = "Rock 'n Roll"
  694. script = f'tell application "Music" to play playlist "{name}"'
  695. ```
  696. **Fix:** Escape quotes.
  697. **❌ Expired tokens:**
  698. Dev tokens last 180 days max.
  699. **Fix:** Check expiration, handle 401 errors.
  700. ---
  701. # The Easy Way: applemusic-mcp
  702. The [applemusic-mcp](https://github.com/epheterson/applemusic-mcp) MCP server handles all this complexity automatically: AppleScript escaping, token management, library-first workflow, ID conversions.
  703. **Install:**
  704. ```bash
  705. git clone https://github.com/epheterson/applemusic-mcp.git
  706. cd applemusic-mcp && python3 -m venv venv && source venv/bin/activate
  707. pip install -e .
  708. ```
  709. **Configure Claude Desktop:**
  710. ```json
  711. {
  712. "mcpServers": {
  713. "Apple Music": {
  714. "command": "/path/to/applemusic-mcp/venv/bin/python",
  715. "args": ["-m", "applemusic_mcp"]
  716. }
  717. }
  718. }
  719. ```
  720. On macOS, most features work immediately. For catalog features or Windows/Linux, see the repo README.
  721. | Manual | applemusic-mcp |
  722. |--------|----------------|
  723. | 4 API calls to add song | `playlist(action="add", auto_add=True)` |
  724. | Copy URL + open in Music | `playback(action="play", url="...")` |
  725. | Add a catalog song to your library | `library(action="add")` (unified API — dev or web token) |
  726. | Track library changes manually | `library(action="snapshot")` |
  727. | AppleScript escaping | Automatic |
  728. | Token management | Automatic with warnings |
README.md · README · 164 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # applemusic-mcp
  2. [![Release](https://img.shields.io/github/v/release/epheterson/applemusic-mcp.svg?label=release)](https://github.com/epheterson/applemusic-mcp/releases)
  3. [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
  4. [![macOS](https://img.shields.io/badge/macOS-15%20%7C%2026-blue.svg)]()
  5. [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
  6. [![Downloads](https://static.pepy.tech/badge/applemusic-mcp)](https://pepy.tech/project/applemusic-mcp)
  7. [![MCP](https://img.shields.io/badge/MCP-server-purple.svg)](https://modelcontextprotocol.io/)
  8. MCP server for Apple Music. It gives any [MCP client](https://modelcontextprotocol.io/clients) (Claude, Cursor, Cline, Windsurf) control of your playlists, library, catalog, discovery, playback, and the Up Next queue. Runs on macOS, Windows, and Linux.
  9. **A Mac or an Apple Music subscription is all you need.**
  10. *"Create a playlist called Road Trip and fill it with upbeat 90s alternative."* · *"Play my workout playlist on shuffle, and queue up Bohemian Rhapsody next."* · *"What have I been listening to lately, and what's topping the charts?"*
  11. ## Choose how much it can reach
  12. You decide what this server may touch, in your MCP client's config. The assistant can't change it, and tools that need more than you allowed aren't offered to it at all.
  13. | `--level` | It can reach | Good for |
  14. |---|---|---|
  15. | `music` | Only the Music app on your Mac. No network, no browser. | Your library, playlists, playback, ratings, AirPlay |
  16. | `api` | + Apple's music service over the internet | Searching and adding from the full catalog, recommendations, Windows and Linux |
  17. | `web` | + a Safari or Chrome web player | The Up Next queue, and playback off the Mac |
  18. | `full` | Everything, including clicking inside the Music app | Every feature, nothing to decide |
  19. | `--allow-ui` (with any level) | + clicking inside the Music app (macOS Accessibility) | Playing catalog songs with no sign-in |
  20. Start with `music` and move up when you want a feature that needs more. Leaving `--level` off is the same as `full` for now, as before 0.21.
  21. For a Mac app with a guided setup instead of a terminal command, consider the community fork [secure-applemusic-mcp-for-osx](https://github.com/jaminben/secure-applemusic-mcp-for-osx).
  22. ## Features
  23. What each engine can do, and the level that turns it on. `✓` supported, `✗` not possible there, `—` not applicable.
  24. |Capability|Music.app (macOS) · `music`|Apple Music API (any OS) · `api`|Web player (Safari / Chrome) · `web`|
  25. |---|:---:|:---:|:---:|
  26. |**Catalog search / browse**|✓|✓ (+ tokenless resolve)|—|
  27. |Recommendations / charts / suggestions|✗|✓|—|
  28. |**Library search / browse**|✓|✓|—|
  29. |Genre search|✓|✗|—|
  30. |Recently played / added|✓|✓|—|
  31. |**Add catalog → library**|✓|✓|✓ (in-page POST)|
  32. |Remove from library|✓|✓|—|
  33. |Love / dislike|✓|✓|—|
  34. |**1–5 star ratings**|✓|✗|✗|
  35. |Favorites list|✓|✗|✗|
  36. |**Playlist** create / add / remove / rename|✓|✓|—|
  37. |Playlist copy|✓|✗|—|
  38. |Playlist delete|✓|✓ (web token)|—|
  39. |Folders: single level + move in/out|✓|✓|—|
  40. |Folders: nested paths / tree / `path`|✓|✗|✗|
  41. |**Playback**: play song / album / playlist / URL|✓|—|✓|
  42. |Controls: pause / stop / next / prev / seek|✓|—|✓|
  43. |Settings: volume / shuffle / repeat|✓|—|✓|
  44. |now_playing|✓|—|✓|
  45. |**Up Next queue**: view / next / last / remove / jump / clear / autoplay|✗|—|✓|
  46. |Reveal in app|✓|—|✓ (navigates page)|
  47. |AirPlay device select|✓|✗|✗|
  48. |Library snapshot / integrity|✓|✗|✗|
  49. |**Works with no Apple account**|✓|✗|✗|
  50. |**Cross-platform (Win/Linux)**|✗|✓|✓|
  51. Music.app's catalog search and catalog play click inside the app, so at a set level they also need `--allow-ui`. Playback and the queue in a web player need a desktop session: Safari on a Mac (nothing to install) or Google Chrome elsewhere. How the engines are picked and overridden: [configuration](https://github.com/epheterson/applemusic-mcp/blob/main/docs/configuration.md).
  52. ## Setup
  53. **Requirements:** Python 3.10+, plus a Mac or an Apple Music subscription. On a Mac nothing else is needed. The Chrome web player (Windows, Linux, or opt-in on a Mac) needs [Google Chrome](https://www.google.com/chrome/).
  54. **Claude Code**, one line:
  55. ```bash
  56. claude mcp add "Apple Music" -- uvx applemusic-mcp serve --level music
  57. ```
  58. **Claude Desktop / Cursor / Cline / Windsurf**, install once, then add the config block:
  59. ```bash
  60. pipx install applemusic-mcp # or: pip install applemusic-mcp
  61. playwright install chromium # the Chrome web player: Windows/Linux, or a Mac with the [browser] extra
  62. ```
  63. ```json
  64. {
  65. "mcpServers": {
  66. "Apple Music": {
  67. "command": "applemusic-mcp",
  68. "args": ["serve", "--level", "music"]
  69. }
  70. }
  71. }
  72. ```
  73. Change `music` to `api` or `web` to [unlock more](#choose-how-much-it-can-reach); on Windows or Linux start at `api`, since `music` needs a Mac. Config file locations, the Chrome web player on a Mac, and source installs: [configuration](https://github.com/epheterson/applemusic-mcp/blob/main/docs/configuration.md).
  74. Restart your client and try *"List my Apple Music playlists"* or *"Play my favorites."* On macOS the local library and playback work immediately. To add catalog music or run on any OS, sign in.
  75. ### Sign in
  76. Needed for `api` and `web`. Your password never touches this tool, and sign-in persists.
  77. ```bash
  78. applemusic-mcp login # Mac: reads your signed-in Safari. Windows/Linux: opens Chrome
  79. applemusic-mcp status # verify
  80. ```
  81. On a Mac, sign in at [music.apple.com](https://music.apple.com) in Safari first and turn on Safari's **Develop → Allow JavaScript from Apple Events** once; `login` tells you exactly what's missing. For bulk work (playlist imports, library migrations), use your own Apple developer token to avoid the shared rate limit. Details, the Chrome and developer-token paths, and which API each write uses: [signing in](https://github.com/epheterson/applemusic-mcp/blob/main/docs/sign-in.md).
  82. ## Tools
  83. Seven action-based tools keep the MCP context small. Each takes an `action` and routes to the right engine.
  84. | Tool | Actions |
  85. |---|---|
  86. | `playlist` | list, folders, tracks, search, create, add, copy, move, remove, delete, rename, path (playlists and folders) |
  87. | `library` | search, add, browse, favorites, recently_played, recently_added, rate, remove, snapshot |
  88. | `catalog` | search, resolve, album_tracks, album_details, song_details, artist_details, genres, suggestions |
  89. | `discover` | recommendations, heavy_rotation, charts, top_songs, similar_artists, personal_station, song_station |
  90. | `playback` | play (track / album / playlist / URL), control, now_playing, settings, reveal, airplay |
  91. | `queue` | list, set, play_next, play_last, remove, jump, clear, autoplay (Up Next — Safari on macOS, Chrome elsewhere; `engine=` to pick) |
  92. | `config` | status, signin, logout, reset, set-pref, audit-log, clear-audit-log, list-storefronts |
  93. Batching, importing playlists, dry runs, export formats and storefronts: [usage patterns](https://github.com/epheterson/applemusic-mcp/blob/main/docs/usage.md).
  94. ## CLI
  95. ```bash
  96. applemusic-mcp serve --level music # run the MCP server (your client calls this)
  97. applemusic-mcp login # web sign-in (macOS: Safari; Windows/Linux: Chrome)
  98. applemusic-mcp login --chrome # use the Chrome web player on a Mac
  99. applemusic-mcp login --dev # your own Apple developer token (.p8)
  100. applemusic-mcp logout # sign out (switch accounts)
  101. applemusic-mcp status # auth status and permission level
  102. applemusic-mcp reset --force # wipe credentials (keeps your .p8 key file)
  103. applemusic-mcp reset --all --force # full uninstall: also removes the .p8, profile, and cache
  104. ```
  105. ## Good to know
  106. - **Playing catalog songs in Music.app needs `--allow-ui`, an unlocked screen and Accessibility permission.** It clicks Play inside the app. Songs already in your library don't need any of this. Or, at `--level web`, set `mode="safari"` to play in Safari instead.
  107. - **Safari playback needs one real click to start.** The first time you play in a freshly-opened or reloaded Safari tab, the browser requires a genuine click before it will start audio (a standard autoplay rule — we don't fake it). Click ▶ once in the Apple Music tab, then play/pause/next all work hands-free. If a play command reports the queue is ready but the track sits at 0:00, that's this — give the tab one click.
  108. - **Brand-new playlists take a moment** to be addable over the API (cloud propagation). Existing ones are immediate.
  109. - **If catalog actions start failing**, re-run `applemusic-mcp login`. A handful of user playlists silently revert AppleScript edits ([known Music.app bug](https://www.macscripter.net/t/add-current-track-from-apple-music-to-playlist/72058)); the server detects and surfaces the rollback.
  110. ## Star History
  111. [![Star History Chart](https://api.star-history.com/svg?repos=epheterson/applemusic-mcp&type=Date)](https://star-history.com/#epheterson/applemusic-mcp&Date)
  112. ---
  113. ## License
  114. MIT · *Unofficial community project — not affiliated with or endorsed by Apple. Uses your own Apple Music account for personal use; follow Apple's terms.*
  115. <!-- Identifier for the official MCP Registry (PyPI ownership check). -->
  116. mcp-name: io.github.epheterson/applemusic-mcp
  117. ## Credits
  118. [FastMCP](https://github.com/jlowin/fastmcp) · [Apple MusicKit](https://developer.apple.com/documentation/applemusicapi) · [Model Context Protocol](https://modelcontextprotocol.io/)
  119. ---
  120. Built with ❤️ in California by [@epheterson](https://github.com/epheterson) and [Claude Code](https://claude.com/claude-code).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.