Apple Music MCP
Provides tools for interacting with an Apple Music account, including reading listening history, heavy rotation, recommendations, Replay summaries, library playlists, searching the catalog, and safely creating playlists and appending tracks with duplicate checks.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Apple Music MCPWhat's my top artist this month?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Apple Music MCP
A single-owner Apple Music MCP server with two deployment options: a standalone Cloudflare Worker, or a private ChatGPT Site with a Cloudflare timer forwarding collection requests. Both share the same observed-history model and tools.
Cloudflare exposes bearer-key and MCP OAuth authentication for compatible remote Streamable HTTP clients. Sites uses its platform authentication and owner access checks. External harness authentication for a private Site must be tested in the chosen client; a URL alone does not establish compatibility.
Why use it
Search the Apple Music catalog and inspect a connected library.
Read playlists, recommendations, heavy rotation, and official Replay summaries.
Create playlists and safely append tracks with preview, matching, and duplicate checks.
Collect recently played tracks every two minutes into an indefinitely retained observed-history ledger.
Query bounded history pages, summaries, and rankings for preset or exact timeframes.
Connect with either a static bearer key or MCP OAuth discovery.
Keep Apple credentials in Worker secrets and encrypt the Apple music user token before D1 storage.
Related MCP server: Apple Music MCP Server
How it works
flowchart LR
Client["Remote MCP client"] -->|"Streamable HTTP + bearer or OAuth"| Worker["Cloudflare Worker"]
Setup["Protected browser setup"] -->|"MusicKit authorization"| Worker
Worker -->|"Developer token + music user token"| Apple["Apple Music API"]
Worker --> D1["Cloudflare D1"]
Worker --> KV["OAuth KV"]
Cron["Two-minute cron"] --> Worker
D1 --> Data["Observed history, analytics, audit log"]The Worker signs short-lived ES256 Apple developer tokens. Browser setup obtains a music user token, encrypts it with AES-GCM, and stores only the ciphertext in D1. A scheduled handler compares Apple’s current recently played window with the preceding snapshot and stores newly observed events.
Choose a deployment
Standalone Cloudflare | Private Sites | Local development | |
MCP endpoint | Worker | Site |
|
Availability | Always on | Published private Site | While Wrangler and computer run |
History collection | Two-minute Cron Trigger | Cloudflare timer forwards every two minutes | Manual or host-scheduled local requests |
Storage | D1 and OAuth KV in your account | Sites-managed | Simulated D1/KV under |
Best use | Compatible remote MCP clients | Sites plugin connection | Development or managed private host |
Use standalone Cloudflare for direct remote MCP client access, or private Sites for a Sites-managed plugin and database. Sites collection still uses a Cloudflare timer; its native tasks cannot supply a two-minute cadence. Neither deployment can backfill listening activity from before collection begins.
Prerequisites
You need:
Node.js 22.18 or newer and npm.
A Cloudflare account with Workers, D1, and KV access.
An Apple Developer Program account with Account Holder or Admin access for Media IDs and keys.
An active Apple Music subscription for the account you will connect.
For Cloudflare, an MCP client supporting remote Streamable HTTP. OAuth is optional because a static bearer key is available.
For Sites, the installed Sites plugin and an account with private hosting and service-access capability.
Part 1: Create Apple credentials
In Certificates, Identifiers & Profiles:
Open Identifiers and select +.
Choose Media IDs and continue.
Enter a user-facing description and a reverse-domain identifier.
Enable the Apple Music or MusicKit service and register the Media ID.
Open Keys, select +, and create a key with Media Services enabled.
Associate the key with the Media ID.
Download the
.p8private key immediately. Apple does not allow another download later.Record the key ID and your Apple Developer team ID.
Keep the .p8 file private. The server needs its complete contents, including the BEGIN PRIVATE KEY and END PRIVATE KEY lines.
Part 2: Deploy to Cloudflare
1. Get the project
git clone https://github.com/YOUR_GITHUB_OWNER/apple-music-mcp.git
cd apple-music-mcp
npm ciReplace YOUR_GITHUB_OWNER with the repository owner before cloning.
2. Sign in to Cloudflare
npx wrangler login
npx wrangler whoami3. Create the deployment configuration
cp wrangler.example.toml wrangler.tomlwrangler.toml is ignored by Git. Keep it local.
Create the OAuth KV namespace:
npx wrangler kv namespace create OAUTH_KVCopy the returned namespace ID into this block in wrangler.toml:
[[kv_namespaces]]
binding = "OAUTH_KV"
id = "<YOUR_KV_NAMESPACE_ID>"Create the D1 database:
npx wrangler d1 create apple-music-mcpCopy the returned database ID into wrangler.toml:
[[d1_databases]]
binding = "DB"
database_name = "apple-music-mcp"
database_id = "<YOUR_D1_DATABASE_ID>"
migrations_dir = "migrations"4. Create the secrets
Generate four different random values. Use a password manager or run this command four times:
openssl rand -base64 32Store each value under a different name:
Secret | Purpose |
| Static bearer key for |
| Unlocks the short-lived browser setup session. |
| Approves MCP OAuth clients; keep it distinct from |
| Encrypts the Apple music user token stored in D1. Keep it for the lifetime of that token. |
| Apple Developer team identifier used as JWT issuer. |
| Media Services private-key identifier. |
| Complete contents of the downloaded |
Set them interactively so they do not appear in shell history:
npx wrangler secret put MCP_API_KEY
npx wrangler secret put SETUP_TOKEN
npx wrangler secret put OAUTH_CONSENT_TOKEN
npx wrangler secret put TOKEN_ENCRYPTION_KEY
npx wrangler secret put APPLE_TEAM_ID
npx wrangler secret put APPLE_KEY_ID
npx wrangler secret put APPLE_PRIVATE_KEYDo not put secret values in wrangler.toml, source files, issue reports, or copied terminal output.
5. Apply the database schema
npx wrangler d1 migrations list apple-music-mcp --remote
npx wrangler d1 migrations apply apple-music-mcp --remoteThe migrations create:
auth_tokensfor the encrypted Apple music user token.configfor short-lived authorization state and the cached storefront.listen_eventsfor normalized observed listening events.track_resource_versionsfor deduplicated raw Apple payload versions.analytics_stateandanalytics_ingest_runsfor collection state and health.audit_logfor bounded MCP activity records.collector_runsfor attempted collection diagnostics.collector_controlfor shared collection leases and rate-limit cooldowns.
6. Validate and deploy
npm test
npm run typecheck
npx wrangler deploy --dry-run
npm run deployThe deploy output prints a URL such as:
https://apple-music-mcp.<YOUR_SUBDOMAIN>.workers.devYour primary MCP endpoint is:
https://apple-music-mcp.<YOUR_SUBDOMAIN>.workers.dev/mcp7. Connect the Apple Music account
Open this clean URL in a browser:
https://apple-music-mcp.<YOUR_SUBDOMAIN>.workers.dev/setupThen:
Enter
SETUP_TOKENin the protected form.Select Authorize Apple Music.
Complete Apple’s authorization prompt.
Wait for Apple Music connected.
The setup token is submitted in a POST body and exchanged for a ten-minute HttpOnly session. Do not add the token to the URL. The Apple authorization state is hashed at rest, bound to that browser session, expires after ten minutes, and is consumed once.
Apple does not provide a refresh token for the music user token. If access later expires, return to /setup and authorize again.
8. Connect an MCP client
Use one of the following authentication modes.
Option A: Static bearer key
Enter these fields in the client’s remote MCP server form:
Name:
Apple MusicURL:
https://apple-music-mcp.<YOUR_SUBDOMAIN>.workers.dev/mcpTransport:
Streamable HTTPHeader name:
AuthorizationHeader value:
Bearer <MCP_API_KEY>
If the client accepts JSON configuration, adapt this generic shape to its field names:
{
"name": "Apple Music",
"url": "https://apple-music-mcp.<YOUR_SUBDOMAIN>.workers.dev/mcp",
"transport": "streamable-http",
"headers": {
"Authorization": "Bearer <MCP_API_KEY>"
}
}Option B: MCP OAuth
For a client that implements MCP OAuth discovery:
Add only the
/mcpURL.Start the client’s authorization flow.
In the browser consent page, confirm the displayed client name.
Enter
OAUTH_CONSENT_TOKEN.Return to the client after authorization completes.
OAuth uses S256 PKCE, one-hour access tokens, 30-day refresh tokens, and the single apple_music scope. One deployment is intentionally one owner and one Apple Music account; every authorized client receives the same tool set.
9. Verify the connection
Call apple_music_status. A healthy result resembles:
{
"appleCredentialsConfigured": true,
"connected": true,
"storefront": "us"
}Then call apple_music_analytics_status to verify database coverage, the configured
poll interval, collector attempts, and any active cooldown. Observe at least two
actual scheduled runs about two minutes apart; a configured cron or a manual
refresh does not prove automatic collection.
Local development
1. Install and configure
npm ci
cp .dev.vars.example .dev.varsEdit .dev.vars with four different random values plus the Apple team ID, key ID, and complete private key. .dev.vars is ignored by Git.
Apply the local migrations:
npm run db:migrate:local2. Start the Worker
npm run dev:localKeep this process running. Open:
http://127.0.0.1:8787/setupEnter the local SETUP_TOKEN, authorize Apple Music, and connect a client to:
http://127.0.0.1:8787/mcpUse Authorization: Bearer <MCP_API_KEY> unless the client supports the local OAuth flow.
Do not expose port 8787 publicly. The server rejects browser requests whose Origin does not match the server origin, but local network binding, TLS, and firewall policy remain the operator’s responsibility.
3. Trigger local collection
Wrangler does not automatically fire Cron Triggers in a local session. While npm run dev:local is running, trigger one collection pass with:
curl -fsS 'http://127.0.0.1:8787/__scheduled?cron=%2A%2F2+%2A+%2A+%2A+%2A'For continuous local history, schedule that request every two minutes and keep Wrangler running. Local D1 and KV state persist under .wrangler/state; back up that directory separately if the observed history matters.
MCP tools
The server exposes 14 tools.
Tool | What it does | Important inputs |
| Checks Apple credentials, connection, token age, and storefront. | None |
| Pages through observed D1 history. |
|
| Reads Apple Music heavy rotation. |
|
| Reads personalized recommendation groups. |
|
| Reads official latest-year Replay totals and top content. | None |
| Lists library playlists and editability. |
|
| Reads tracks from a library playlist. |
|
| Searches songs, albums, artists, playlists, or music videos. |
|
| Creates an empty library playlist. |
|
| Resolves, previews, deduplicates, and appends up to 100 tracks. |
|
| Refreshes the observed listening ledger. |
|
| Reports ledger coverage and recent ingest runs. | None |
| Returns observed totals and top categories for a timeframe. |
|
| Ranks tracks, artists, albums, or genres. |
|
Timeframe examples
Last 30 days:
{
"preset": "30d",
"limit": 20
}Exact range with explicit offsets:
{
"start": "2026-08-01T00:00:00-06:00",
"end": "2026-08-15T00:00:00-06:00",
"limit": 50
}All observed history:
{
"preset": "all_time",
"limit": 50
}Presets are today, 24h, 7d, 30d, 90d, ytd, last_year, and all_time. Use either a preset or a custom inclusive start and optional exclusive end. Custom timestamps must include Z or a UTC offset. Calendar presets default to America/Denver; provide an IANA timeZone to override it.
History pages default to 50 and are capped at 200. When coverage.hasMore is true, pass nextCursor on the next call. The cursor preserves the original timeframe so a rolling preset cannot shift between pages.
Safe playlist writes
The playlist write surface is intentionally narrow:
It creates playlists and appends tracks; it does not delete, remove, reorder, or edit playlist metadata.
Unknown songs are matched against up to 10 catalog candidates.
Title, artist, and version checks reject unintended remixes, live recordings, covers, and similar variants.
Existing playlist tracks and duplicate request IDs are skipped.
One unresolved or ambiguous song blocks the batch unless
allowPartial: trueis explicitly chosen.dryRun: truepreviews matching and deduplication without changing Apple Music.A completed append is read back with bounded retries.
pending_apple_propagationmeans Apple accepted the write but its eventually consistent library read has not caught up yet.
Use dryRun: true before large or important batches.
Collection frequency and rate limits
The default is */2 * * * *: one poll every two minutes, or 720 scheduled polls
per full day before deferrals. Set COLLECTOR_POLL_INTERVAL_SECONDS to 120 in
both the authoritative collector and its deployment configuration. Cloudflare
cron timing can vary; diagnose coverage using actual stored runs.
Migration 0007_collector_control.sql adds a database-backed 180-second lease.
Scheduled and manual refreshes share it. A concurrent request returns a busy
deferral without contacting Apple. busy and cooldown deferrals return a
temporary run ID and retry time without creating a collector_runs row. The
Sites timer logs them as deferred, rather than successful polls. Successful history inserts and snapshot
advancement run in one atomic transaction fenced by that lease; a stale writer
cannot advance the snapshot after losing its lease.
An Apple 429 causes no immediate retry. The collector persists the complete
Retry-After delay, with a minimum of one minute and a five-minute default when
Apple does not supply a valid delay. Collection requests during that window return a
cooldown deferral. Inspect the reported retry time instead of issuing repeated
manual refreshes. Apple does not publish a numeric developer-token request
ceiling, so monitor actual 429 responses and plan-specific usage.
Standalone Cloudflare runs OAuth and audit maintenance at most once per hour. The usual two OAuth KV list scans per cleanup are about 48 scans daily, instead of 1,440 if cleanup ran on every two-minute tick; additional KV pages add usage. A Sites forwarding timer performs zero scheduled KV operations; legacy MCP/OAuth client traffic can still use KV. Sites collection still consumes requests, database operations and diagnostic storage, so verify the hosting account's allowances before shortening the interval further.
Listening-history limits
Apple’s recently played endpoint is not a historical export. It returns at most 30 tracks and does not include play timestamps.
As a result:
History cannot be backfilled.
observedAtis estimated within the polling interval; Apple may report changes late.Faster polling improves freshness and observation bounds, but does not measure actual play duration or identify skips.
More than 30 changes between polls can create a permanent gap.
A timeframe is not complete unless the collector covered all of it without a gap.
The ledger retains each observed event indefinitely, while identical raw Apple payloads are content-addressed and deduplicated.
apple_music_replay_summaryis the correct source for authoritative latest-year Replay totals.
Routes and authentication
Route | Access | Purpose |
| Public | Minimal service descriptor. |
| OAuth access token or | Primary Streamable HTTP endpoint. |
|
| Legacy endpoint name using the same MCP handler. |
| CSRF check plus | Owner approval for MCP OAuth clients. |
| OAuth protocol | Token exchange and refresh. |
| OAuth protocol | Dynamic client registration. |
| Short-lived session established with | Apple Music authorization page. |
| Setup session plus one-time state | Receives and encrypts the Apple music user token. |
Never put access tokens, setup tokens, or OAuth tokens in a URL.
Security model
All MCP calls require OAuth or the static bearer key.
Cross-origin browser MCP requests are rejected unless the
Originmatches the server origin.Setup and OAuth approval use different secrets.
Public form and JSON bodies are type-checked and size-limited before parsing.
Setup sessions are HMAC-authenticated, HttpOnly, SameSite, and ten minutes long.
Apple setup state is hashed, session-bound, expiring, and atomically consumed.
Apple’s music user token is encrypted with AES-GCM before D1 storage.
The Apple API origin is fixed and caller-controlled path components are encoded.
Tool inputs, result sizes, Apple request timeouts, retries, and concurrency are bounded.
Audit identity comes from authenticated server context, not a caller-supplied header.
Standalone Cloudflare audit rows are retained for
AUDIT_RETENTION_DAYS, defaulting to 90, with hourly audit and OAuth cleanup. Sites requires separately configured audit maintenance; setting the retention value alone does not schedule cleanup.Playlist writes are append-oriented and exclude destructive operations.
This remains a single-owner system. Anyone who receives either an OAuth grant or MCP_API_KEY can use every exposed tool against the one connected Apple Music account.
Updating an existing deployment
Back up the database, sequence state and OAuth KV to protected local storage. Retain the encryption key and deployment rollback version. Follow the update checklist without replacing account-specific local configuration with placeholders.
Apply all database migrations before deploying code, including
0007_collector_control.sql. Set COLLECTOR_POLL_INTERVAL_SECONDS = "120" and
crons = ["*/2 * * * *"] together. Changing only the interval setting does not
schedule requests; changing only the cron leaves incorrect diagnostics.
For Sites, publish the tested Sites source and migration with the supported Sites workflow, then update the Cloudflare bridge timer. Keep the destination's collector paused during final data transfer and keep only one authoritative collector active. See Sites migration.
Operations and troubleshooting
Useful commands
npm test
npm run typecheck
npm run dev:local
npm run db:migrate:local
npx wrangler d1 migrations list apple-music-mcp --remote
npx wrangler deploy --dry-run
npx wrangler tailMCP returns Unauthorized
For static authentication, confirm the client sends exactly:
Authorization: Bearer <MCP_API_KEY>For OAuth, restart the client’s authorization flow if its access and refresh tokens have expired.
Apple Music is disconnected
Open /setup, enter SETUP_TOKEN, and authorize again. If the page reports missing Apple credentials, check:
npx wrangler secret listHistory is shorter than expected
Call apple_music_analytics_status, confirm the two-minute cron is deployed, and inspect recent ingest runs. Downtime and more than 30 upstream changes between polls cannot be recovered later.
Raw HTTP testing returns Not Acceptable
Streamable HTTP requests must accept both supported response types:
Accept: application/json, text/event-streamNormal MCP clients set this automatically.
Local state reset
Local D1, KV, authorization, and history live under .wrangler/state. Removing that directory resets local state. Back it up before resetting if the observed history matters.
Project structure
src/
index.ts Cloudflare routes, MCP authentication, OAuth, and scheduled work
sites.ts Private Sites MCP and browser entrypoint
sites-operations.ts Authenticated service collection and migration routes
sites-trigger.ts Cloudflare-to-Sites scheduled forwarding
collector-control.ts Shared leases, cooldowns, and hourly maintenance
setup.ts Protected browser MusicKit authorization flow
setup-session.ts Short-lived signed setup-session tokens
http-security.ts Body limits, cookie parsing, comparisons, and security headers
mcp.ts Tool definitions, schemas, safety metadata, and write verification
apple.ts Apple Music API client and developer-token signing
apple-transport.ts Timeouts, retry policy, and bounded concurrency
analytics.ts D1 collection, history pagination, and SQL statistics
recent-history.ts Snapshot diffing and history cursors
timeframe.ts Preset and custom timeframes
song-matching.ts Conservative catalog matching
storage.ts Encrypted token, config, audit, and retention persistence
crypto.ts ES256 signing and AES-GCM encryption
format.ts Compact MCP response formatting
types.ts Worker and Apple API types
migrations/ Ordered Cloudflare D1 schema migrations
db/schema.ts Sites Drizzle schema
drizzle/ Generated Sites migrations and journal
drizzle.config.ts Sites migration-generation configuration
test/ Functional, safety, storage, and metadata tests
wrangler.example.toml Cloudflare deployment template
wrangler.local.toml Local workerd, D1, and KV configurationOfficial references
This server cannot be deployed
Maintenance
Related MCP Connectors
The media memory layer for AI agents and their humans. Your AI client gets 29 tools to search your collection, add items, update ratings, preview music, and find patterns across everything you've read, watched, and listened to.
Music marketing for AI agents: free Smart Links, promotion campaigns, analytics, and distribution.
Personal context and preferences for AI via OAuth-approved profile sections and taste data.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables AI assistants to control Spotify playback, manage playlists, search music, and access listening history. Requires Spotify Premium and uses secure OAuth 2.0 with PKCE authentication.1372 npmMIT
- FlicenseNot gradedqualityDmaintenanceIntegrates Apple Music with MCP clients to search the global catalog, manage personal playlists, and access library data. It enables users to perform actions like creating playlists, adding tracks, and viewing recommendations through natural language commands.1-
- AlicenseNot gradedqualityDmaintenanceConnects Claude Code to Apple Music using only your Apple ID, without needing a developer account. Enables access to recently played, playlists, search, recommendations, and playlist creation.11 npmMIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to control Spotify playback, search music, manage playlists and library, and access user listening insights via the Spotify Web API.-