1use 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#[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#[derive(Debug, Serialize, schemars::JsonSchema)]
37pub struct GraphqlResponse {
38 pub result: serde_json::Value,
40}
41
42#[derive(Clone)]
47pub struct KoanMcpServer {
48 #[allow(dead_code)]
49 tool_router: ToolRouter<Self>,
50 graphql_schema: crate::graphql::KoanSchema,
51 headless: bool,
54 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 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
94fn 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
109pub const DENIED_MUTATIONS: &[&str] = &["organizeExecute", "organizeUndo", "updateConfig"];
115
116struct 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
144pub 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 ¶ms.query,
195 params.variables,
196 caller,
197 )
198 .await;
199 Json(GraphqlResponse { result })
200 }
201}
202
203impl KoanMcpServer {
204 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 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
237macro_rules! choosing_by_style {
240 () => {
241 "- **Choosing music by style, mood or era** (\"psychedelic rock\", \"something for a rainy \
242Sunday\"): genre tags are sparse and inconsistent, so do not rely on `genre` filters. Use your \
243own knowledge, and research when unsure, to list many artists and albums that fit, then look \
244them all up in a single query with aliases (`a: artists(search: \"Can\") { … } b: …`) and \
245choose from the ones present. `search` matches any part of a name, ignoring case, so check that \
246a result is the artist you meant. If most are missing, read the library's artist names once \
247(`artists(first: 500, sortBy: TRACK_COUNT, sortDir: DESC) { edges { node { id name } } \
248pageInfo { hasNextPage endCursor } }`, then `after: endCursor` while `hasNextPage`) and pick \
249from them by what you know of each. Do not guess names one round at a time.
250"
251 };
252}
253
254const SERVER_INSTRUCTIONS: &str = concat!("kōan is the user's music: their whole music library, and the \
255phones and computers they listen on. Use it for anything about music they are playing or own — \
256\"pause the music\", \"play something like Polar Bear on my phone\", \"what's this song\", \
257\"skip to the Phace remix\", \"add their new album when it's downloaded\". Call `schema_sdl` \
258once, then do everything through `graphql`.
259
260## Where the music plays
261The user listens in kōan apps on their devices, linked to this server. Query \
262`clients { name platform playing nowPlaying album positionMs durationMs queue { trackId \
263title artist current } }` to see each device, what it is playing and what it has queued. Every \
264command about the user's music goes to a device:
265- `controlClient(action: PAUSE|RESUME|NEXT|PREVIOUS)`, `seekOnClient(positionMs)`
266- `playOnClient(trackIds, startAt)` replaces the queue and plays; `enqueue: true` appends. \
267A phone iOS has suspended is not linked but is still reached. Music comes up there as a \
268notification to tap, since iOS lets no app start audio on its own from sleep; queue and \
269other changes are applied as it wakes. The message says when a device was asleep: tell the user \
270to tap the notification
271- `playNextOnClient(trackIds)`, `jumpOnClient(trackId)` (skip to a track, queued or not), \
272`removeFromClient(trackIds)`, `clearClient`, `syncClient`
273- **Making a playlist the user asked for** (\"make me a cyberpunk playlist\"): research what \
274fits, find each track in the library, `createPlaylist` with those in order. For picks the \
275library lacks, fetch the album with slsk's `grab`, then `addToPlaylistWhenAdded(playlistId, \
276artist, album, titles)` to add the wanted tracks once it is imported. Tell the user what is \
277there now and what is on its way.
278- Playlists made or edited here (`createPlaylist`, `setPlaylistTracks`…) reach every device \
279by themselves: linked ones sync at once, others when next opened. `syncClients` does the same \
280on request.
281- `evictOnClients(trackIds)` makes every linked device drop its downloaded copies of those \
282tracks: when a track plays as noise or glitches, after the file on the server is replaced
283- `queueOnClientWhenAdded(artist, album)` queues an album once it reaches the library, e.g. \
284one being downloaded with slsk's `grab`; `clientOrders` lists those waiting
285Leave `client` out unless the user named a device (\"my phone\", \"the desktop\": match it \
286against `clients` names and platforms). Without it the server picks the device that is \
287playing, else the one played most recently; if it answers that it cannot tell, ask the user \
288which device.
289
290**Act on what the user asks; do not second-guess it from reported state.** \"Pause\", \
291\"skip\" and \"resume\" go straight to `controlClient`: the user can hear the device and you \
292cannot, and a report can be stale or, from an older app (`playing: null`), absent.
293
294**Never use the server's own player for the user's music.** `play`, `pause`, `resume`, \
295`next`, `previous`, `seek`, `nowPlaying`, `queue`, `addToQueue`, `replaceQueue`, \
296and `playPlaylist` drive a headless player on the server that nobody \
297hears; `nowPlaying` there reports nothing about what the user is listening to.
298
299## The library
300- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
301duration, favourites), `randomTracks`, `fuzzySearch`
302",
303 choosing_by_style!(),
304 "- Build a set from these, then send its track ids to a device with `playOnClient`. Track ids are \
305integers in queries; pass them to the client mutations as strings.
306- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
307- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `addToPlaylist`, \
308`setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`
309- History: `playHistory`
310- Sharing: `createShare(trackIds, description)` makes a public link anyone can open without an \
311account; confirm with the user first. `shares`, `updateShare`, `deleteShare` manage them.
312
313## Not available
314`organizeExecute`, `organizeUndo` (move files on disk) and `updateConfig` are never run \
315through MCP. Other admin mutations (`triggerScan`, user management) are refused unless \
316`KOAN_MCP_ADMIN=1` is set.");
317
318const LOCAL_INSTRUCTIONS: &str = concat!(
319 "kōan is the user's music player on this machine and their \
320music library. Use it for anything about music they are playing or own — \"pause the music\", \
321\"play something like Polar Bear\", \"what's this song\". Call `schema_sdl` once, then do \
322everything through `graphql`.
323
324## Playback
325This player is what the user hears: `play`, `pause`, `resume`, `stop`, `next`, `previous`, \
326`seek`, `nowPlaying`; the queue with `queue`, `addToQueue`, `replaceQueue`, `removeFromQueue`, \
327`moveInQueue`, `clearQueue`, `undo`, `redo`.
328
329## The library
330- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
331duration, favourites), `randomTracks`, `fuzzySearch`
332",
333 choosing_by_style!(),
334 "- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
335- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `saveQueueAsPlaylist`, \
336`addToPlaylist`, `setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`, `playPlaylist`
337- History: `playHistory`
338- Sharing: `createShare(trackIds, description)` makes a public link; confirm with the user first.
339
340## Not available
341`organizeExecute`, `organizeUndo` (move files on disk) and `updateConfig` are never run \
342through MCP. `triggerScan` and `setDevice` are refused unless `KOAN_MCP_ADMIN=1` is set.
343
344## IDs
345Track IDs are integers from the library; queue item IDs are UUIDs from the queue."
346);
347
348const MAX_BODY: usize = 1024 * 1024;
349const MAX_CONCURRENT: usize = 64;
352
353pub fn router(
357 state: Arc<SharedPlayerState>,
358 cmd_tx: Sender<PlayerCommand>,
359 auth: crate::auth::middleware::AuthState,
360 public_url: Option<String>,
361 headless: bool,
362 shutdown: tokio_util::sync::CancellationToken,
363) -> axum::Router {
364 use rmcp::transport::streamable_http_server::{
365 StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
366 };
367 let mut template = KoanMcpServer::new(state, cmd_tx, auth.pool.clone());
368 template.headless = headless;
369 template.public_url = public_url.clone();
370 let service = StreamableHttpService::new(
371 move || Ok(template.clone()),
372 Arc::new(LocalSessionManager::default()),
373 StreamableHttpServerConfig::default()
376 .disable_allowed_hosts()
377 .with_cancellation_token(shutdown),
378 );
379 axum::Router::new()
381 .nest_service("/mcp", service)
382 .layer(tower_http::catch_panic::CatchPanicLayer::new())
383 .layer(tower_http::limit::RequestBodyLimitLayer::new(MAX_BODY))
384 .layer(axum::middleware::from_fn_with_state(
385 (auth, public_url),
386 bearer_gate,
387 ))
388 .layer(
389 tower::ServiceBuilder::new()
390 .layer(axum::error_handling::HandleErrorLayer::new(
391 |_: tower::BoxError| async {
392 (axum::http::StatusCode::SERVICE_UNAVAILABLE, "busy")
393 },
394 ))
395 .load_shed()
396 .concurrency_limit(MAX_CONCURRENT),
397 )
398}
399
400async fn bearer_gate(
404 axum::extract::State((auth, public_url)): axum::extract::State<(
405 crate::auth::middleware::AuthState,
406 Option<String>,
407 )>,
408 mut req: axum::extract::Request,
409 next: axum::middleware::Next,
410) -> axum::response::Response {
411 use axum::http::{Method, StatusCode, header};
412 use axum::response::IntoResponse;
413 let browser = req.method() == Method::GET
415 && !req.headers().contains_key(header::AUTHORIZATION)
416 && req
417 .headers()
418 .get(header::ACCEPT)
419 .and_then(|v| v.to_str().ok())
420 .is_some_and(|a| a.contains("text/html"));
421 if browser {
422 return axum::response::Redirect::to("/connect").into_response();
423 }
424 let user = if auth.auth_enabled {
425 let token = req
426 .headers()
427 .get(header::AUTHORIZATION)
428 .and_then(|v| v.to_str().ok())
429 .and_then(|v| v.strip_prefix("Bearer "))
430 .and_then(|t| {
431 koan_core::auth::validate_scoped_token(
432 &auth.public_pem,
433 t,
434 Some(koan_core::auth::MCP_SCOPE),
435 )
436 .ok()
437 });
438 match token {
439 Some(claims) => crate::auth::current_user(&auth.pool, claims).await,
440 None => None,
441 }
442 } else {
443 Some(AuthUser::anonymous_admin())
444 };
445 match user {
446 Some(user) => {
447 req.extensions_mut().insert(user);
448 next.run(req).await
449 }
450 None => {
451 let challenge = match public_url.as_deref().map(|u| u.trim_end_matches('/')) {
453 Some(base) => format!(
454 "Bearer resource_metadata=\"{base}{}\"",
455 crate::ui::RESOURCE_METADATA
456 ),
457 None => "Bearer".to_owned(),
458 };
459 (
460 StatusCode::UNAUTHORIZED,
461 [(header::WWW_AUTHENTICATE, challenge)],
462 "sign in to kōan",
463 )
464 .into_response()
465 }
466 }
467}
468
469pub fn cmd_mcp() {
471 use koan_core::player::Player;
472 use rmcp::ServiceExt;
473
474 let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
476 let db_path = koan_core::config::db_path();
477
478 let (state, _timeline, _viz, cmd_tx) = Player::spawn();
480
481 let pool = Arc::new(koan_core::db::pool::Pool::new(db_path));
482 let server = KoanMcpServer::new(state, cmd_tx, pool);
483
484 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
486 rt.block_on(async {
487 let transport = rmcp::transport::io::stdio();
488 let service = server
489 .serve(transport)
490 .await
491 .expect("failed to start MCP server");
492 let _ = service.waiting().await;
493 });
494}
495
496#[cfg(test)]
501mod tests {
502 use super::*;
503 use koan_core::db::connection::Database;
504 use koan_core::db::queries;
505 use koan_core::player::commands::CommandChannel;
506 use tempfile::TempDir;
507
508 fn test_server() -> (KoanMcpServer, CommandChannel, TempDir) {
509 let tmp = TempDir::new().unwrap();
510 let db_path = tmp.path().join("test.db");
511 let db = Database::open(&db_path).unwrap();
512 koan_core::db::schema::create_tables(&db.conn).unwrap();
513
514 let state = SharedPlayerState::new();
515 let ch = CommandChannel::new();
516 let tx = ch.tx.clone();
517
518 let server =
519 KoanMcpServer::new(state, tx, Arc::new(koan_core::db::pool::Pool::new(db_path)));
520 (server, ch, tmp)
521 }
522
523 fn as_user(user: AuthUser) -> rmcp::model::Extensions {
524 let (mut parts, ()) = axum::http::Request::new(()).into_parts();
525 parts.extensions.insert(user);
526 let mut ext = rmcp::model::Extensions::new();
527 ext.insert(parts);
528 ext
529 }
530
531 #[test]
532 fn a_token_acts_as_its_account_with_admin_capped() {
533 use koan_core::auth::Role;
534 let (server, _ch, _tmp) = test_server();
535 let user = |role| AuthUser {
536 user_id: 7,
537 username: "mate".into(),
538 role,
539 };
540 let c = server.caller(&as_user(user(Role::Admin)));
541 assert_eq!((c.user_id, c.username.as_str()), (7, "mate"));
542 assert_eq!(c.role, capped(Role::Admin));
543 assert_eq!(
544 server.caller(&as_user(user(Role::Readonly))).role,
545 Role::Readonly
546 );
547 let local = server.caller(&Default::default());
549 assert_eq!(
550 (local.user_id, local.role),
551 (queries::LOCAL_USER, mcp_role())
552 );
553 }
554
555 #[tokio::test]
556 async fn a_browser_opening_mcp_is_shown_how_to_connect() {
557 use tower::ServiceExt as _;
558 let (_server, ch, tmp) = test_server();
559 let auth = crate::auth::middleware::AuthState {
560 public_pem: Arc::new(Vec::new()),
561 auth_enabled: true,
562 introspection_key: None,
563 pool: Arc::new(koan_core::db::pool::Pool::new(tmp.path().join("test.db"))),
564 };
565 let app = router(
566 SharedPlayerState::new(),
567 ch.tx.clone(),
568 auth,
569 None,
570 true,
571 Default::default(),
572 );
573 let req = |accept: &str| {
574 axum::http::Request::get("/mcp")
575 .header(axum::http::header::ACCEPT, accept)
576 .body(axum::body::Body::empty())
577 .unwrap()
578 };
579 let r = app.clone().oneshot(req("text/html,*/*")).await.unwrap();
580 assert_eq!(r.headers()[axum::http::header::LOCATION], "/connect");
581 let r = app.oneshot(req("text/event-stream")).await.unwrap();
582 assert_eq!(r.status(), axum::http::StatusCode::UNAUTHORIZED);
583 }
584
585 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
586 async fn mutations_that_touch_files_are_refused_whoever_asks() {
587 use koan_core::auth::Role;
588 let (server, _ch, _tmp) = test_server();
589 let admin = as_user(AuthUser {
590 user_id: 1,
591 username: "owner".into(),
592 role: Role::Admin,
593 });
594 let Json(resp) = server
595 .graphql(
596 Parameters(GraphqlParams {
597 query: "mutation { undo: organizeUndo { ok } }".into(),
598 variables: None,
599 }),
600 admin,
601 )
602 .await;
603 let errors = resp.result["errors"].to_string();
604 assert!(errors.contains("not available through MCP"), "{errors}");
605 }
606
607 #[test]
608 fn a_server_with_an_address_names_its_icon() {
609 let (mut server, _ch, _tmp) = test_server();
610 assert!(server.get_info().server_info.icons.is_none());
611 server.public_url = Some("https://koan.test/".into());
612 let icons = server.get_info().server_info.icons.unwrap();
613 assert_eq!(icons[0].src, "https://koan.test/ui/assets/icon-192.png");
614 }
615
616 fn insert_test_track(db_path: &std::path::Path, title: &str, artist: &str, album: &str) -> i64 {
617 let db = Database::open(db_path).unwrap();
618 let meta = queries::TrackMeta {
619 title: title.to_string(),
620 artist: artist.to_string(),
621 album_artist: Some(artist.to_string()),
622 album: album.to_string(),
623 track_number: Some(1),
624 disc: Some(1),
625 date: Some("2024".into()),
626 genre: Some("Electronic".into()),
627 duration_ms: Some(240000),
628 path: Some(format!(
629 "/tmp/test/{}.flac",
630 title.to_lowercase().replace(' ', "_")
631 )),
632 codec: Some("FLAC".into()),
633 sample_rate: Some(44100),
634 bit_depth: Some(16),
635 channels: Some(2),
636 bitrate: Some(1411),
637 size_bytes: Some(42_000_000),
638 mtime: Some(1700000000),
639 source: "local".into(),
640 remote_id: None,
641 remote_url: None,
642 album_remote_id: None,
643 artist_remote_id: None,
644 mbid: None,
645 album_mbid: None,
646 album_added_at: None,
647 label: None,
648 };
649 queries::upsert_track(&db.conn, &meta).unwrap()
650 }
651
652 #[test]
653 fn schema_sdl_returns_schema() {
654 let (server, _ch, _tmp) = test_server();
655 let Json(resp) = server.schema_sdl();
656 let sdl = resp.result.as_str().unwrap();
657 assert!(sdl.contains("type QueryRoot"));
658 assert!(sdl.contains("type MutationRoot"));
659 assert!(sdl.contains("artists"));
660 assert!(sdl.contains("nowPlaying"));
661 }
662
663 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
664 async fn graphql_query_works() {
665 let (server, _ch, tmp) = test_server();
666 let db_path = tmp.path().join("test.db");
667 insert_test_track(&db_path, "Windowlicker", "Aphex Twin", "Windowlicker EP");
668
669 let result = server
670 .graphql(
671 Parameters(GraphqlParams {
672 query: r#"{ tracks(search: "aphex") { edges { node { title artist } } } }"#
673 .into(),
674 variables: None,
675 }),
676 Default::default(),
677 )
678 .await;
679 let Json(resp) = result;
680 let data = &resp.result["data"]["tracks"]["edges"];
681 assert_eq!(data.as_array().unwrap().len(), 1);
682 assert_eq!(data[0]["node"]["title"], "Windowlicker");
683 }
684
685 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
686 async fn graphql_mutation_works() {
687 let (server, _ch, _tmp) = test_server();
688 let result = server
689 .graphql(
690 Parameters(GraphqlParams {
691 query: "mutation { pause { ok message } }".into(),
692 variables: None,
693 }),
694 Default::default(),
695 )
696 .await;
697 let Json(resp) = result;
698 assert_eq!(resp.result["data"]["pause"]["ok"], true);
699 }
700
701 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
702 async fn graphql_now_playing_stopped() {
703 let (server, _ch, _tmp) = test_server();
704 let result = server
705 .graphql(
706 Parameters(GraphqlParams {
707 query: "{ nowPlaying { state positionMs } }".into(),
708 variables: None,
709 }),
710 Default::default(),
711 )
712 .await;
713 let Json(resp) = result;
714 assert_eq!(resp.result["data"]["nowPlaying"]["state"], "STOPPED");
715 }
716
717 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
718 async fn graphql_library_stats() {
719 let (server, _ch, tmp) = test_server();
720 let db_path = tmp.path().join("test.db");
721 insert_test_track(&db_path, "T1", "A1", "Album1");
722
723 let result = server
724 .graphql(
725 Parameters(GraphqlParams {
726 query: "{ libraryStats { totalTracks totalArtists totalAlbums } }".into(),
727 variables: None,
728 }),
729 Default::default(),
730 )
731 .await;
732 let Json(resp) = result;
733 assert_eq!(resp.result["data"]["libraryStats"]["totalTracks"], 1);
734 }
735}