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, ServerInfo};
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#[derive(Clone)]
47pub struct KoanMcpServer {
48    #[allow(dead_code)]
49    tool_router: ToolRouter<Self>,
50    graphql_schema: crate::graphql::KoanSchema,
51}
52
53impl KoanMcpServer {
54    pub fn new(
55        state: Arc<SharedPlayerState>,
56        cmd_tx: Sender<PlayerCommand>,
57        db_path: PathBuf,
58    ) -> Self {
59        let graphql_schema =
60            crate::graphql::build_schema(state.clone(), cmd_tx.clone(), db_path.clone(), None);
61        Self {
62            tool_router: Self::tool_router(),
63            graphql_schema,
64        }
65    }
66}
67
68use rmcp::handler::server::wrapper::Parameters;
69use rmcp::tool;
70
71#[tool_router]
72impl KoanMcpServer {
73    #[tool(
74        description = "Get the full GraphQL schema in SDL format. CALL THIS FIRST to learn all \
75        available queries, mutations, types, and filter parameters. The schema is the complete \
76        reference for everything koan can do — library discovery, playback control, queue \
77        management, favourites, snapshots, radio mode, device switching, and more."
78    )]
79    fn schema_sdl(&self) -> Json<GraphqlResponse> {
80        let sdl = self.graphql_schema.sdl();
81        Json(GraphqlResponse {
82            result: serde_json::Value::String(sdl),
83        })
84    }
85
86    #[tool(
87        description = "Execute a GraphQL query or mutation against the koan music player. \
88        This is the primary interface for ALL operations — library browsing, playback control, \
89        queue management, favourites, snapshots, radio, devices.\n\n\
90        Call schema_sdl first to learn the full schema.\n\n\
91        Quick examples:\n\
92        - Search: { tracks(search: \"aphex\") { edges { node { id title artist album } } } }\n\
93        - Filter: { albums(yearEnd: 1995, codec: \"FLAC\") { edges { node { title artistName date } } } }\n\
94        - Now playing: { nowPlaying { state positionMs track { title artist codec sampleRate } } }\n\
95        - Queue tracks: mutation { addToQueue(trackIds: [42, 43]) { ok addedCount } }\n\
96        - Play/pause: mutation { pause { ok } } / mutation { resume { ok } }\n\
97        - Snapshot: mutation { saveSnapshot(name: \"techno\") { ok } }\n\
98        - Radio: mutation { enableRadio { ok } }\n\n\
99        Track IDs are integers from the library. Queue item IDs are UUIDs from the queue.\n\
100        All string filters are case-insensitive substrings."
101    )]
102    fn graphql(
103        &self,
104        Parameters(params): Parameters<GraphqlParams>,
105    ) -> Result<Json<GraphqlResponse>, String> {
106        let schema = self.graphql_schema.clone();
107        let query = params.query;
108        let variables = params.variables;
109        let rt =
110            tokio::runtime::Handle::try_current().map_err(|_| "no tokio runtime".to_string())?;
111        let result = tokio::task::block_in_place(|| {
112            rt.block_on(crate::graphql::execute_in_process(
113                &schema, &query, variables,
114            ))
115        });
116        Ok(Json(GraphqlResponse { result }))
117    }
118}
119
120#[rmcp::tool_handler]
121impl ServerHandler for KoanMcpServer {
122    fn get_info(&self) -> ServerInfo {
123        ServerInfo::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(
124            "koan is a bit-perfect macOS music player. You control it entirely via GraphQL.\n\n\
125             ## How to use\n\
126             1. Call `schema_sdl` to get the full GraphQL schema\n\
127             2. Use the `graphql` tool for ALL queries and mutations\n\n\
128             ## What you can do\n\
129             - **Discover music**: query `artists`, `albums`, `tracks` with rich filters \
130               (genre, year range, codec, sample rate, bit depth, duration, favourites)\n\
131             - **Control playback**: mutations `play`, `pause`, `resume`, `stop`, `next`, \
132               `previous`, `seek`\n\
133             - **Manage queue**: `addToQueue`, `replaceQueue`, `removeFromQueue`, `moveInQueue`, \
134               `clearQueue`, `undo`, `redo`\n\
135             - **Favourites**: `favourite`, `unfavourite`, `toggleFavourite` (auto-syncs to \
136               Subsonic/Navidrome). Filter any query with `favouritesOnly: true`\n\
137             - **Snapshots**: `saveSnapshot`, `restoreSnapshot`, `deleteSnapshot` — bank curated \
138               mixes and switch between them\n\
139             - **Radio**: `enableRadio`, `disableRadio` — auto-queues similar tracks\n\
140             - **Devices**: query `devices`, mutation `setDevice`, `clearDevice`\n\
141             - **History**: query `playHistory`, `similarArtists`\n\n\
142             ## ID conventions\n\
143             - Track IDs: integers from the library database\n\
144             - Queue item IDs: UUIDs assigned when tracks enter the queue",
145        )
146    }
147}
148
149/// Entry point for `koan mcp` — starts a headless player with an MCP server on stdio.
150pub fn cmd_mcp() {
151    use koan_core::player::Player;
152    use rmcp::ServiceExt;
153
154    // Validate DB is accessible before starting the server.
155    let _db = koan_core::db::connection::Database::open_default().expect("failed to open database");
156    let db_path = koan_core::config::db_path();
157
158    // Spawn the player engine (headless — no TUI).
159    let (state, _timeline, _viz, cmd_tx) = Player::spawn();
160
161    let server = KoanMcpServer::new(state, cmd_tx, db_path);
162
163    // Run the MCP server on the tokio runtime (blocking the main thread).
164    let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
165    rt.block_on(async {
166        let transport = rmcp::transport::io::stdio();
167        let service = server
168            .serve(transport)
169            .await
170            .expect("failed to start MCP server");
171        let _ = service.waiting().await;
172    });
173}
174
175// ---------------------------------------------------------------------------
176// Tests
177// ---------------------------------------------------------------------------
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use koan_core::db::connection::Database;
183    use koan_core::db::queries;
184    use koan_core::player::commands::CommandChannel;
185    use tempfile::TempDir;
186
187    fn test_server() -> (KoanMcpServer, CommandChannel, TempDir) {
188        let tmp = TempDir::new().unwrap();
189        let db_path = tmp.path().join("test.db");
190        let db = Database::open(&db_path).unwrap();
191        koan_core::db::schema::create_tables(&db.conn).unwrap();
192
193        let state = SharedPlayerState::new();
194        let ch = CommandChannel::new();
195        let tx = ch.tx.clone();
196
197        let server = KoanMcpServer::new(state, tx, db_path);
198        (server, ch, tmp)
199    }
200
201    fn insert_test_track(db_path: &std::path::Path, title: &str, artist: &str, album: &str) -> i64 {
202        let db = Database::open(db_path).unwrap();
203        let meta = queries::TrackMeta {
204            title: title.to_string(),
205            artist: artist.to_string(),
206            album_artist: Some(artist.to_string()),
207            album: album.to_string(),
208            track_number: Some(1),
209            disc: Some(1),
210            date: Some("2024".into()),
211            genre: Some("Electronic".into()),
212            duration_ms: Some(240000),
213            path: Some(format!(
214                "/tmp/test/{}.flac",
215                title.to_lowercase().replace(' ', "_")
216            )),
217            codec: Some("FLAC".into()),
218            sample_rate: Some(44100),
219            bit_depth: Some(16),
220            channels: Some(2),
221            bitrate: Some(1411),
222            size_bytes: Some(42_000_000),
223            mtime: Some(1700000000),
224            source: "local".into(),
225            remote_id: None,
226            remote_url: None,
227            label: None,
228        };
229        queries::upsert_track(&db.conn, &meta).unwrap()
230    }
231
232    #[test]
233    fn schema_sdl_returns_schema() {
234        let (server, _ch, _tmp) = test_server();
235        let Json(resp) = server.schema_sdl();
236        let sdl = resp.result.as_str().unwrap();
237        assert!(sdl.contains("type QueryRoot"));
238        assert!(sdl.contains("type MutationRoot"));
239        assert!(sdl.contains("artists"));
240        assert!(sdl.contains("nowPlaying"));
241    }
242
243    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
244    async fn graphql_query_works() {
245        let (server, _ch, tmp) = test_server();
246        let db_path = tmp.path().join("test.db");
247        insert_test_track(&db_path, "Windowlicker", "Aphex Twin", "Windowlicker EP");
248
249        let result = server.graphql(Parameters(GraphqlParams {
250            query: r#"{ tracks(search: "aphex") { edges { node { title artist } } } }"#.into(),
251            variables: None,
252        }));
253        assert!(result.is_ok());
254        let Json(resp) = result.unwrap();
255        let data = &resp.result["data"]["tracks"]["edges"];
256        assert_eq!(data.as_array().unwrap().len(), 1);
257        assert_eq!(data[0]["node"]["title"], "Windowlicker");
258    }
259
260    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
261    async fn graphql_mutation_works() {
262        let (server, _ch, _tmp) = test_server();
263        let result = server.graphql(Parameters(GraphqlParams {
264            query: "mutation { pause { ok message } }".into(),
265            variables: None,
266        }));
267        assert!(result.is_ok());
268        let Json(resp) = result.unwrap();
269        assert_eq!(resp.result["data"]["pause"]["ok"], true);
270    }
271
272    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
273    async fn graphql_now_playing_stopped() {
274        let (server, _ch, _tmp) = test_server();
275        let result = server.graphql(Parameters(GraphqlParams {
276            query: "{ nowPlaying { state positionMs } }".into(),
277            variables: None,
278        }));
279        assert!(result.is_ok());
280        let Json(resp) = result.unwrap();
281        assert_eq!(resp.result["data"]["nowPlaying"]["state"], "STOPPED");
282    }
283
284    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
285    async fn graphql_library_stats() {
286        let (server, _ch, tmp) = test_server();
287        let db_path = tmp.path().join("test.db");
288        insert_test_track(&db_path, "T1", "A1", "Album1");
289
290        let result = server.graphql(Parameters(GraphqlParams {
291            query: "{ libraryStats { totalTracks totalArtists totalAlbums } }".into(),
292            variables: None,
293        }));
294        assert!(result.is_ok());
295        let Json(resp) = result.unwrap();
296        assert_eq!(resp.result["data"]["libraryStats"]["totalTracks"], 1);
297    }
298}