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 role a request acts with: the account in its headers, or
77    /// `mcp_role()` when it names none. With `KOAN_MCP_REQUIRE_LOGIN=1`, a
78    /// request naming no account is refused.
79    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(|| "koan 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 koan 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
106/// Role the MCP `graphql` tool executes at.
107///
108/// The transport carries no credential, so anything reachable here is reachable
109/// by whoever can talk to the MCP process. `User` covers everything the tool
110/// advertises — browsing, playback, queue, favourites, playlists, radio — and
111/// leaves out the admin mutations that move files on disk (`organize*`), rewrite
112/// config, or change the output device. `KOAN_MCP_ADMIN=1` opts back in.
113fn 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 = "Get the full GraphQL schema in SDL format. CALL THIS FIRST to learn all \
125        available queries, mutations, types, and filter parameters. The schema is the complete \
126        reference for everything koan can do — library discovery, playback control, queue \
127        management, favourites, playlists, radio mode, device switching, and more."
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 = "Execute a GraphQL query or mutation against the koan music player. \
138        This is the primary interface for ALL operations — library browsing, playback control, \
139        queue management, favourites, playlists, radio, devices.\n\n\
140        Call schema_sdl first to learn the full schema.\n\n\
141        Quick examples:\n\
142        - Search: { tracks(search: \"aphex\") { edges { node { id title artist album } } } }\n\
143        - Filter: { albums(yearEnd: 1995, codec: \"FLAC\") { edges { node { title artistName date } } } }\n\
144        - Now playing: { nowPlaying { state positionMs track { title artist codec sampleRate } } }\n\
145        - Queue tracks: mutation { addToQueue(trackIds: [42, 43]) { ok addedCount } }\n\
146        - Play/pause: mutation { pause { ok } } / mutation { resume { ok } }\n\
147        - Playlist: mutation { saveQueueAsPlaylist(name: \"techno\") { id name } }\n\
148        - Radio: mutation { enableRadio { ok } }\n\n\
149        Track IDs are integers from the library. Queue item IDs are UUIDs from the queue.\n\
150        All string filters are case-insensitive substrings."
151    )]
152    fn graphql(
153        &self,
154        Parameters(params): Parameters<GraphqlParams>,
155        extensions: rmcp::model::Extensions,
156    ) -> Result<Json<GraphqlResponse>, String> {
157        let schema = self.graphql_schema.clone();
158        let query = params.query;
159        let variables = params.variables;
160        let rt =
161            tokio::runtime::Handle::try_current().map_err(|_| "no tokio runtime".to_string())?;
162        // Inside block_in_place too: a first sign-in runs argon2.
163        let result = tokio::task::block_in_place(|| {
164            let role = self.role(&extensions)?;
165            Ok::<_, String>(rt.block_on(crate::graphql::execute_in_process(
166                &schema, &query, variables, role,
167            )))
168        })?;
169        Ok(Json(GraphqlResponse { result }))
170    }
171}
172
173#[rmcp::tool_handler]
174impl ServerHandler for KoanMcpServer {
175    fn get_info(&self) -> ServerConfig {
176        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
177            .with_server_info(rmcp::model::Implementation::new(
178                "koan",
179                env!("CARGO_PKG_VERSION"),
180            ))
181            .with_instructions(
182                "koan is a bit-perfect music player. You control it entirely via GraphQL.\n\n\
183             ## How to use\n\
184             1. Call `schema_sdl` to get the full GraphQL schema\n\
185             2. Use the `graphql` tool for ALL queries and mutations\n\n\
186             ## What you can do\n\
187             - **Discover music**: query `artists`, `albums`, `tracks` with rich filters \
188               (genre, year range, codec, sample rate, bit depth, duration, favourites)\n\
189             - **Control playback**: mutations `play`, `pause`, `resume`, `stop`, `next`, \
190               `previous`, `seek`\n\
191             - **Manage queue**: `addToQueue`, `replaceQueue`, `removeFromQueue`, `moveInQueue`, \
192               `clearQueue`, `undo`, `redo`\n\
193             - **Favourites**: `favourite`, `unfavourite`, `toggleFavourite` (auto-syncs to \
194               Subsonic/Navidrome). Filter any query with `favouritesOnly: true`\n\
195             - **Playlists**: query `playlists`/`playlistTracks`; `createPlaylist`, \
196               `saveQueueAsPlaylist`, `addToPlaylist`, `setPlaylistTracks`, `renamePlaylist`, \
197               `deletePlaylist`, `playPlaylist`. Synced to Subsonic/Navidrome\n\
198             - **Radio**: `enableRadio`, `disableRadio` — auto-queues similar tracks\n\
199             - **Devices**: query `devices`; `setDevice`/`clearDevice` need `KOAN_MCP_ADMIN=1`\n\
200             - **History**: query `playHistory`, `similarArtists`\n\
201             - **Sharing**: `createShare(trackIds, description)` returns a public link anyone can \
202               open without an account; query `shares` to list them, `updateShare` to set an \
203               expiry, `deleteShare` to revoke one. A link is public, so confirm with the user \
204               before making one\n\n\
205             ## Not available\n\
206             Admin mutations — `organize*` (moves files on disk), `updateConfig`, \
207             `triggerScan` — are refused unless `KOAN_MCP_ADMIN=1` is set.\n\n\
208             ## ID conventions\n\
209             - Track IDs: integers from the library database\n\
210             - Queue item IDs: UUIDs assigned when tracks enter the queue",
211            )
212    }
213}
214
215/// Serve MCP over streamable HTTP at `addr`/mcp, on a thread of its own.
216///
217/// The gateway authenticates its user and then forwards a koan account in
218/// `x-koan-username` / `x-koan-password`, which set the role each request acts
219/// with. The headers are trusted to come from the gateway, so this listener
220/// must not be reachable from anywhere else: bind it to an address only the
221/// gateway can reach, and keep it off the public GraphQL port.
222pub fn spawn_http(
223    addr: std::net::SocketAddr,
224    state: Arc<SharedPlayerState>,
225    cmd_tx: Sender<PlayerCommand>,
226    db_path: PathBuf,
227) -> std::io::Result<std::thread::JoinHandle<()>> {
228    use rmcp::transport::streamable_http_server::{
229        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
230    };
231    let mut template = KoanMcpServer::new(state, cmd_tx, db_path.clone());
232    template.users = Some(Arc::new(crate::auth::password::PasswordVerifier::new(
233        db_path,
234    )));
235    // Bound here rather than on the thread, so a taken port fails the start.
236    let listener = std::net::TcpListener::bind(addr)?;
237    listener.set_nonblocking(true)?;
238    std::thread::Builder::new()
239        .name("koan-mcp-http".into())
240        .spawn(move || {
241            let rt = tokio::runtime::Builder::new_multi_thread()
242                .enable_all()
243                .build()
244                .expect("failed to create tokio runtime");
245            rt.block_on(async move {
246                let service = StreamableHttpService::new(
247                    move || Ok(template.clone()),
248                    Arc::new(LocalSessionManager::default()),
249                    // The gateway forwards its own Host header, which rmcp's
250                    // DNS-rebinding allowlist would refuse; reachability is
251                    // what guards this listener.
252                    StreamableHttpServerConfig::default().disable_allowed_hosts(),
253                );
254                let app = axum::Router::new().nest_service("/mcp", service);
255                let listener =
256                    tokio::net::TcpListener::from_std(listener).expect("listener from std");
257                if let Err(e) = axum::serve(listener, app).await {
258                    log::error!("MCP HTTP server stopped: {e}");
259                }
260            });
261        })
262}
263
264/// Entry point for `koan mcp` — starts a headless player with an MCP server on stdio.
265pub fn cmd_mcp() {
266    use koan_core::player::Player;
267    use rmcp::ServiceExt;
268
269    // Validate DB is accessible before starting the server.
270    let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
271    let db_path = koan_core::config::db_path();
272
273    // Spawn the player engine (headless — no TUI).
274    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
275
276    let server = KoanMcpServer::new(state, cmd_tx, db_path);
277
278    // Run the MCP server on the tokio runtime (blocking the main thread).
279    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
280    rt.block_on(async {
281        let transport = rmcp::transport::io::stdio();
282        let service = server
283            .serve(transport)
284            .await
285            .expect("failed to start MCP server");
286        let _ = service.waiting().await;
287    });
288}
289
290// ---------------------------------------------------------------------------
291// Tests
292// ---------------------------------------------------------------------------
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297    use koan_core::db::connection::Database;
298    use koan_core::db::queries;
299    use koan_core::player::commands::CommandChannel;
300    use tempfile::TempDir;
301
302    fn test_server() -> (KoanMcpServer, CommandChannel, TempDir) {
303        let tmp = TempDir::new().unwrap();
304        let db_path = tmp.path().join("test.db");
305        let db = Database::open(&db_path).unwrap();
306        koan_core::db::schema::create_tables(&db.conn).unwrap();
307
308        let state = SharedPlayerState::new();
309        let ch = CommandChannel::new();
310        let tx = ch.tx.clone();
311
312        let server = KoanMcpServer::new(state, tx, db_path);
313        (server, ch, tmp)
314    }
315
316    fn with_headers(headers: &[(&str, &str)]) -> rmcp::model::Extensions {
317        let mut req = axum::http::Request::builder();
318        for (k, v) in headers {
319            req = req.header(*k, *v);
320        }
321        let (parts, ()) = req.body(()).unwrap().into_parts();
322        let mut ext = rmcp::model::Extensions::new();
323        ext.insert(parts);
324        ext
325    }
326
327    #[test]
328    fn gateway_headers_act_as_that_account() {
329        use koan_core::auth::Role;
330        let (mut server, _ch, tmp) = test_server();
331        let db_path = tmp.path().join("test.db");
332        let db = Database::open(&db_path).unwrap();
333        queries::auth::create_user(&db.conn, "owner", "sesame", Role::Admin).unwrap();
334        queries::auth::create_user(&db.conn, "mate", "hunter22", Role::Readonly).unwrap();
335        server.users = Some(Arc::new(crate::auth::password::PasswordVerifier::new(
336            db_path,
337        )));
338
339        let as_ = |u: &str, p: &str| {
340            server.role(&with_headers(&[(USERNAME_HEADER, u), (PASSWORD_HEADER, p)]))
341        };
342        assert_eq!(as_("owner", "sesame"), Ok(Role::Admin));
343        assert_eq!(as_("mate", "hunter22"), Ok(Role::Readonly));
344        assert!(as_("owner", "wrong").is_err());
345        // No account named: the transport's default role.
346        assert_eq!(server.role(&with_headers(&[])), Ok(mcp_role()));
347    }
348
349    fn insert_test_track(db_path: &std::path::Path, title: &str, artist: &str, album: &str) -> i64 {
350        let db = Database::open(db_path).unwrap();
351        let meta = queries::TrackMeta {
352            title: title.to_string(),
353            artist: artist.to_string(),
354            album_artist: Some(artist.to_string()),
355            album: album.to_string(),
356            track_number: Some(1),
357            disc: Some(1),
358            date: Some("2024".into()),
359            genre: Some("Electronic".into()),
360            duration_ms: Some(240000),
361            path: Some(format!(
362                "/tmp/test/{}.flac",
363                title.to_lowercase().replace(' ', "_")
364            )),
365            codec: Some("FLAC".into()),
366            sample_rate: Some(44100),
367            bit_depth: Some(16),
368            channels: Some(2),
369            bitrate: Some(1411),
370            size_bytes: Some(42_000_000),
371            mtime: Some(1700000000),
372            source: "local".into(),
373            remote_id: None,
374            remote_url: None,
375            album_remote_id: None,
376            artist_remote_id: None,
377            mbid: None,
378            album_mbid: None,
379            album_added_at: None,
380            label: None,
381        };
382        queries::upsert_track(&db.conn, &meta).unwrap()
383    }
384
385    #[test]
386    fn schema_sdl_returns_schema() {
387        let (server, _ch, _tmp) = test_server();
388        let Json(resp) = server.schema_sdl();
389        let sdl = resp.result.as_str().unwrap();
390        assert!(sdl.contains("type QueryRoot"));
391        assert!(sdl.contains("type MutationRoot"));
392        assert!(sdl.contains("artists"));
393        assert!(sdl.contains("nowPlaying"));
394    }
395
396    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
397    async fn graphql_query_works() {
398        let (server, _ch, tmp) = test_server();
399        let db_path = tmp.path().join("test.db");
400        insert_test_track(&db_path, "Windowlicker", "Aphex Twin", "Windowlicker EP");
401
402        let result = server.graphql(
403            Parameters(GraphqlParams {
404                query: r#"{ tracks(search: "aphex") { edges { node { title artist } } } }"#.into(),
405                variables: None,
406            }),
407            Default::default(),
408        );
409        assert!(result.is_ok());
410        let Json(resp) = result.unwrap();
411        let data = &resp.result["data"]["tracks"]["edges"];
412        assert_eq!(data.as_array().unwrap().len(), 1);
413        assert_eq!(data[0]["node"]["title"], "Windowlicker");
414    }
415
416    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
417    async fn graphql_mutation_works() {
418        let (server, _ch, _tmp) = test_server();
419        let result = server.graphql(
420            Parameters(GraphqlParams {
421                query: "mutation { pause { ok message } }".into(),
422                variables: None,
423            }),
424            Default::default(),
425        );
426        assert!(result.is_ok());
427        let Json(resp) = result.unwrap();
428        assert_eq!(resp.result["data"]["pause"]["ok"], true);
429    }
430
431    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
432    async fn graphql_now_playing_stopped() {
433        let (server, _ch, _tmp) = test_server();
434        let result = server.graphql(
435            Parameters(GraphqlParams {
436                query: "{ nowPlaying { state positionMs } }".into(),
437                variables: None,
438            }),
439            Default::default(),
440        );
441        assert!(result.is_ok());
442        let Json(resp) = result.unwrap();
443        assert_eq!(resp.result["data"]["nowPlaying"]["state"], "STOPPED");
444    }
445
446    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
447    async fn graphql_library_stats() {
448        let (server, _ch, tmp) = test_server();
449        let db_path = tmp.path().join("test.db");
450        insert_test_track(&db_path, "T1", "A1", "Album1");
451
452        let result = server.graphql(
453            Parameters(GraphqlParams {
454                query: "{ libraryStats { totalTracks totalArtists totalAlbums } }".into(),
455                variables: None,
456            }),
457            Default::default(),
458        );
459        assert!(result.is_ok());
460        let Json(resp) = result.unwrap();
461        assert_eq!(resp.result["data"]["libraryStats"]["totalTracks"], 1);
462    }
463}