GraphQL API
The GraphQL API runs standalone in headless mode, or alongside the TUI when asked for with --api or [graphql] enabled = true (port 4000, localhost only). The TUI does not serve it unasked, because a server with no accounts makes whoever opens /setup first its admin.
Quick start
# TUI + API
koan --api
# Headless with GraphiQL web IDE
KOAN_SERVER__URL=http://localhost:4000 koan --headless --playground
# As a background daemon
KOAN_SERVER__URL=http://localhost:4000 koan -d --playgroundThen open http://localhost:4000/graphql for the GraphiQL IDE, or query directly:
# If auth is enabled (default), get a token first
TOKEN=$(curl -s -X POST http://localhost:4000/auth/login \
-H 'Content-Type: application/json' \
-d '{"username": "admin", "password": "your-password"}' | jq -r '.access_token')
curl -s http://localhost:4000/graphql \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-d '{"query": "{ nowPlaying { state, track { title, artist } } }"}'A script is better served by an API key (koan auth api-key create --username <user> --name <key>, or API keys in the web UI or the apps' Settings), sent the same way as Authorization: Bearer <key>: it does not expire, and it can be revoked without touching the account's password.
The IDE is for a server on your own machine: its key grants admin without signing in. A deployed server runs without --playground and is explored with a GraphQL client and an API key or access token (see Authentication).
Authentication
Auth is enabled by default. Run koan auth setup to create a keypair and first admin user before starting the server. See Authentication for the full guide.
koan auth setup # generate keypair + create admin user
KOAN_SERVER__URL=http://localhost:4000 koan --headless --playground # start serverTo disable auth:
[graphql]
auth_enabled = falseWith auth disabled, anything that can reach the port is an admin; see Recovery / lockout before doing it.
Configuration
[graphql]
enabled = false # run alongside TUI (default: false, same as --api)
port = 4000 # API port (default: 4000)
bind = "127.0.0.1" # bind address (default: 127.0.0.1)
playground = false # GraphiQL IDE at GET /graphql (default: false)
auth_enabled = true # JWT authentication (default: true)
access_token_ttl = "15m" # access token lifetime (default: 15m)
refresh_token_ttl = "30d" # refresh token lifetime (default: 30d)The server binds to 127.0.0.1 by default. Use --bind 0.0.0.0 or bind = "0.0.0.0" in config to expose on all interfaces.
Example queries
Library browsing
# Find early FLAC albums
{
albums(yearEnd: 1995, codec: "FLAC") {
edges { node { title, artistName, date } }
}
}
# Hi-res techno tracks
{
tracks(genre: "techno", minSampleRate: 96000, minBitDepth: 24) {
edges { node { title, artist, codec, sampleRate } }
}
}
# Nested: artist -> albums -> tracks
{
artists(search: "Aphex") {
edges {
node {
name
albums {
edges {
node {
title
tracks { edges { node { title } } }
}
}
}
}
}
}
}Playback control
# What's playing?
#
# `seekableMs` is how far in a seek can land. It equals `durationMs` for
# anything on disk and falls short of it while a track is still downloading,
# so a client draws its seek bar against it rather than letting someone scrub
# into audio that has not arrived. `moving` is whether the playhead is
# advancing: false while paused, and while playing but waiting on a download.
# The `nowPlaying` subscription sends again on a seek, a stall, a pause or a
# drift past 1 s, not as the playhead runs on time, so a client counts on from
# `positionMs` while `moving` is true.
{
nowPlaying {
state
positionMs
durationMs
seekableMs
moving
shuffle
repeat
track { title, artist, codec, sampleRate, bitDepth }
}
}
# Shuffle plays the tracks not yet played in a random order, each once, and
# never moves the queue; `queue` marks what has played as PLAYED whatever its
# place. Repeat is OFF, QUEUE or ONE. `setPlayModeOnClient` does the
# same on a linked app, whose modes `clients { shuffle repeat }` reports.
mutation { setPlayMode(shuffle: true, repeat: QUEUE) { ok } }
# Replacing the queue to play it turns shuffle and repeat off, as a play
# button does; `shuffle: true` (`shuffled` on playPlaylist) queues the tracks
# in a random order. Enqueueing leaves the order and the modes alone.
mutation { playOnClient(trackIds: ["42", "43"], shuffle: true) { ok } }
# Stop after 30 minutes, fading out, or at the end of the record (endOf:
# RECORD; TRACK for the track). It pauses and keeps the queue. The ...OnClient
# forms set a linked app's; `nowPlaying { sleep { remainingMs endOf } }` and
# `clients { sleep { ... } }` show what is set.
mutation { setSleepTimerOnClient(minutes: 30) { ok } }
mutation { cancelSleepTimerOnClient { ok } }
# Queue management
mutation { replaceQueue(trackIds: [42, 43, 44]) { ok, addedCount } }
mutation { saveQueueAsPlaylist(name: "techno friday") { id, name, trackCount } }
# Playlists
{ playlists { id, name, trackCount, durationMs, remoteId } }
{ playlistTracks(id: 3) { id, title, artist } }
mutation { addToPlaylist(id: 3, trackIds: [42, 43]) { ok } }
# A reorder, a removal and a shuffle are all the same call: the list you want.
mutation { setPlaylistTracks(id: 3, trackIds: [43, 42]) { ok } }
mutation { playPlaylist(id: 3, shuffled: true) { ok } }
# Smart playlists: rules instead of a list. See Smart playlists for the format.
mutation {
createSmartPlaylist(name: "On repeat", rules: {
rules: [{ field: "lastPlayed", op: "inTheLast", value: 14 }]
sort: [{ field: "playCount", desc: true }], limit: 25
}) { id, trackCount, readonly, rules }
}
mutation { setPlaylistRules(id: 4, rules: null) { id, readonly } }Filtering
Collection queries filter on:
- Albums: year range, codec, label, genre
- Tracks: genre, codec, sample rate, bit depth, duration
- Artists: genre
All string filters are case-insensitive substrings. % and _ in a filter value are literal, not wildcards.
Pagination and sorting
Collections are Relay connections (edges + pageInfo). A collection with no first returns 50 rows, and first is capped at 500 — the API will not hand back a whole library in one response. Page with the cursor from pageInfo.endCursor:
{
tracks(first: 200, after: "199", sortBy: TITLE, sortDir: DESC) {
edges { cursor node { title } }
pageInfo { hasNextPage endCursor }
}
}sortBy accepts TITLE, ARTIST, ALBUM, DURATION or ARTIST_ALBUM_DISC_TRACK for tracks; NAME, ALBUM_COUNT or TRACK_COUNT for artists; TITLE, DATE, ARTIST_THEN_DATE or TRACK_COUNT for albums.
Long-running work
triggerScan and triggerRemoteSync run for minutes, so they return a job handle immediately and do the work on a detached thread:
mutation { triggerScan { id kind state } }
{ job(id: "0199...") { state message } }state is RUNNING, SUCCEEDED or FAILED; message carries the outcome. triggerScan(reread: true) reads every file's tags again, including files the scan cache says are unchanged. Only one job of each kind runs at a time — calling again while one is live returns the running job rather than starting a second.
The server also scans the library by itself: at start-up, when the library folders change, when a folder is added or a volume holding one is mounted again, and every fifteen minutes for a folder on a network share, where another machine's writes raise no event. Each of those scans is a job of kind watch, listed by jobs, with reason saying which it was (start-up, folder change, periodic or new folder). While a scan runs, done counts the files whose tags it has read and total the files it has found to need reading so far; with the scan cache, that is only the files that changed.
subscription { jobs { kind reason state message done total } } sends the same list as jobs, and again whenever a job starts, reports progress or ends, so a client can show the server's scan without polling. job, jobs and the subscription are for admins, as starting a job is.
Each job has startedAt and finishedAt, in Unix milliseconds.
The server's caches
serverCaches reports what the server keeps beside the library, for diagnosing slow covers without reading its logs or its config directory:
{ serverCaches {
covers { bytes budget misses unwarmed sizes { size covers bytes misses }
warm { state sizes done total made finishedAt nextAt } lastSweep { at removed bytes } }
downloads { bytes limit tracks }
lastScan { kind state startedAt finishedAt message } } }warm.state is RUNNING, AT_BUDGET (the cache is full, so covers are made only as asked for), IDLE or OFF (an app sharing its own library, which makes covers as asked). unwarmed counts the records still without a cover at one of warm.sizes. clearCoverCache removes every kept cover and warmCovers starts a pass now. All three are for admins. Transcodes are encoded as they stream and never kept, so there is nothing to report for them.
Limits
Requests are refused rather than queued when the server is saturated, so a slow client cannot make every other client slow:
- query depth 12, complexity 2000
- 30 second timeout on a query (
408); subscriptions are exempt - 64 queries in flight, beyond which further requests get
503immediately
The schema
--playground serves GraphiQL at /graphql, which browses the schema. The MCP tool schema_sdl returns the same schema as SDL.
Subsonic API
The server's Subsonic API, at /rest on the same port, is configured separately; see Configuration and Authentication.
MCP server
The MCP server (koan mcp) uses the same GraphQL schema in-process (no HTTP round-trip). See MCP Integration for Claude Desktop setup.