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