Skip to main content

qualia_cli/
mcp.rs

1use clap::{Subcommand, ValueEnum};
2use serde::{Deserialize, Serialize};
3use serde_json::{json, Value};
4use std::fs;
5use std::io::{BufRead, BufReader, Write};
6use std::net::{Shutdown, TcpStream};
7use std::path::PathBuf;
8use std::process::{Command, Stdio};
9use std::time::Duration;
10use sysinfo::{Pid, Signal, System};
11use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader as TokioBufReader};
12use tokio::net::{TcpListener, TcpStream as TokioTcpStream};
13
14pub const DEFAULT_MCP_BIND: &str = "127.0.0.1:4244";
15const PID_FILE_NAME: &str = "mcp-service.json";
16const LOG_FILE_NAME: &str = "mcp-service.log";
17const ERR_LOG_FILE_NAME: &str = "mcp-service.err.log";
18
19#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, ValueEnum)]
20#[serde(rename_all = "lowercase")]
21pub enum McpTransport {
22    Stdio,
23    Tcp,
24}
25
26#[derive(Subcommand, Debug)]
27pub enum McpAction {
28    /// Run the MCP server in the foreground
29    Serve {
30        /// Transport used by this MCP server instance
31        #[arg(long, value_enum, default_value_t = McpTransport::Stdio)]
32        transport: McpTransport,
33        /// Bind address for TCP transport
34        #[arg(long, default_value = DEFAULT_MCP_BIND)]
35        bind: String,
36        /// Hidden child mode used by `mcp start`
37        #[arg(long, hide = true)]
38        service_child: bool,
39    },
40    /// Start a detached MCP service with PID management
41    Start {
42        /// Bind address for the background TCP transport
43        #[arg(long, default_value = DEFAULT_MCP_BIND)]
44        bind: String,
45        /// Replace an existing recorded service if its PID file is stale
46        #[arg(long)]
47        force: bool,
48    },
49    /// Stop the detached MCP service
50    Stop,
51    /// Report whether the detached MCP service is running
52    Status,
53    /// Inspect the MCP surface, transport, and health checks
54    Doctor,
55    /// Proxy MCP stdio to the Webizen Desktop GUI application (TCP 4245)
56    DesktopProxy,
57}
58
59#[derive(Debug, Serialize, Deserialize)]
60struct McpServiceRecord {
61    pid: u32,
62    transport: McpTransport,
63    bind: String,
64    started_at: String,
65    log_path: String,
66    qpu_enabled: bool,
67}
68
69/// Handles the subcommand action.
70pub async fn handle(action: &McpAction, qpu_enabled: bool) {
71    match action {
72        McpAction::Serve {
73            transport,
74            bind,
75            service_child,
76        } => {
77            if *service_child {
78                let _ = write_service_record(McpServiceRecord {
79                    pid: std::process::id(),
80                    transport: *transport,
81                    bind: bind.clone(),
82                    started_at: chrono::Utc::now().to_rfc3339(),
83                    log_path: log_file_path().display().to_string(),
84                    qpu_enabled,
85                });
86            }
87            match transport {
88                McpTransport::Stdio => {
89                    let _ = qualia_mcp::start_mcp_listener_with_flags(qpu_enabled, true)
90                        .await;
91                }
92                McpTransport::Tcp => {
93                    if let Err(err) = serve_tcp(bind, qpu_enabled).await {
94                        eprintln!("MCP TCP server failed: {err}");
95                    }
96                }
97            }
98        }
99        McpAction::Start { bind, force } => {
100            if let Err(err) = start_background(bind, qpu_enabled, *force) {
101                eprintln!("Failed to start MCP service: {err}");
102            }
103        }
104        McpAction::Stop => {
105            if let Err(err) = stop_background() {
106                eprintln!("Failed to stop MCP service: {err}");
107            }
108        }
109        McpAction::Status => {
110            if let Err(err) = print_status() {
111                eprintln!("Failed to inspect MCP service: {err}");
112            }
113        }
114        McpAction::Doctor => {
115            if let Err(err) = print_doctor() {
116                eprintln!("MCP doctor failed: {err}");
117            }
118        }
119        McpAction::DesktopProxy => {
120            if let Err(err) = run_desktop_proxy() {
121                eprintln!("MCP desktop proxy failed: {err}");
122            }
123        }
124    }
125}
126
127/// Proxy MCP stdio ↔ the Webizen Desktop GUI's TCP MCP server (127.0.0.1:4245). An external MCP
128/// client that speaks stdio (e.g. an editor agent) can drive the desktop app's tool surface through
129/// this bridge: each stdin JSON-RPC line is forwarded to the desktop server and its reply written to
130/// stdout.
131fn run_desktop_proxy() -> Result<(), String> {
132    let stream = TcpStream::connect("127.0.0.1:4245")
133        .map_err(|e| format!("connect desktop MCP (127.0.0.1:4245): {e}"))?;
134    let mut tcp_writer = stream.try_clone().map_err(|e| e.to_string())?;
135    let mut tcp_reader = BufReader::new(stream);
136    let stdin = std::io::stdin();
137    let stdout = std::io::stdout();
138    let mut reply = String::new();
139    for req in stdin.lock().lines() {
140        let req = req.map_err(|e| e.to_string())?;
141        if req.trim().is_empty() {
142            continue;
143        }
144        tcp_writer
145            .write_all(req.as_bytes())
146            .map_err(|e| e.to_string())?;
147        tcp_writer.write_all(b"\n").map_err(|e| e.to_string())?;
148        tcp_writer.flush().ok();
149        reply.clear();
150        if tcp_reader
151            .read_line(&mut reply)
152            .map_err(|e| e.to_string())?
153            == 0
154        {
155            break;
156        }
157        let mut out = stdout.lock();
158        out.write_all(reply.as_bytes()).map_err(|e| e.to_string())?;
159        out.flush().ok();
160    }
161    Ok(())
162}
163
164async fn serve_tcp(bind: &str, qpu_enabled: bool) -> Result<(), String> {
165    let listener = TcpListener::bind(bind)
166        .await
167        .map_err(|e| format!("bind {bind}: {e}"))?;
168    eprintln!("[MCP Server] Listening on tcp://{bind}");
169
170    loop {
171        let (socket, _) = listener
172            .accept()
173            .await
174            .map_err(|e| format!("accept failed: {e}"))?;
175        tokio::spawn(handle_tcp_client(socket, qpu_enabled));
176    }
177}
178
179async fn handle_tcp_client(stream: TokioTcpStream, qpu_enabled: bool) {
180    let (reader_half, mut writer_half) = stream.into_split();
181    let mut reader = TokioBufReader::new(reader_half);
182    let mut line = String::new();
183    let intent = qualia_mcp::McpIntentFrame {
184        qpu_enabled,
185        llm_enabled: true,
186        ..Default::default()
187    };
188
189    loop {
190        line.clear();
191        match reader.read_line(&mut line).await {
192            Ok(0) => break,
193            Ok(_) => {
194                let request = line.trim_end_matches(['\r', '\n']);
195                if request.is_empty() {
196                    continue;
197                }
198                if let Some(reply) =
199                    qualia_mcp::process_jsonrpc_message(request, &intent)
200                {
201                    let _ = writer_half.write_all(reply.as_bytes()).await;
202                    let _ = writer_half.write_all(b"\n").await;
203                }
204            }
205            Err(_) => break,
206        }
207    }
208}
209
210/// Starts in the background.
211pub fn start_background(bind: &str, qpu_enabled: bool, force: bool) -> Result<(), String> {
212    ensure_runtime_dir()?;
213
214    if let Some(record) = read_service_record()? {
215        if pid_is_running(record.pid) {
216            return Err(format!(
217                "service already running (pid {}, bind {}). Use `qualia-cli mcp stop` first.",
218                record.pid, record.bind
219            ));
220        }
221        if !force {
222            eprintln!(
223                "Removing stale MCP service record for pid {} at {}.",
224                record.pid, record.bind
225            );
226        }
227        let _ = clear_service_record();
228    }
229
230    let launched_pid = spawn_detached_service(bind, qpu_enabled)?;
231
232    for _ in 0..20 {
233        std::thread::sleep(Duration::from_millis(200));
234        if let Some(record) = read_service_record()? {
235            if record.bind == bind && ping_service(bind).is_ok() {
236                println!(
237                    "MCP service started on tcp://{} (pid {}).",
238                    record.bind, record.pid
239                );
240                return Ok(());
241            }
242        }
243    }
244
245    let pid_hint = read_service_record()?
246        .map(|record| record.pid.to_string())
247        .or_else(|| launched_pid.map(|pid| pid.to_string()))
248        .unwrap_or_else(|| "unknown".to_string());
249    match ping_service(bind) {
250        Ok(_) => {
251            println!("MCP service started on tcp://{bind} (pid {pid_hint}).");
252            Ok(())
253        }
254        Err(err) => Err(format!(
255            "spawned pid {pid_hint}, but health probe failed: {err}. Check {}",
256            err_log_file_path().display()
257        )),
258    }
259}
260
261fn spawn_detached_service(bind: &str, qpu_enabled: bool) -> Result<Option<u32>, String> {
262    #[cfg(windows)]
263    {
264        spawn_detached_service_windows(bind, qpu_enabled)
265    }
266
267    #[cfg(not(windows))]
268    {
269        spawn_detached_service_portable(bind, qpu_enabled)
270    }
271}
272
273#[cfg(windows)]
274fn spawn_detached_service_windows(bind: &str, qpu_enabled: bool) -> Result<Option<u32>, String> {
275    let current_exe = std::env::current_exe().map_err(|e| e.to_string())?;
276    let log = log_file_path();
277    let err = err_log_file_path();
278    let batch = runtime_dir().join("mcp-start.cmd");
279    let line = if qpu_enabled {
280        format!(
281            "@echo off\r\n\"{}\" --enable-qpu mcp serve --transport tcp --bind {bind} --service-child 1>> \"{}\" 2>> \"{}\"\r\n",
282            current_exe.display(),
283            log.display(),
284            err.display()
285        )
286    } else {
287        format!(
288            "@echo off\r\n\"{}\" mcp serve --transport tcp --bind {bind} --service-child 1>> \"{}\" 2>> \"{}\"\r\n",
289            current_exe.display(),
290            log.display(),
291            err.display()
292        )
293    };
294    fs::write(&batch, line).map_err(|e| format!("write {}: {e}", batch.display()))?;
295
296    let mut command = Command::new("cmd");
297    command
298        .arg("/C")
299        .arg("start")
300        .arg("/B")
301        .arg("")
302        .arg(&batch)
303        .stdin(Stdio::null());
304
305    use std::os::windows::process::CommandExt;
306    const CREATE_NO_WINDOW: u32 = 0x08000000;
307    const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
308    command.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
309
310    let child = command.spawn().map_err(|e| format!("spawn failed: {e}"))?;
311    Ok(Some(child.id()))
312}
313
314#[cfg(not(windows))]
315fn spawn_detached_service_portable(bind: &str, qpu_enabled: bool) -> Result<Option<u32>, String> {
316    let current_exe = std::env::current_exe().map_err(|e| e.to_string())?;
317    let mut command = Command::new(current_exe);
318    if qpu_enabled {
319        command.arg("--enable-qpu");
320    }
321    command
322        .arg("mcp")
323        .arg("serve")
324        .arg("--transport")
325        .arg("tcp")
326        .arg("--bind")
327        .arg(bind)
328        .arg("--service-child")
329        .stdin(Stdio::null());
330
331    let child = command.spawn().map_err(|e| format!("spawn failed: {e}"))?;
332    Ok(Some(child.id()))
333}
334
335/// Stops the background service.
336pub fn stop_background() -> Result<(), String> {
337    let Some(record) = read_service_record()? else {
338        println!("MCP service is not running.");
339        return Ok(());
340    };
341
342    if !pid_is_running(record.pid) {
343        clear_service_record()?;
344        println!("Removed stale MCP service record for pid {}.", record.pid);
345        return Ok(());
346    }
347
348    let mut system = System::new_all();
349    system.refresh_all();
350    let pid = Pid::from_u32(record.pid);
351    let Some(process) = system.process(pid) else {
352        clear_service_record()?;
353        println!("Removed stale MCP service record for pid {}.", record.pid);
354        return Ok(());
355    };
356
357    let terminated = process.kill_with(Signal::Term).unwrap_or(false) || process.kill();
358    if !terminated {
359        return Err(format!("unable to terminate pid {}", record.pid));
360    }
361
362    for _ in 0..10 {
363        if !pid_is_running(record.pid) {
364            clear_service_record()?;
365            println!("Stopped MCP service pid {}.", record.pid);
366            return Ok(());
367        }
368        std::thread::sleep(Duration::from_millis(200));
369    }
370
371    clear_service_record()?;
372    println!(
373        "Sent termination to pid {} and cleared the MCP service record.",
374        record.pid
375    );
376    Ok(())
377}
378
379/// Prints status.
380pub fn print_status() -> Result<(), String> {
381    let Some(record) = read_service_record()? else {
382        println!("stopped");
383        return Ok(());
384    };
385
386    let running = pid_is_running(record.pid);
387    let health = ping_service(&record.bind).ok();
388    let health_label = if health.is_some() {
389        "healthy"
390    } else {
391        "unreachable"
392    };
393
394    if running {
395        println!(
396            "running pid={} transport={:?} bind={} health={}",
397            record.pid, record.transport, record.bind, health_label
398        );
399    } else {
400        println!(
401            "stale pid={} transport={:?} bind={} health={}",
402            record.pid, record.transport, record.bind, health_label
403        );
404    }
405    Ok(())
406}
407
408/// Prints diagnostics.
409pub fn print_doctor() -> Result<(), String> {
410    println!("MCP doctor");
411    println!("  foreground stdio : qualia-cli mcp serve");
412    println!(
413        "  background tcp   : qualia-cli mcp start --bind {}",
414        DEFAULT_MCP_BIND
415    );
416
417    match read_service_record()? {
418        Some(record) => {
419            println!(
420                "  service record   : pid={} transport={:?} bind={}",
421                record.pid, record.transport, record.bind
422            );
423            println!("  pid alive        : {}", pid_is_running(record.pid));
424            println!("  log file         : {}", record.log_path);
425
426            match ping_service(&record.bind) {
427                Ok(reply) => {
428                    println!("  health           : ok");
429                    if let Ok(tool_reply) = send_request(
430                        &record.bind,
431                        &json!({"jsonrpc":"2.0","id":"tools","method":"tools/list"}),
432                    ) {
433                        let count = tool_reply["result"]["tools"]
434                            .as_array()
435                            .map(|tools| tools.len())
436                            .unwrap_or(0);
437                        println!("  tools/list       : {} tool(s)", count);
438                    }
439                    println!(
440                        "  ping response    : {}",
441                        reply["jsonrpc"].as_str().unwrap_or("unknown")
442                    );
443                }
444                Err(err) => {
445                    println!("  health           : failed ({err})");
446                }
447            }
448        }
449        None => {
450            println!("  service record   : none");
451            println!("  health           : service not running");
452        }
453    }
454
455    Ok(())
456}
457
458fn ping_service(bind: &str) -> Result<Value, String> {
459    send_request(bind, &json!({"jsonrpc":"2.0","id":"ping","method":"ping"}))
460}
461
462fn send_request(bind: &str, payload: &Value) -> Result<Value, String> {
463    let mut stream = TcpStream::connect(bind).map_err(|e| format!("connect {bind}: {e}"))?;
464    stream
465        .set_read_timeout(Some(Duration::from_secs(2)))
466        .map_err(|e| e.to_string())?;
467    stream
468        .set_write_timeout(Some(Duration::from_secs(2)))
469        .map_err(|e| e.to_string())?;
470
471    let request = serde_json::to_string(payload).map_err(|e| e.to_string())?;
472    stream
473        .write_all(request.as_bytes())
474        .map_err(|e| format!("write request: {e}"))?;
475    stream
476        .write_all(b"\n")
477        .map_err(|e| format!("write newline: {e}"))?;
478    stream.flush().map_err(|e| e.to_string())?;
479    let _ = stream.shutdown(Shutdown::Write);
480
481    let mut reader = BufReader::new(stream);
482    let mut response = String::new();
483    reader
484        .read_line(&mut response)
485        .map_err(|e| format!("read response: {e}"))?;
486    if response.trim().is_empty() {
487        return Err("empty response".to_string());
488    }
489    serde_json::from_str(response.trim()).map_err(|e| format!("decode response: {e}"))
490}
491
492fn ensure_runtime_dir() -> Result<(), String> {
493    fs::create_dir_all(runtime_dir()).map_err(|e| e.to_string())
494}
495
496fn runtime_dir() -> PathBuf {
497    state_dir().join("run")
498}
499
500fn state_dir() -> PathBuf {
501    if let Ok(dir) = std::env::var("QUALIA_DATA_DIR") {
502        return PathBuf::from(dir);
503    }
504    if let Ok(dir) = std::env::var("QUALIA_STORAGE_PATH") {
505        return PathBuf::from(dir);
506    }
507    if let Ok(dir) = std::env::current_dir() {
508        return dir.join(".qualia");
509    }
510    if let Ok(home) = std::env::var("HOME") {
511        return PathBuf::from(home).join(".qualia");
512    }
513    if let Ok(home) = std::env::var("USERPROFILE") {
514        return PathBuf::from(home).join(".qualia");
515    }
516    PathBuf::from(".qualia")
517}
518
519fn pid_file_path() -> PathBuf {
520    runtime_dir().join(PID_FILE_NAME)
521}
522
523fn log_file_path() -> PathBuf {
524    runtime_dir().join(LOG_FILE_NAME)
525}
526
527fn err_log_file_path() -> PathBuf {
528    runtime_dir().join(ERR_LOG_FILE_NAME)
529}
530
531fn read_service_record() -> Result<Option<McpServiceRecord>, String> {
532    let path = pid_file_path();
533    if !path.exists() {
534        return Ok(None);
535    }
536    let raw = fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
537    let record =
538        serde_json::from_str(&raw).map_err(|e| format!("decode {}: {e}", path.display()))?;
539    Ok(Some(record))
540}
541
542fn write_service_record(record: McpServiceRecord) -> Result<(), String> {
543    ensure_runtime_dir()?;
544    let path = pid_file_path();
545    let raw = serde_json::to_string_pretty(&record).map_err(|e| e.to_string())?;
546    fs::write(&path, raw).map_err(|e| format!("write {}: {e}", path.display()))
547}
548
549fn clear_service_record() -> Result<(), String> {
550    let path = pid_file_path();
551    if path.exists() {
552        fs::remove_file(&path).map_err(|e| format!("remove {}: {e}", path.display()))?;
553    }
554    Ok(())
555}
556
557fn pid_is_running(pid: u32) -> bool {
558    let mut system = System::new_all();
559    system.refresh_all();
560    system.process(Pid::from_u32(pid)).is_some()
561}