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