1use std::path::PathBuf;
6use std::sync::Arc;
7
8use crate::auth::AuthUser;
9use crate::auth::password::Refused;
10use crossbeam_channel::Sender;
11use koan_core::player::commands::PlayerCommand;
12use koan_core::player::state::SharedPlayerState;
13use rmcp::handler::server::router::tool::ToolRouter;
14use rmcp::handler::server::wrapper::Json;
15use rmcp::model::{ServerCapabilities, ServerConfig};
16use rmcp::{ServerHandler, schemars, tool_router};
17use serde::{Deserialize, Serialize};
18
19#[derive(Debug, Deserialize, schemars::JsonSchema)]
24pub struct GraphqlParams {
25 #[schemars(
26 description = "GraphQL query or mutation string. Use the schema_sdl tool first to learn available types, queries, mutations, and filter parameters."
27 )]
28 pub query: String,
29 #[schemars(description = "Optional JSON object of query variables")]
30 pub variables: Option<serde_json::Value>,
31}
32
33#[derive(Debug, Serialize, schemars::JsonSchema)]
39pub struct GraphqlResponse {
40 pub result: serde_json::Value,
42}
43
44pub const USERNAME_HEADER: &str = "x-koan-username";
52pub const PASSWORD_HEADER: &str = "x-koan-password";
53
54#[derive(Clone)]
55pub struct KoanMcpServer {
56 #[allow(dead_code)]
57 tool_router: ToolRouter<Self>,
58 graphql_schema: crate::graphql::KoanSchema,
59 users: Option<Arc<crate::auth::password::PasswordVerifier>>,
61}
62
63impl KoanMcpServer {
64 pub fn new(
65 state: Arc<SharedPlayerState>,
66 cmd_tx: Sender<PlayerCommand>,
67 db_path: PathBuf,
68 ) -> Self {
69 let graphql_schema = crate::graphql::build_schema(state, cmd_tx, db_path, None);
70 Self {
71 tool_router: Self::tool_router(),
72 graphql_schema,
73 users: None,
74 }
75 }
76
77 fn caller(&self, extensions: &rmcp::model::Extensions) -> Result<AuthUser, String> {
81 let local = AuthUser {
82 user_id: koan_core::db::queries::LOCAL_USER,
83 role: mcp_role(),
84 ..AuthUser::anonymous_admin()
85 };
86 let Some(users) = &self.users else {
87 return Ok(local);
88 };
89 let parts = extensions.get::<axum::http::request::Parts>();
90 let get = |h: &str| {
91 parts
92 .and_then(|p| p.headers.get(h))
93 .and_then(|v| v.to_str().ok())
94 .map(str::trim)
95 .filter(|v| !v.is_empty())
96 };
97 match (get(USERNAME_HEADER), get(PASSWORD_HEADER)) {
98 (Some(u), Some(p)) => match users.verify(u, p) {
99 Ok((user_id, role)) => Ok(AuthUser {
101 user_id,
102 username: u.to_owned(),
103 role,
104 }),
105 Err(Refused::Wrong) => Err("kōan rejected that username and password".into()),
106 Err(Refused::Busy) => Err("kōan is busy checking passwords; try again".into()),
107 },
108 _ if std::env::var("KOAN_MCP_REQUIRE_LOGIN").is_ok_and(|v| v == "1") => Err(format!(
109 "this kōan needs an account: send {USERNAME_HEADER} and {PASSWORD_HEADER}"
110 )),
111 _ => Ok(local),
112 }
113 }
114}
115
116use rmcp::handler::server::wrapper::Parameters;
117use rmcp::tool;
118
119fn mcp_role() -> koan_core::auth::Role {
127 if std::env::var("KOAN_MCP_ADMIN").is_ok_and(|v| v == "1") {
128 koan_core::auth::Role::Admin
129 } else {
130 koan_core::auth::Role::User
131 }
132}
133
134#[tool_router]
135impl KoanMcpServer {
136 #[tool(
137 description = "The GraphQL schema for the user's music (kōan): their library and the \
138 players they listen on. Call this first, before `graphql`. It covers playing, pausing, \
139 skipping and queueing music on the user's phone and computers, what is playing now, \
140 and searching, browsing and making playlists from the music they own."
141 )]
142 fn schema_sdl(&self) -> Json<GraphqlResponse> {
143 let sdl = self.graphql_schema.sdl();
144 Json(GraphqlResponse {
145 result: serde_json::Value::String(sdl),
146 })
147 }
148
149 #[tool(
150 description = "Control the user's music and search their music library (kōan). Use it \
151 for any request about music they listen to or own: play something, pause, resume, skip, \
152 what's playing, what's next, add to or change the queue, find or recommend from their \
153 collection, playlists, favourites. \"Pause the music on my desktop\", \"play some \
154 jazz on my phone\" and \"what is this song\" are all this tool.\n\n\
155 Call schema_sdl first for the full schema. The user's phones and computers running \
156 kōan are `clients`; commands for them end in `OnClient`.\n\n\
157 Examples:\n\
158 - What's playing, where: { clients { name playing nowPlaying positionMs } }\n\
159 - Pause: mutation { controlClient(action: PAUSE) { ok message } }\n\
160 - Find music: { tracks(search: \"aphex\", first: 20) { edges { node { id title artist album } } } }\n\
161 - Play it: mutation { playOnClient(trackIds: [\"42\", \"43\"]) { ok message } }\n\n\
162 String filters are case-insensitive substrings."
163 )]
164 fn graphql(
165 &self,
166 Parameters(params): Parameters<GraphqlParams>,
167 extensions: rmcp::model::Extensions,
168 ) -> Result<Json<GraphqlResponse>, String> {
169 let schema = self.graphql_schema.clone();
170 let query = params.query;
171 let variables = params.variables;
172 let rt =
173 tokio::runtime::Handle::try_current().map_err(|_| "no tokio runtime".to_string())?;
174 let result = tokio::task::block_in_place(|| {
176 let caller = self.caller(&extensions)?;
177 Ok::<_, String>(rt.block_on(crate::graphql::execute_in_process(
178 &schema, &query, variables, caller,
179 )))
180 })?;
181 Ok(Json(GraphqlResponse { result }))
182 }
183}
184
185#[rmcp::tool_handler]
186impl ServerHandler for KoanMcpServer {
187 fn get_info(&self) -> ServerConfig {
188 let instructions = if self.users.is_some() {
192 SERVER_INSTRUCTIONS
193 } else {
194 LOCAL_INSTRUCTIONS
195 };
196 ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
197 .with_server_info(rmcp::model::Implementation::new(
198 "koan",
199 env!("CARGO_PKG_VERSION"),
200 ))
201 .with_instructions(instructions)
202 }
203}
204
205const SERVER_INSTRUCTIONS: &str = "kōan is the user's music: their whole music library, and the \
206phones and computers they listen on. Use it for anything about music they are playing or own — \
207\"pause the music\", \"play something like Polar Bear on my phone\", \"what's this song\", \
208\"skip to the Phace remix\", \"add their new album when it's downloaded\". Call `schema_sdl` \
209once, then do everything through `graphql`.
210
211## Where the music plays
212The user listens in kōan apps on their devices, linked to this server. Query \
213`clients { name platform playing nowPlaying album positionMs durationMs radio queue { trackId \
214title artist current } }` to see each device, what it is playing and what it has queued. Every \
215command about the user's music goes to a device:
216- `controlClient(action: PAUSE|RESUME|NEXT|PREVIOUS)`, `seekOnClient(positionMs)`
217- `playOnClient(trackIds, startAt)` replaces the queue and plays; `enqueue: true` appends. \
218A phone iOS has suspended is not linked but is still reached. Music comes up there as a \
219notification to tap, since iOS lets no app start audio on its own from sleep; queue, radio and \
220other changes are applied as it wakes. The message says when a device was asleep: tell the user \
221to tap the notification
222- `playNextOnClient(trackIds)`, `jumpOnClient(trackId)` (skip to a track, queued or not), \
223`removeFromClient(trackIds)`, `clearClient`, `setClientRadio(enabled)`, `syncClient`
224- **Making a playlist the user asked for** (\"make me a cyberpunk playlist\"): research what \
225fits, find each track in the library, `createPlaylist` with those in order. For picks the \
226library lacks, fetch the album with slsk's `grab`, then `addToPlaylistWhenAdded(playlistId, \
227artist, album, titles)` to add the wanted tracks once it is imported. Tell the user what is \
228there now and what is on its way.
229- Playlists made or edited here (`createPlaylist`, `setPlaylistTracks`…) reach every device \
230by themselves: linked ones sync at once, others when next opened. `syncClients` does the same \
231on request.
232- `evictOnClients(trackIds)` makes every linked device drop its downloaded copies of those \
233tracks: when a track plays as noise or glitches, after the file on the server is replaced
234- `queueOnClientWhenAdded(artist, album)` queues an album once it reaches the library, e.g. \
235one being downloaded with slsk's `grab`; `clientOrders` lists those waiting
236Leave `client` out unless the user named a device (\"my phone\", \"the desktop\": match it \
237against `clients` names and platforms). Without it the server picks the device that is \
238playing, else the one played most recently; if it answers that it cannot tell, ask the user \
239which device.
240
241**Act on what the user asks; do not second-guess it from reported state.** \"Pause\", \
242\"skip\" and \"resume\" go straight to `controlClient`: the user can hear the device and you \
243cannot, and a report can be stale or, from an older app (`playing: null`), absent.
244
245**Never use the server's own player for the user's music.** `play`, `pause`, `resume`, \
246`next`, `previous`, `seek`, `nowPlaying`, `queue`, `addToQueue`, `replaceQueue`, \
247`playPlaylist` and the radio mutations drive a headless player on the server that nobody \
248hears; `nowPlaying` there reports nothing about what the user is listening to.
249
250## The library
251- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
252duration, favourites), `randomTracks`, `similarArtists`, `similarTracks`, `fuzzySearch`
253- Build a set from these, then send its track ids to a device with `playOnClient`. Track ids are \
254integers in queries; pass them to the client mutations as strings.
255- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
256- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `addToPlaylist`, \
257`setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`
258- History: `playHistory`
259- Sharing: `createShare(trackIds, description)` makes a public link anyone can open without an \
260account; confirm with the user first. `shares`, `updateShare`, `deleteShare` manage them.
261
262## Not available
263`organize*` (moves files on disk), `updateConfig` and `triggerScan` are refused unless \
264`KOAN_MCP_ADMIN=1` is set.";
265
266const LOCAL_INSTRUCTIONS: &str = "kōan is the user's music player on this machine and their \
267music library. Use it for anything about music they are playing or own — \"pause the music\", \
268\"play something like Polar Bear\", \"what's this song\". Call `schema_sdl` once, then do \
269everything through `graphql`.
270
271## Playback
272This player is what the user hears: `play`, `pause`, `resume`, `stop`, `next`, `previous`, \
273`seek`, `nowPlaying`; the queue with `queue`, `addToQueue`, `replaceQueue`, `removeFromQueue`, \
274`moveInQueue`, `clearQueue`, `undo`, `redo`; radio with `enableRadio`, `disableRadio`.
275
276## The library
277- `artists`, `albums`, `tracks` with filters (genre, year range, codec, sample rate, bit depth, \
278duration, favourites), `randomTracks`, `similarArtists`, `similarTracks`, `fuzzySearch`
279- Favourites: `favourite`, `unfavourite`, `toggleFavourite`, `favouritesOnly: true` on queries
280- Playlists: `playlists`, `playlistTracks`, `createPlaylist`, `saveQueueAsPlaylist`, \
281`addToPlaylist`, `setPlaylistTracks`, `renamePlaylist`, `deletePlaylist`, `playPlaylist`
282- History: `playHistory`
283- Sharing: `createShare(trackIds, description)` makes a public link; confirm with the user first.
284
285## Not available
286`organize*` (moves files on disk), `updateConfig`, `triggerScan` and `setDevice` are refused \
287unless `KOAN_MCP_ADMIN=1` is set.
288
289## IDs
290Track IDs are integers from the library; queue item IDs are UUIDs from the queue.";
291
292pub fn spawn_http(
300 addr: std::net::SocketAddr,
301 state: Arc<SharedPlayerState>,
302 cmd_tx: Sender<PlayerCommand>,
303 pool: Arc<koan_core::db::pool::Pool>,
304) -> std::io::Result<std::thread::JoinHandle<()>> {
305 use rmcp::transport::streamable_http_server::{
306 StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
307 };
308 let mut template = KoanMcpServer::new(state, cmd_tx, pool.path().to_path_buf());
309 template.users = Some(Arc::new(crate::auth::password::PasswordVerifier::new(pool)));
310 let listener = std::net::TcpListener::bind(addr)?;
312 listener.set_nonblocking(true)?;
313 std::thread::Builder::new()
314 .name("koan-mcp-http".into())
315 .spawn(move || {
316 let rt = tokio::runtime::Builder::new_multi_thread()
317 .enable_all()
318 .build()
319 .expect("failed to create tokio runtime");
320 rt.block_on(async move {
321 let service = StreamableHttpService::new(
322 move || Ok(template.clone()),
323 Arc::new(LocalSessionManager::default()),
324 StreamableHttpServerConfig::default().disable_allowed_hosts(),
328 );
329 let app = axum::Router::new().nest_service("/mcp", service);
330 let listener =
331 tokio::net::TcpListener::from_std(listener).expect("listener from std");
332 if let Err(e) = axum::serve(listener, app).await {
333 log::error!("MCP HTTP server stopped: {e}");
334 }
335 });
336 })
337}
338
339pub fn cmd_mcp() {
341 use koan_core::player::Player;
342 use rmcp::ServiceExt;
343
344 let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
346 let db_path = koan_core::config::db_path();
347
348 let (state, _timeline, _viz, cmd_tx) = Player::spawn();
350
351 let server = KoanMcpServer::new(state, cmd_tx, db_path);
352
353 let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
355 rt.block_on(async {
356 let transport = rmcp::transport::io::stdio();
357 let service = server
358 .serve(transport)
359 .await
360 .expect("failed to start MCP server");
361 let _ = service.waiting().await;
362 });
363}
364
365#[cfg(test)]
370mod tests {
371 use super::*;
372 use koan_core::db::connection::Database;
373 use koan_core::db::queries;
374 use koan_core::player::commands::CommandChannel;
375 use tempfile::TempDir;
376
377 fn test_server() -> (KoanMcpServer, CommandChannel, TempDir) {
378 let tmp = TempDir::new().unwrap();
379 let db_path = tmp.path().join("test.db");
380 let db = Database::open(&db_path).unwrap();
381 koan_core::db::schema::create_tables(&db.conn).unwrap();
382
383 let state = SharedPlayerState::new();
384 let ch = CommandChannel::new();
385 let tx = ch.tx.clone();
386
387 let server = KoanMcpServer::new(state, tx, db_path);
388 (server, ch, tmp)
389 }
390
391 fn with_headers(headers: &[(&str, &str)]) -> rmcp::model::Extensions {
392 let mut req = axum::http::Request::builder();
393 for (k, v) in headers {
394 req = req.header(*k, *v);
395 }
396 let (parts, ()) = req.body(()).unwrap().into_parts();
397 let mut ext = rmcp::model::Extensions::new();
398 ext.insert(parts);
399 ext
400 }
401
402 #[test]
403 fn gateway_headers_act_as_that_account() {
404 use koan_core::auth::Role;
405 let (mut server, _ch, tmp) = test_server();
406 let db_path = tmp.path().join("test.db");
407 let db = Database::open(&db_path).unwrap();
408 queries::auth::create_user(&db.conn, "owner", "sesame", Role::Admin).unwrap();
409 queries::auth::create_user(&db.conn, "mate", "hunter22", Role::Readonly).unwrap();
410 server.users = Some(Arc::new(crate::auth::password::PasswordVerifier::new(
411 Arc::new(koan_core::db::pool::Pool::new(db_path)),
412 )));
413
414 let as_ = |u: &str, p: &str| {
415 server
416 .caller(&with_headers(&[(USERNAME_HEADER, u), (PASSWORD_HEADER, p)]))
417 .map(|c| (c.user_id, c.username, c.role))
418 };
419 assert_eq!(as_("owner", "sesame"), Ok((1, "owner".into(), Role::Admin)));
421 assert_eq!(
422 as_("mate", "hunter22"),
423 Ok((2, "mate".into(), Role::Readonly))
424 );
425 assert!(as_("owner", "wrong").is_err());
426 let local = server.caller(&with_headers(&[])).unwrap();
428 assert_eq!(
429 (local.user_id, local.role),
430 (queries::LOCAL_USER, mcp_role())
431 );
432 }
433
434 fn insert_test_track(db_path: &std::path::Path, title: &str, artist: &str, album: &str) -> i64 {
435 let db = Database::open(db_path).unwrap();
436 let meta = queries::TrackMeta {
437 title: title.to_string(),
438 artist: artist.to_string(),
439 album_artist: Some(artist.to_string()),
440 album: album.to_string(),
441 track_number: Some(1),
442 disc: Some(1),
443 date: Some("2024".into()),
444 genre: Some("Electronic".into()),
445 duration_ms: Some(240000),
446 path: Some(format!(
447 "/tmp/test/{}.flac",
448 title.to_lowercase().replace(' ', "_")
449 )),
450 codec: Some("FLAC".into()),
451 sample_rate: Some(44100),
452 bit_depth: Some(16),
453 channels: Some(2),
454 bitrate: Some(1411),
455 size_bytes: Some(42_000_000),
456 mtime: Some(1700000000),
457 source: "local".into(),
458 remote_id: None,
459 remote_url: None,
460 album_remote_id: None,
461 artist_remote_id: None,
462 mbid: None,
463 album_mbid: None,
464 album_added_at: None,
465 label: None,
466 };
467 queries::upsert_track(&db.conn, &meta).unwrap()
468 }
469
470 #[test]
471 fn schema_sdl_returns_schema() {
472 let (server, _ch, _tmp) = test_server();
473 let Json(resp) = server.schema_sdl();
474 let sdl = resp.result.as_str().unwrap();
475 assert!(sdl.contains("type QueryRoot"));
476 assert!(sdl.contains("type MutationRoot"));
477 assert!(sdl.contains("artists"));
478 assert!(sdl.contains("nowPlaying"));
479 }
480
481 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
482 async fn graphql_query_works() {
483 let (server, _ch, tmp) = test_server();
484 let db_path = tmp.path().join("test.db");
485 insert_test_track(&db_path, "Windowlicker", "Aphex Twin", "Windowlicker EP");
486
487 let result = server.graphql(
488 Parameters(GraphqlParams {
489 query: r#"{ tracks(search: "aphex") { edges { node { title artist } } } }"#.into(),
490 variables: None,
491 }),
492 Default::default(),
493 );
494 assert!(result.is_ok());
495 let Json(resp) = result.unwrap();
496 let data = &resp.result["data"]["tracks"]["edges"];
497 assert_eq!(data.as_array().unwrap().len(), 1);
498 assert_eq!(data[0]["node"]["title"], "Windowlicker");
499 }
500
501 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
502 async fn graphql_mutation_works() {
503 let (server, _ch, _tmp) = test_server();
504 let result = server.graphql(
505 Parameters(GraphqlParams {
506 query: "mutation { pause { ok message } }".into(),
507 variables: None,
508 }),
509 Default::default(),
510 );
511 assert!(result.is_ok());
512 let Json(resp) = result.unwrap();
513 assert_eq!(resp.result["data"]["pause"]["ok"], true);
514 }
515
516 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
517 async fn graphql_now_playing_stopped() {
518 let (server, _ch, _tmp) = test_server();
519 let result = server.graphql(
520 Parameters(GraphqlParams {
521 query: "{ nowPlaying { state positionMs } }".into(),
522 variables: None,
523 }),
524 Default::default(),
525 );
526 assert!(result.is_ok());
527 let Json(resp) = result.unwrap();
528 assert_eq!(resp.result["data"]["nowPlaying"]["state"], "STOPPED");
529 }
530
531 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
532 async fn graphql_library_stats() {
533 let (server, _ch, tmp) = test_server();
534 let db_path = tmp.path().join("test.db");
535 insert_test_track(&db_path, "T1", "A1", "Album1");
536
537 let result = server.graphql(
538 Parameters(GraphqlParams {
539 query: "{ libraryStats { totalTracks totalArtists totalAlbums } }".into(),
540 variables: None,
541 }),
542 Default::default(),
543 );
544 assert!(result.is_ok());
545 let Json(resp) = result.unwrap();
546 assert_eq!(resp.result["data"]["libraryStats"]["totalTracks"], 1);
547 }
548}