Skip to main content

koan_server/
mcp.rs

1//! MCP (Model Context Protocol) server for koan.
2//!
3//! Exposes the GraphQL schema as MCP tools for Claude Desktop / MCP clients.
4
5use std::sync::Arc;
6
7use crate::auth::AuthUser;
8use crossbeam_channel::Sender;
9use koan_core::player::commands::PlayerCommand;
10use koan_core::player::state::SharedPlayerState;
11use rmcp::handler::server::router::tool::ToolRouter;
12use rmcp::handler::server::wrapper::Json;
13use rmcp::model::{ServerCapabilities, ServerConfig};
14use rmcp::{ServerHandler, schemars, tool_router};
15use serde::{Deserialize, Serialize};
16
17// ---------------------------------------------------------------------------
18// Parameter types
19// ---------------------------------------------------------------------------
20
21#[derive(Debug, Deserialize, schemars::JsonSchema)]
22pub struct GraphqlParams {
23    #[schemars(
24        description = "GraphQL query or mutation string. Use the schema_sdl tool first to learn available types, queries, mutations, and filter parameters."
25    )]
26    pub query: String,
27    #[schemars(description = "Optional JSON object of query variables")]
28    pub variables: Option<serde_json::Value>,
29}
30
31// ---------------------------------------------------------------------------
32// Response types
33// ---------------------------------------------------------------------------
34
35/// GraphQL execution result wrapper — MCP spec requires outputSchema to be an object type.
36#[derive(Debug, Serialize, schemars::JsonSchema)]
37pub struct GraphqlResponse {
38    /// The GraphQL response JSON (contains data and/or errors fields).
39    pub result: serde_json::Value,
40}
41
42// ---------------------------------------------------------------------------
43// MCP Server
44// ---------------------------------------------------------------------------
45
46#[derive(Clone)]
47pub struct KoanMcpServer {
48    #[allow(dead_code)]
49    tool_router: ToolRouter<Self>,
50    graphql_schema: crate::graphql::KoanSchema,
51    /// A headless server: its own player is heard by nobody, and the music
52    /// plays on the devices linked to it.
53    headless: bool,
54    /// `sharing.public_url`, where an MCP client fetches koan's icon from.
55    public_url: Option<String>,
56}
57
58impl KoanMcpServer {
59    pub fn new(
60        state: Arc<SharedPlayerState>,
61        cmd_tx: Sender<PlayerCommand>,
62        pool: Arc<koan_core::db::pool::Pool>,
63    ) -> Self {
64        let graphql_schema = crate::graphql::build_schema_extended(state, cmd_tx, pool, Denylist);
65        Self {
66            tool_router: Self::tool_router(),
67            graphql_schema,
68            headless: false,
69            public_url: None,
70        }
71    }
72
73    /// Who a request acts as: the account `bearer_gate` found its token for,
74    /// at most at `capped` role; on stdio, the local user at `mcp_role()`.
75    fn caller(&self, extensions: &rmcp::model::Extensions) -> AuthUser {
76        extensions
77            .get::<axum::http::request::Parts>()
78            .and_then(|p| p.extensions.get::<AuthUser>())
79            .map(|u| AuthUser {
80                role: capped(u.role),
81                ..u.clone()
82            })
83            .unwrap_or_else(|| AuthUser {
84                user_id: koan_core::db::queries::LOCAL_USER,
85                role: mcp_role(),
86                ..AuthUser::anonymous_admin()
87            })
88    }
89}
90
91use rmcp::handler::server::wrapper::Parameters;
92use rmcp::tool;
93
94/// Role the MCP `graphql` tool executes at.
95///
96/// The transport carries no credential, so anything reachable here is reachable
97/// by whoever can talk to the MCP process. `User` covers everything the tool
98/// advertises — browsing, playback, queue, favourites, playlists — and
99/// leaves out the admin mutations that move files on disk (`organize*`), rewrite
100/// config, or change the output device. `KOAN_MCP_ADMIN=1` opts back in.
101fn mcp_role() -> koan_core::auth::Role {
102    if std::env::var("KOAN_MCP_ADMIN").is_ok_and(|v| v == "1") {
103        koan_core::auth::Role::Admin
104    } else {
105        koan_core::auth::Role::User
106    }
107}
108
109/// Mutations the MCP never runs, whoever is calling and at whatever role,
110/// `KOAN_MCP_ADMIN` included: everything that moves or rewrites files on disk,
111/// and the config that says where the library is. A model that has been
112/// misled, or is simply wrong, can then lose nobody any music. GraphQL itself
113/// still offers them to an admin.
114pub const DENIED_MUTATIONS: &[&str] = &["organizeExecute", "organizeUndo", "updateConfig"];
115
116/// Refuses `DENIED_MUTATIONS` as they resolve, so no alias, fragment or
117/// variable spelling of the query gets past it.
118struct Denylist;
119
120impl async_graphql::extensions::ExtensionFactory for Denylist {
121    fn create(&self) -> Arc<dyn async_graphql::extensions::Extension> {
122        Arc::new(Denylist)
123    }
124}
125
126#[async_trait::async_trait]
127impl async_graphql::extensions::Extension for Denylist {
128    async fn resolve(
129        &self,
130        ctx: &async_graphql::extensions::ExtensionContext<'_>,
131        info: async_graphql::extensions::ResolveInfo<'_>,
132        next: async_graphql::extensions::NextResolve<'_>,
133    ) -> async_graphql::ServerResult<Option<async_graphql::Value>> {
134        if info.parent_type == "MutationRoot" && DENIED_MUTATIONS.contains(&info.name) {
135            return Err(async_graphql::ServerError::new(
136                format!("{} is not available through MCP", info.name),
137                None,
138            ));
139        }
140        next.run(ctx, info).await
141    }
142}
143
144/// The role an account acts at through the MCP: its own, but no higher than
145/// `mcp_role()`. Track titles, tags and share descriptions reach the model, and
146/// any of them may carry an instruction; capped, an admin account's model
147/// cannot be talked into moving files or rewriting config.
148pub fn capped(role: koan_core::auth::Role) -> koan_core::auth::Role {
149    use koan_core::auth::Role;
150    match (role, mcp_role()) {
151        (Role::Admin, Role::User) => Role::User,
152        (role, _) => role,
153    }
154}
155
156#[tool_router]
157impl KoanMcpServer {
158    #[tool(
159        description = "The GraphQL schema for the user's music (kōan): their library and the \
160        players they listen on. Call this first, before `graphql`. It covers playing, pausing, \
161        skipping and queueing music on the user's phone and computers, what is playing now, \
162        and searching, browsing and making playlists from the music they own."
163    )]
164    fn schema_sdl(&self) -> Json<GraphqlResponse> {
165        let sdl = self.graphql_schema.sdl();
166        Json(GraphqlResponse {
167            result: serde_json::Value::String(sdl),
168        })
169    }
170
171    #[tool(
172        description = "Control the user's music and search their music library (kōan). Use it \
173        for any request about music they listen to or own: play something, pause, resume, skip, \
174        what's playing, what's next, add to or change the queue, find or recommend from their \
175        collection, playlists, favourites. \"Pause the music on my desktop\", \"play some \
176        jazz on my phone\" and \"what is this song\" are all this tool.\n\n\
177        Call schema_sdl first for the full schema. The user's phones and computers running \
178        kōan are `clients`; commands for them end in `OnClient`.\n\n\
179        Examples:\n\
180        - What's playing, where: { clients { name playing nowPlaying positionMs } }\n\
181        - Pause: mutation { controlClient(action: PAUSE) { ok message } }\n\
182        - Find music: { tracks(search: \"aphex\", first: 20) { edges { node { id title artist album } } } }\n\
183        - Play it: mutation { playOnClient(trackIds: [\"42\", \"43\"]) { ok message } }\n\n\
184        String filters are case-insensitive substrings."
185    )]
186    async fn graphql(
187        &self,
188        Parameters(params): Parameters<GraphqlParams>,
189        extensions: rmcp::model::Extensions,
190    ) -> Json<GraphqlResponse> {
191        let caller = self.caller(&extensions);
192        let result = crate::graphql::execute_in_process(
193            &self.graphql_schema,
194            &params.query,
195            params.variables,
196            caller,
197        )
198        .await;
199        Json(GraphqlResponse { result })
200    }
201}
202
203impl KoanMcpServer {
204    /// Who this server is to a client, with the icon a client shows beside it.
205    /// Without an icon, clients guess from the domain and find its parent's.
206    fn implementation(&self) -> rmcp::model::Implementation {
207        let info =
208            rmcp::model::Implementation::new("koan", env!("CARGO_PKG_VERSION")).with_title("kōan");
209        match self.public_url.as_deref().map(|u| u.trim_end_matches('/')) {
210            Some(base) => info.with_website_url(base).with_icons(vec![
211                rmcp::model::Icon::new(format!("{base}/ui/assets/icon-192.png"))
212                    .with_mime_type("image/png")
213                    .with_sizes(vec!["192x192".into()]),
214            ]),
215            None => info,
216        }
217    }
218}
219
220#[rmcp::tool_handler]
221impl ServerHandler for KoanMcpServer {
222    fn get_info(&self) -> ServerConfig {
223        // Over HTTP this is a server: its own player is headless and nobody
224        // hears it, and what the user listens to is the apps linked to it. On
225        // stdio it is the user's own machine, and its player is the music.
226        let instructions = if self.headless {
227            SERVER_INSTRUCTIONS
228        } else {
229            LOCAL_INSTRUCTIONS
230        };
231        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
232            .with_server_info(self.implementation())
233            .with_instructions(instructions)
234    }
235}
236
237const SERVER_INSTRUCTIONS: &str = "kōan is the user's music: their whole music library, and the \
238phones and computers they listen on. Use it for anything about music they are playing or own — \
239\"pause the music\", \"play something like Polar Bear on my phone\", \"what's this song\", \
240\"skip to the Phace remix\", \"add their new album when it's downloaded\". Call `schema_sdl` \
241once, then do everything through `graphql`.
242
243## Where the music plays
244The user listens in kōan apps on their devices, linked to this server. Query \
245`clients { name platform playing nowPlaying album positionMs durationMs queue { trackId \
246title artist current } }` to see each device, what it is playing and what it has queued. Every \
247command about the user's music goes to a device:
248- `controlClient(action: PAUSE|RESUME|NEXT|PREVIOUS)`, `seekOnClient(positionMs)`
249- `playOnClient(trackIds, startAt)` replaces the queue and plays; `enqueue: true` appends. \
250A phone iOS has suspended is not linked but is still reached. Music comes up there as a \
251notification to tap, since iOS lets no app start audio on its own from sleep; queue and \
252other changes are applied as it wakes. The message says when a device was asleep: tell the user \
253to tap the notification
254- `playNextOnClient(trackIds)`, `jumpOnClient(trackId)` (skip to a track, queued or not), \
255`removeFromClient(trackIds)`, `clearClient`, `syncClient`
256- **Making a playlist the user asked for** (\"make me a cyberpunk playlist\"): research what \
257fits, find each track in the library, `createPlaylist` with those in order. For picks the \
258library lacks, fetch the album with slsk's `grab`, then `addToPlaylistWhenAdded(playlistId, \
259artist, album, titles)` to add the wanted tracks once it is imported. Tell the user what is \
260there now and what is on its way.
261- Playlists made or edited here (`createPlaylist`, `setPlaylistTracks`…) reach every device \
262by themselves: linked ones sync at once, others when next opened. `syncClients` does the same \
263on request.
264- `evictOnClients(trackIds)` makes every linked device drop its downloaded copies of those \
265tracks: when a track plays as noise or glitches, after the file on the server is replaced
266- `queueOnClientWhenAdded(artist, album)` queues an album once it reaches the library, e.g. \
267one being downloaded with slsk's `grab`; `clientOrders` lists those waiting
268Leave `client` out unless the user named a device (\"my phone\", \"the desktop\": match it \
269against `clients` names and platforms). Without it the server picks the device that is \
270playing, else the one played most recently; if it answers that it cannot tell, ask the user \
271which device.
272
273**Act on what the user asks; do not second-guess it from reported state.** \"Pause\", \
274\"skip\" and \"resume\" go straight to `controlClient`: the user can hear the device and you \
275cannot, and a report can be stale or, from an older app (`playing: null`), absent.
276
277**Never use the server's own player for the user's music.** `play`, `pause`, `resume`, \
278`next`, `previous`, `seek`, `nowPlaying`, `queue`, `addToQueue`, `replaceQueue`, \
279and `playPlaylist` drive a headless player on the server that nobody \
280hears; `nowPlaying` there reports nothing about what the user is listening to.
281
282## The library
283- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
284duration, favourites), `randomTracks`, `fuzzySearch`
285- Build a set from these, then send its track ids to a device with `playOnClient`. Track ids are \
286integers in queries; pass them to the client mutations as strings.
287- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
288- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `addToPlaylist`, \
289`setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`
290- History: `playHistory`
291- Sharing: `createShare(trackIds, description)` makes a public link anyone can open without an \
292account; confirm with the user first. `shares`, `updateShare`, `deleteShare` manage them.
293
294## Not available
295`organizeExecute`, `organizeUndo` (move files on disk) and `updateConfig` are never run \
296through MCP. Other admin mutations (`triggerScan`, user management) are refused unless \
297`KOAN_MCP_ADMIN=1` is set.";
298
299const LOCAL_INSTRUCTIONS: &str = "kōan is the user's music player on this machine and their \
300music library. Use it for anything about music they are playing or own — \"pause the music\", \
301\"play something like Polar Bear\", \"what's this song\". Call `schema_sdl` once, then do \
302everything through `graphql`.
303
304## Playback
305This player is what the user hears: `play`, `pause`, `resume`, `stop`, `next`, `previous`, \
306`seek`, `nowPlaying`; the queue with `queue`, `addToQueue`, `replaceQueue`, `removeFromQueue`, \
307`moveInQueue`, `clearQueue`, `undo`, `redo`.
308
309## The library
310- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
311duration, favourites), `randomTracks`, `fuzzySearch`
312- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
313- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `saveQueueAsPlaylist`, \
314`addToPlaylist`, `setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`, `playPlaylist`
315- History: `playHistory`
316- Sharing: `createShare(trackIds, description)` makes a public link; confirm with the user first.
317
318## Not available
319`organizeExecute`, `organizeUndo` (move files on disk) and `updateConfig` are never run \
320through MCP. `triggerScan` and `setDevice` are refused unless `KOAN_MCP_ADMIN=1` is set.
321
322## IDs
323Track IDs are integers from the library; queue item IDs are UUIDs from the queue.";
324
325const MAX_BODY: usize = 1024 * 1024;
326/// Open event streams count against it, so it allows a few clients each with
327/// a stream and requests in flight.
328const MAX_CONCURRENT: usize = 64;
329
330/// `/mcp` on the main port, for clients holding a token from koan's own OAuth
331/// (`ui::oauth`). Each request acts as the account its token names, at that
332/// account's role.
333pub fn router(
334    state: Arc<SharedPlayerState>,
335    cmd_tx: Sender<PlayerCommand>,
336    auth: crate::auth::middleware::AuthState,
337    public_url: Option<String>,
338    headless: bool,
339    shutdown: tokio_util::sync::CancellationToken,
340) -> axum::Router {
341    use rmcp::transport::streamable_http_server::{
342        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
343    };
344    let mut template = KoanMcpServer::new(state, cmd_tx, auth.pool.clone());
345    template.headless = headless;
346    template.public_url = public_url.clone();
347    let service = StreamableHttpService::new(
348        move || Ok(template.clone()),
349        Arc::new(LocalSessionManager::default()),
350        // The main app's Host guard has already checked the Host. Cancelled at
351        // shutdown, so open event streams end rather than hold it up.
352        StreamableHttpServerConfig::default()
353            .disable_allowed_hosts()
354            .with_cancellation_token(shutdown),
355    );
356    // No request timeout: a session's GET is an event stream that stays open.
357    axum::Router::new()
358        .nest_service("/mcp", service)
359        .layer(tower_http::catch_panic::CatchPanicLayer::new())
360        .layer(tower_http::limit::RequestBodyLimitLayer::new(MAX_BODY))
361        .layer(axum::middleware::from_fn_with_state(
362            (auth, public_url),
363            bearer_gate,
364        ))
365        .layer(
366            tower::ServiceBuilder::new()
367                .layer(axum::error_handling::HandleErrorLayer::new(
368                    |_: tower::BoxError| async {
369                        (axum::http::StatusCode::SERVICE_UNAVAILABLE, "busy")
370                    },
371                ))
372                .load_shed()
373                .concurrency_limit(MAX_CONCURRENT),
374        )
375}
376
377/// Let a request with a valid access token through as its account. Without
378/// one, the 401 names the resource metadata, which is how a client finds where
379/// to sign in.
380async fn bearer_gate(
381    axum::extract::State((auth, public_url)): axum::extract::State<(
382        crate::auth::middleware::AuthState,
383        Option<String>,
384    )>,
385    mut req: axum::extract::Request,
386    next: axum::middleware::Next,
387) -> axum::response::Response {
388    use axum::http::{Method, StatusCode, header};
389    use axum::response::IntoResponse;
390    // Someone who pasted the address into a browser: show them what it is for.
391    let browser = req.method() == Method::GET
392        && !req.headers().contains_key(header::AUTHORIZATION)
393        && req
394            .headers()
395            .get(header::ACCEPT)
396            .and_then(|v| v.to_str().ok())
397            .is_some_and(|a| a.contains("text/html"));
398    if browser {
399        return axum::response::Redirect::to("/connect").into_response();
400    }
401    let user = if auth.auth_enabled {
402        let token = req
403            .headers()
404            .get(header::AUTHORIZATION)
405            .and_then(|v| v.to_str().ok())
406            .and_then(|v| v.strip_prefix("Bearer "))
407            .and_then(|t| {
408                koan_core::auth::validate_scoped_token(
409                    &auth.public_pem,
410                    t,
411                    Some(koan_core::auth::MCP_SCOPE),
412                )
413                .ok()
414            });
415        match token {
416            Some(claims) => crate::auth::current_user(&auth.pool, claims).await,
417            None => None,
418        }
419    } else {
420        Some(AuthUser::anonymous_admin())
421    };
422    match user {
423        Some(user) => {
424            req.extensions_mut().insert(user);
425            next.run(req).await
426        }
427        None => {
428            // Without `public_url` there is no OAuth to point the client at.
429            let challenge = match public_url.as_deref().map(|u| u.trim_end_matches('/')) {
430                Some(base) => format!(
431                    "Bearer resource_metadata=\"{base}{}\"",
432                    crate::ui::RESOURCE_METADATA
433                ),
434                None => "Bearer".to_owned(),
435            };
436            (
437                StatusCode::UNAUTHORIZED,
438                [(header::WWW_AUTHENTICATE, challenge)],
439                "sign in to kōan",
440            )
441                .into_response()
442        }
443    }
444}
445
446/// Entry point for `koan mcp` — starts a headless player with an MCP server on stdio.
447pub fn cmd_mcp() {
448    use koan_core::player::Player;
449    use rmcp::ServiceExt;
450
451    // Validate DB is accessible before starting the server.
452    let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
453    let db_path = koan_core::config::db_path();
454
455    // Spawn the player engine (headless — no TUI).
456    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
457
458    let pool = Arc::new(koan_core::db::pool::Pool::new(db_path));
459    let server = KoanMcpServer::new(state, cmd_tx, pool);
460
461    // Run the MCP server on the tokio runtime (blocking the main thread).
462    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
463    rt.block_on(async {
464        let transport = rmcp::transport::io::stdio();
465        let service = server
466            .serve(transport)
467            .await
468            .expect("failed to start MCP server");
469        let _ = service.waiting().await;
470    });
471}
472
473// ---------------------------------------------------------------------------
474// Tests
475// ---------------------------------------------------------------------------
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use koan_core::db::connection::Database;
481    use koan_core::db::queries;
482    use koan_core::player::commands::CommandChannel;
483    use tempfile::TempDir;
484
485    fn test_server() -> (KoanMcpServer, CommandChannel, TempDir) {
486        let tmp = TempDir::new().unwrap();
487        let db_path = tmp.path().join("test.db");
488        let db = Database::open(&db_path).unwrap();
489        koan_core::db::schema::create_tables(&db.conn).unwrap();
490
491        let state = SharedPlayerState::new();
492        let ch = CommandChannel::new();
493        let tx = ch.tx.clone();
494
495        let server =
496            KoanMcpServer::new(state, tx, Arc::new(koan_core::db::pool::Pool::new(db_path)));
497        (server, ch, tmp)
498    }
499
500    fn as_user(user: AuthUser) -> rmcp::model::Extensions {
501        let (mut parts, ()) = axum::http::Request::new(()).into_parts();
502        parts.extensions.insert(user);
503        let mut ext = rmcp::model::Extensions::new();
504        ext.insert(parts);
505        ext
506    }
507
508    #[test]
509    fn a_token_acts_as_its_account_with_admin_capped() {
510        use koan_core::auth::Role;
511        let (server, _ch, _tmp) = test_server();
512        let user = |role| AuthUser {
513            user_id: 7,
514            username: "mate".into(),
515            role,
516        };
517        let c = server.caller(&as_user(user(Role::Admin)));
518        assert_eq!((c.user_id, c.username.as_str()), (7, "mate"));
519        assert_eq!(c.role, capped(Role::Admin));
520        assert_eq!(
521            server.caller(&as_user(user(Role::Readonly))).role,
522            Role::Readonly
523        );
524        // stdio: the local user, at the transport's default role.
525        let local = server.caller(&Default::default());
526        assert_eq!(
527            (local.user_id, local.role),
528            (queries::LOCAL_USER, mcp_role())
529        );
530    }
531
532    #[tokio::test]
533    async fn a_browser_opening_mcp_is_shown_how_to_connect() {
534        use tower::ServiceExt as _;
535        let (_server, ch, tmp) = test_server();
536        let auth = crate::auth::middleware::AuthState {
537            public_pem: Arc::new(Vec::new()),
538            auth_enabled: true,
539            introspection_key: None,
540            pool: Arc::new(koan_core::db::pool::Pool::new(tmp.path().join("test.db"))),
541        };
542        let app = router(
543            SharedPlayerState::new(),
544            ch.tx.clone(),
545            auth,
546            None,
547            true,
548            Default::default(),
549        );
550        let req = |accept: &str| {
551            axum::http::Request::get("/mcp")
552                .header(axum::http::header::ACCEPT, accept)
553                .body(axum::body::Body::empty())
554                .unwrap()
555        };
556        let r = app.clone().oneshot(req("text/html,*/*")).await.unwrap();
557        assert_eq!(r.headers()[axum::http::header::LOCATION], "/connect");
558        let r = app.oneshot(req("text/event-stream")).await.unwrap();
559        assert_eq!(r.status(), axum::http::StatusCode::UNAUTHORIZED);
560    }
561
562    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
563    async fn mutations_that_touch_files_are_refused_whoever_asks() {
564        use koan_core::auth::Role;
565        let (server, _ch, _tmp) = test_server();
566        let admin = as_user(AuthUser {
567            user_id: 1,
568            username: "owner".into(),
569            role: Role::Admin,
570        });
571        let Json(resp) = server
572            .graphql(
573                Parameters(GraphqlParams {
574                    query: "mutation { undo: organizeUndo { ok } }".into(),
575                    variables: None,
576                }),
577                admin,
578            )
579            .await;
580        let errors = resp.result["errors"].to_string();
581        assert!(errors.contains("not available through MCP"), "{errors}");
582    }
583
584    #[test]
585    fn a_server_with_an_address_names_its_icon() {
586        let (mut server, _ch, _tmp) = test_server();
587        assert!(server.get_info().server_info.icons.is_none());
588        server.public_url = Some("https://koan.test/".into());
589        let icons = server.get_info().server_info.icons.unwrap();
590        assert_eq!(icons[0].src, "https://koan.test/ui/assets/icon-192.png");
591    }
592
593    fn insert_test_track(db_path: &std::path::Path, title: &str, artist: &str, album: &str) -> i64 {
594        let db = Database::open(db_path).unwrap();
595        let meta = queries::TrackMeta {
596            title: title.to_string(),
597            artist: artist.to_string(),
598            album_artist: Some(artist.to_string()),
599            album: album.to_string(),
600            track_number: Some(1),
601            disc: Some(1),
602            date: Some("2024".into()),
603            genre: Some("Electronic".into()),
604            duration_ms: Some(240000),
605            path: Some(format!(
606                "/tmp/test/{}.flac",
607                title.to_lowercase().replace(' ', "_")
608            )),
609            codec: Some("FLAC".into()),
610            sample_rate: Some(44100),
611            bit_depth: Some(16),
612            channels: Some(2),
613            bitrate: Some(1411),
614            size_bytes: Some(42_000_000),
615            mtime: Some(1700000000),
616            source: "local".into(),
617            remote_id: None,
618            remote_url: None,
619            album_remote_id: None,
620            artist_remote_id: None,
621            mbid: None,
622            album_mbid: None,
623            album_added_at: None,
624            label: None,
625        };
626        queries::upsert_track(&db.conn, &meta).unwrap()
627    }
628
629    #[test]
630    fn schema_sdl_returns_schema() {
631        let (server, _ch, _tmp) = test_server();
632        let Json(resp) = server.schema_sdl();
633        let sdl = resp.result.as_str().unwrap();
634        assert!(sdl.contains("type QueryRoot"));
635        assert!(sdl.contains("type MutationRoot"));
636        assert!(sdl.contains("artists"));
637        assert!(sdl.contains("nowPlaying"));
638    }
639
640    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
641    async fn graphql_query_works() {
642        let (server, _ch, tmp) = test_server();
643        let db_path = tmp.path().join("test.db");
644        insert_test_track(&db_path, "Windowlicker", "Aphex Twin", "Windowlicker EP");
645
646        let result = server
647            .graphql(
648                Parameters(GraphqlParams {
649                    query: r#"{ tracks(search: "aphex") { edges { node { title artist } } } }"#
650                        .into(),
651                    variables: None,
652                }),
653                Default::default(),
654            )
655            .await;
656        let Json(resp) = result;
657        let data = &resp.result["data"]["tracks"]["edges"];
658        assert_eq!(data.as_array().unwrap().len(), 1);
659        assert_eq!(data[0]["node"]["title"], "Windowlicker");
660    }
661
662    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
663    async fn graphql_mutation_works() {
664        let (server, _ch, _tmp) = test_server();
665        let result = server
666            .graphql(
667                Parameters(GraphqlParams {
668                    query: "mutation { pause { ok message } }".into(),
669                    variables: None,
670                }),
671                Default::default(),
672            )
673            .await;
674        let Json(resp) = result;
675        assert_eq!(resp.result["data"]["pause"]["ok"], true);
676    }
677
678    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
679    async fn graphql_now_playing_stopped() {
680        let (server, _ch, _tmp) = test_server();
681        let result = server
682            .graphql(
683                Parameters(GraphqlParams {
684                    query: "{ nowPlaying { state positionMs } }".into(),
685                    variables: None,
686                }),
687                Default::default(),
688            )
689            .await;
690        let Json(resp) = result;
691        assert_eq!(resp.result["data"]["nowPlaying"]["state"], "STOPPED");
692    }
693
694    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
695    async fn graphql_library_stats() {
696        let (server, _ch, tmp) = test_server();
697        let db_path = tmp.path().join("test.db");
698        insert_test_track(&db_path, "T1", "A1", "Album1");
699
700        let result = server
701            .graphql(
702                Parameters(GraphqlParams {
703                    query: "{ libraryStats { totalTracks totalArtists totalAlbums } }".into(),
704                    variables: None,
705                }),
706                Default::default(),
707            )
708            .await;
709        let Json(resp) = result;
710        assert_eq!(resp.result["data"]["libraryStats"]["totalTracks"], 1);
711    }
712}