Skip to main content

qualia_mcp/
listener.rs

1//! Async stdio listener loop for Model Context Protocol (MCP) server.
2//!
3//! Follows `AGENTS.md` ยง0-B (<500 lines).
4
5use crate::protocol::process_jsonrpc_message;
6use crate::types::McpIntentFrame;
7use std::io::Write;
8use tokio::io::{AsyncBufReadExt, BufReader};
9
10/// Starts the MCP server on standard input/output with specified hardware flags.
11pub async fn start_mcp_listener_with_flags(
12    enable_qpu: bool,
13    enable_llm: bool,
14) -> Result<(), Box<dyn std::error::Error>> {
15    let intent_frame = McpIntentFrame {
16        purpose_hash: 0,
17        active_deontic_constraints: Vec::new(),
18        active_profile_id: None,
19        session_nonce: 0x4242,
20        sanctuary_override: None,
21        qpu_enabled: enable_qpu,
22        llm_enabled: enable_llm,
23    };
24
25    let stdin = tokio::io::stdin();
26    let reader = BufReader::new(stdin);
27    let mut lines = reader.lines();
28
29    log::info!("Qualia MCP Server listening on stdio (qpu={}, llm={})...", enable_qpu, enable_llm);
30
31    while let Ok(Some(line)) = lines.next_line().await {
32        let trimmed = line.trim();
33        if trimmed.is_empty() {
34            continue;
35        }
36
37        if let Some(response) = process_jsonrpc_message(trimmed, &intent_frame) {
38            let mut stdout = std::io::stdout().lock();
39            let _ = stdout.write_all(response.as_bytes());
40            let _ = stdout.write_all(b"\n");
41            let _ = stdout.flush();
42        }
43    }
44
45    log::info!("Qualia MCP stdio stream closed, shutting down.");
46    Ok(())
47}