/SKILL.md
Apple Music integration via AppleScript, UI automation, or MusicKit API
npx skillsauth add epheterson/mcp-applemusic apple-musicInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Guide for integrating with Apple Music. Three approaches: AppleScript (direct control), UI automation (catalog without API), and MusicKit API (cross-platform).
Invoke when users ask to:
You CANNOT add catalog songs directly to playlists.
Songs must be in the user's library first:
Why: Playlists use library IDs (i.abc123), not catalog IDs (1234567890).
This applies to both AppleScript and API approaches.
Zero setup. Works immediately with the Music app.
Run via Bash:
osascript -e 'tell application "Music" to playpause'
osascript -e 'tell application "Music" to return name of current track'
Multi-line scripts:
osascript <<'EOF'
tell application "Music"
set t to current track
return {name of t, artist of t}
end tell
EOF
| Category | Operations | |----------|------------| | Playback | play, pause, stop, resume, next track, previous track, fast forward, rewind, play URL | | Player State | player position, player state, sound volume, mute, shuffle enabled/mode, song repeat | | Current Track | name, artist, album, duration, time, rating, loved, disliked, genre, year, track number | | Library | search, list tracks, get track properties, set ratings | | Playlists | list, create, delete, rename, add tracks, remove tracks, get tracks | | AirPlay | list devices, select device, current device |
tell application "Music"
set t to current track
-- Basic info
name of t -- "Hey Jude"
artist of t -- "The Beatles"
album of t -- "1 (Remastered)"
album artist of t -- "The Beatles"
composer of t -- "Lennon-McCartney"
genre of t -- "Rock"
year of t -- 1968
-- Timing
duration of t -- 431.0 (seconds)
time of t -- "7:11" (formatted)
start of t -- start time in seconds
finish of t -- end time in seconds
-- Track info
track number of t -- 21
track count of t -- 27
disc number of t -- 1
disc count of t -- 1
-- Ratings
rating of t -- 0-100 (20 per star)
loved of t -- true/false
disliked of t -- true/false
-- Playback
played count of t -- 42
played date of t -- date last played
skipped count of t -- 3
skipped date of t -- date last skipped
-- IDs
persistent ID of t -- "ABC123DEF456"
database ID of t -- 12345
end tell
tell application "Music"
set t to current track
set rating of t to 80 -- 4 stars
set loved of t to true
set disliked of t to false
set name of t to "New Name" -- rename track
set genre of t to "Alternative"
set year of t to 1995
end tell
tell application "Music"
player state -- stopped, playing, paused, fast forwarding, rewinding
player position -- current position in seconds (read/write)
sound volume -- 0-100 (read/write)
mute -- true/false (read/write)
shuffle enabled -- true/false (read/write)
shuffle mode -- songs, albums, groupings
song repeat -- off, one, all (read/write)
current track -- track object
current playlist -- playlist object
current stream URL -- URL if streaming
end tell
tell application "Music"
-- Play controls
play -- play current selection
pause
stop
resume
playpause -- toggle play/pause
next track
previous track
fast forward
rewind
-- Play specific content
play (first track of library playlist 1 whose name contains "Hey Jude")
play user playlist "Road Trip"
-- Settings
set player position to 60 -- seek to 1:00
set sound volume to 50 -- 0-100
set mute to true
set shuffle enabled to true
set song repeat to all -- off, one, all
end tell
whose name contains "..." is glyph-exact — unlike Music's native search
command, it does not fold a straight apostrophe (U+0027) against the curly one
(U+2019) Music often stores, nor accents. So whose name contains "That's a No No" misses a title stored as That's a No No. Two robust strategies:
-- 1. Match the quote-free fragments instead of the apostrophe itself.
-- Works regardless of which apostrophe variant is stored or typed.
play (first track of library playlist 1 whose ¬
(name contains "That" and name contains "s a No No"))
-- 2. For accents/ellipsis/anything: bulk-fetch names in ONE Apple Event and
-- fold in-memory. `ignoring punctuation and diacriticals` uses Apple's
-- Unicode tables (curly quotes, ellipses, café≈cafe). Do NOT access
-- `name of t` per-iteration in a loop — that is one Apple Event per track
-- (~17s on a 12k library); fetch the whole list at once (~instant).
tell application "Music"
set allNames to (get name of every track of library playlist 1)
set idx to 0
ignoring punctuation and diacriticals
repeat with i from 1 to (count of allNames)
if ((item i of allNames) as text) contains "Fur Elise" then
set idx to i
exit repeat
end if
end repeat
end ignoring
if idx > 0 then play (track idx of library playlist 1)
end tell
tell application "Music"
-- All library tracks
every track of library playlist 1
-- Search by name
tracks of library playlist 1 whose name contains "Beatles"
-- Search by artist
tracks of library playlist 1 whose artist contains "Beatles"
-- Search by album
tracks of library playlist 1 whose album contains "Abbey Road"
-- Combined search
tracks of library playlist 1 whose name contains "Hey" and artist contains "Beatles"
-- By genre
tracks of library playlist 1 whose genre is "Rock"
-- By year
tracks of library playlist 1 whose year is 1969
-- By rating
tracks of library playlist 1 whose rating > 60 -- 3+ stars
-- Loved tracks
tracks of library playlist 1 whose loved is true
-- Recently played (sort by played date)
tracks of library playlist 1 whose played date > (current date) - 7 * days
end tell
tell application "Music"
-- List all playlists
name of every user playlist
-- Get playlist
user playlist "Road Trip"
first user playlist whose name contains "Road"
-- Create playlist
make new user playlist with properties {name:"New Playlist", description:"My playlist"}
-- Delete playlist
delete user playlist "Old Playlist"
-- Rename playlist
set name of user playlist "Old Name" to "New Name"
-- Get playlist tracks
every track of user playlist "Road Trip"
name of every track of user playlist "Road Trip"
-- Add track to playlist (must be library track)
set targetPlaylist to user playlist "Road Trip"
set targetTrack to first track of library playlist 1 whose name contains "Hey Jude"
duplicate targetTrack to targetPlaylist
-- Remove track from playlist
delete (first track of user playlist "Road Trip" whose name contains "Hey Jude")
-- Playlist properties
duration of user playlist "Road Trip" -- total duration
time of user playlist "Road Trip" -- formatted duration
count of tracks of user playlist "Road Trip"
end tell
tell application "Music"
-- List AirPlay devices
name of every AirPlay device
-- Get current device
current AirPlay devices
-- Set output device
set current AirPlay devices to {AirPlay device "Living Room"}
-- Multiple devices
set current AirPlay devices to {AirPlay device "Living Room", AirPlay device "Kitchen"}
-- Device properties
set d to AirPlay device "Living Room"
name of d
kind of d -- computer, AirPort Express, Apple TV, AirPlay device, Bluetooth device
active of d -- true if playing
available of d -- true if reachable
selected of d -- true if in current devices
sound volume of d -- 0-100
end tell
Always escape user input:
def escape_applescript(s):
return s.replace('\\', '\\\\').replace('"', '\\"')
safe_name = escape_applescript(user_input)
script = f'tell application "Music" to play user playlist "{safe_name}"'
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).
| Stderr signal | What it means | What to tell the user |
|---|---|---|
| (-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." |
| (-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." |
| 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." |
| syntax error, expected … but found … | The script itself is malformed (developer bug) | Report the raw error — this is on us, not the user. |
| 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. |
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.
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.
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.For catalog features without an API token. Controls Music.app through System Events (Accessibility API) and CoreGraphics (mouse events).
Requirements: Display attached, Music.app visible, Accessibility permissions for System Events (System Settings → Privacy & Security → Accessibility).
System Events reads and clicks UI elements by their accessibility hierarchy:
tell application "System Events" to tell process "Music"
-- Main content area
scroll area 2 of splitter group 1 of window "Music"
-- Search field
text field 1 of UI element 1 of row 1 of outline 1 of scroll area 1 of splitter group 1 of window "Music"
end tell
CoreGraphics mouse events (via JXA) trigger hover effects that reveal hidden UI controls:
// osascript -l JavaScript
ObjC.import("CoreGraphics");
var point = $.CGPointMake(x, y);
var event = $.CGEventCreateMouseEvent($(), $.kCGEventMouseMoved, point, 0);
$.CGEventPost($.kCGHIDEventTap, event);
Music.app hides per-track Play and "Add to Library" buttons until the mouse hovers over a track row. To interact with them programmatically:
checkbox (play) and button (Add to Library) appear in the accessibility treeset value of searchField to "query"key code 36scroll area 2UI element with description = name, static texts for type/artistNote: The type separator in results uses Unicode three-per-em space (U+2004) + middle dot (U+00B7): Song꘎·꘎Radiohead
Music.app can run without a window. To ensure a window exists:
tell application "Music" to activate
tell application "System Events" to tell process "Music"
if (count of windows) is 0 then
click menu item "Music" of menu "Window" of menu bar 1
end if
end tell
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.
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.
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.
| Goal | Use | Notes |
|---|---|---|
| Find a song the user already has | library(action='search', query='...') | Local library only. AppleScript on macOS, API otherwise. |
| 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. |
| Add a catalog song to the user's library | library(action='add', track='...') | API path with token, UI automation path on tokenless macOS. |
| Add a song (in library OR catalog) to a playlist | playlist(action='add', track='...', auto_search=True) | auto_search=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. |
| Browse charts / recommendations | discover | API only. No UI fallback for this one. |
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_search=True) instead. The tokenless macOS path covers all of these.
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.
If the user gave a single combined string like "Silvera - GOJIRA", split on - before searching so the catalog query gets a clean name.
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.search_library via AppleScript until the track is visible locally (typical 0.5–8 s; iCloud can stall longer — cap at ~18 s, then give up cleanly)Compose "add to library" (above) → then AppleScript duplicate the new library track into the target playlist:
tell application "Music"
set targetTrack to first track of library playlist 1 ¬
whose name contains "Silvera" and artist contains "GOJIRA"
duplicate targetTrack to user playlist "Road Trip"
end tell
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.
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:
tell application "Music"
set matches to (every track of user playlist "Road Trip" ¬
whose name contains "Silvera" and artist contains "GOJIRA")
return (count of matches) > 0
end tell
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.
Cross-platform but requires Apple Developer account ($99/year) and token setup.
Requirements:
Generate developer token:
import jwt, datetime
with open('AuthKey_XXXXXXXXXX.p8') as f:
private_key = f.read()
token = jwt.encode(
{
'iss': 'TEAM_ID',
'iat': int(datetime.datetime.now().timestamp()),
'exp': int((datetime.datetime.now() + datetime.timedelta(days=180)).timestamp())
},
private_key,
algorithm='ES256',
headers={'alg': 'ES256', 'kid': 'KEY_ID'}
)
Get user token: Browser OAuth to https://authorize.music.apple.com/woa
Headers for all requests:
Authorization: Bearer {developer_token}
Music-User-Token: {user_music_token}
Base URL: https://api.music.apple.com/v1
| Endpoint | Method | Description |
|----------|--------|-------------|
| /catalog/{storefront}/search | GET | Search songs, albums, artists, playlists |
| /catalog/{storefront}/songs/{id} | GET | Song details |
| /catalog/{storefront}/albums/{id} | GET | Album details |
| /catalog/{storefront}/albums/{id}/tracks | GET | Album tracks |
| /catalog/{storefront}/artists/{id} | GET | Artist details |
| /catalog/{storefront}/artists/{id}/albums | GET | Artist's albums |
| /catalog/{storefront}/artists/{id}/songs | GET | Artist's top songs |
| /catalog/{storefront}/artists/{id}/related-artists | GET | Similar artists |
| /catalog/{storefront}/playlists/{id} | GET | Playlist details |
| /catalog/{storefront}/charts | GET | Top charts |
| /catalog/{storefront}/genres | GET | All genres |
| /catalog/{storefront}/search/suggestions | GET | Search autocomplete |
| /catalog/{storefront}/stations/{id} | GET | Radio station |
| Endpoint | Method | Description |
|----------|--------|-------------|
| /me/library/songs | GET | All library songs |
| /me/library/albums | GET | All library albums |
| /me/library/artists | GET | All library artists |
| /me/library/playlists | GET | All library playlists |
| /me/library/playlists/{id} | GET | Playlist details |
| /me/library/playlists/{id}/tracks | GET | Playlist tracks |
| /me/library/search | GET | Search library |
| /me/library | POST | Add to library |
| /catalog/{sf}/songs/{id}/library | GET | Get library ID from catalog ID |
| Endpoint | Method | Description |
|----------|--------|-------------|
| /me/library/playlists | POST | Create playlist |
| /me/library/playlists/{id}/tracks | POST | Add tracks to playlist |
| Endpoint | Method | Description |
|----------|--------|-------------|
| /me/recommendations | GET | Personalized recommendations |
| /me/history/heavy-rotation | GET | Frequently played |
| /me/recent/played | GET | Recently played |
| /me/recent/added | GET | Recently added |
| Endpoint | Method | Description |
|----------|--------|-------------|
| /me/ratings/songs/{id} | GET | Get song rating |
| /me/ratings/songs/{id} | PUT | Set song rating |
| /me/ratings/songs/{id} | DELETE | Remove rating |
| /me/ratings/albums/{id} | GET/PUT/DELETE | Album ratings |
| /me/ratings/playlists/{id} | GET/PUT/DELETE | Playlist ratings |
| Endpoint | Method | Description |
|----------|--------|-------------|
| /storefronts | GET | All storefronts |
| /storefronts/{id} | GET | Storefront details |
| /me/storefront | GET | User's storefront |
| Parameter | Description | Example |
|-----------|-------------|---------|
| term | Search query | term=beatles |
| types | Resource types | types=songs,albums |
| limit | Results per page (max 25) | limit=10 |
| offset | Pagination offset | offset=25 |
| include | Related resources | include=artists,albums |
| extend | Additional attributes | extend=editorialNotes |
| l | Language code | l=en-US |
GET /v1/catalog/us/search?term=wonderwall&types=songs&limit=10
Response:
{
"results": {
"songs": {
"data": [{
"id": "1234567890",
"type": "songs",
"attributes": {
"name": "Wonderwall",
"artistName": "Oasis",
"albumName": "(What's the Story) Morning Glory?",
"durationInMillis": 258773,
"releaseDate": "1995-10-02",
"genreNames": ["Alternative", "Music"]
}
}]
}
}
}
Adding a catalog song to a playlist requires 4 API calls:
import requests
headers = {
"Authorization": f"Bearer {dev_token}",
"Music-User-Token": user_token
}
# 1. Search catalog
r = requests.get(
"https://api.music.apple.com/v1/catalog/us/search",
headers=headers,
params={"term": "Wonderwall Oasis", "types": "songs", "limit": 1}
)
catalog_id = r.json()['results']['songs']['data'][0]['id']
# 2. Add to library
requests.post(
"https://api.music.apple.com/v1/me/library",
headers=headers,
params={"ids[songs]": catalog_id}
)
# 3. Get library ID (catalog ID → library ID)
r = requests.get(
f"https://api.music.apple.com/v1/catalog/us/songs/{catalog_id}/library",
headers=headers
)
library_id = r.json()['data'][0]['id']
# 4. Add to playlist (library IDs only!)
requests.post(
f"https://api.music.apple.com/v1/me/library/playlists/{playlist_id}/tracks",
headers={**headers, "Content-Type": "application/json"},
json={"data": [{"id": library_id, "type": "library-songs"}]}
)
POST /v1/me/library/playlists
Content-Type: application/json
{
"attributes": {
"name": "Road Trip",
"description": "Summer vibes"
},
"relationships": {
"tracks": {
"data": []
}
}
}
# Love a song (value: 1 = love, -1 = dislike)
PUT /v1/me/ratings/songs/{id}
Content-Type: application/json
{"attributes": {"value": 1}}
❌ Using catalog IDs in playlists:
# WRONG
json={"data": [{"id": "1234567890", "type": "songs"}]}
Fix: Add to library first, get library ID, then add.
❌ Playing catalog songs via AppleScript:
# WRONG
play track id "1234567890"
Fix: Song must be in library.
❌ Unescaped AppleScript strings:
# WRONG
name = "Rock 'n Roll"
script = f'tell application "Music" to play playlist "{name}"'
Fix: Escape quotes.
❌ Expired tokens: Dev tokens last 180 days max. Fix: Check expiration, handle 401 errors.
The applemusic-mcp MCP server handles all this complexity automatically: AppleScript escaping, token management, library-first workflow, ID conversions.
Install:
git clone https://github.com/epheterson/applemusic-mcp.git
cd applemusic-mcp && python3 -m venv venv && source venv/bin/activate
pip install -e .
Configure Claude Desktop:
{
"mcpServers": {
"Apple Music": {
"command": "/path/to/applemusic-mcp/venv/bin/python",
"args": ["-m", "applemusic_mcp"]
}
}
}
On macOS, most features work immediately. For catalog features or Windows/Linux, see the repo README.
| Manual | applemusic-mcp |
|--------|----------------|
| 4 API calls to add song | playlist(action="add", auto_search=True) |
| Copy URL + open in Music | playback(action="play", url="...") |
| UI hover + click to add to library | library(action="add") with UI fallback |
| Track library changes manually | library(action="snapshot") |
| AppleScript escaping | Automatic |
| Token management | Automatic with warnings |
tools
Use when work should span one or more detached tasks but still behave like one job with a single owner context. TaskFlow is the durable flow substrate under authoring layers like Lobster, ACPX, plugins, or plain code. Keep conditional logic in the caller; use TaskFlow for flow identity, child-task linkage, waiting state, revision-checked mutations, and user-facing emergence.
tools
# Lobster Lobster executes multi-step workflows with approval checkpoints. Use it when: - User wants a repeatable automation (triage, monitor, sync) - Actions need human approval before executing (send, post, delete) - Multiple tool calls should run as one deterministic operation ## When to use Lobster | User intent | Use Lobster? | | ------------------------------------------------------ | --------------------------
tools
# Lobster Lobster executes multi-step workflows with approval checkpoints. Use it when: - User wants a repeatable automation (triage, monitor, sync) - Actions need human approval before executing (send, post, delete) - Multiple tool calls should run as one deterministic operation ## When to use Lobster | User intent | Use Lobster? | | ------------------------------------------------------ | --------------------------
tools
A CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.