From 1d1747deb3800aee830f3d7a1dd9ba8f53e4781f Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 18:43:25 +0300 Subject: [PATCH 1/2] feat(tauri): querya-mcp stdio shim for Rust MCP host Add a Rust `querya-mcp` binary that reads the same endpoint file as the Flutter bridge, authenticates with the token, and pipes stdio to the in-process loopback MCP server so external clients can dial Tauri. Closes #1902 --- apps/tauri/src-tauri/Cargo.toml | 6 +- apps/tauri/src-tauri/src/bin/querya_mcp.rs | 23 +++ apps/tauri/src-tauri/src/lib.rs | 2 +- apps/tauri/src-tauri/src/mcp/mod.rs | 2 + apps/tauri/src-tauri/src/mcp/server.rs | 1 - apps/tauri/src-tauri/src/mcp/shim.rs | 230 +++++++++++++++++++++ 6 files changed, 261 insertions(+), 3 deletions(-) create mode 100644 apps/tauri/src-tauri/src/bin/querya_mcp.rs create mode 100644 apps/tauri/src-tauri/src/mcp/shim.rs diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index b6c70b2e..230e9036 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -9,6 +9,10 @@ edition = "2021" name = "querya_desktop_tauri_lib" crate-type = ["staticlib", "cdylib", "rlib"] +[[bin]] +name = "querya-mcp" +path = "src/bin/querya_mcp.rs" + [build-dependencies] tauri-build = { version = "2", features = [] } @@ -21,7 +25,7 @@ serde_json = "1" uuid = { version = "1", features = ["v4", "serde"] } rusqlite = { version = "0.32", features = ["bundled"] } dirs = "5" -tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net", "io-util", "sync"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net", "io-util", "sync", "io-std", "process"] } sqlx = { version = "0.8", default-features = false, features = [ "runtime-tokio", "postgres", diff --git a/apps/tauri/src-tauri/src/bin/querya_mcp.rs b/apps/tauri/src-tauri/src/bin/querya_mcp.rs new file mode 100644 index 00000000..eb1d88cb --- /dev/null +++ b/apps/tauri/src-tauri/src/bin/querya_mcp.rs @@ -0,0 +1,23 @@ +//! `querya-mcp` — stdio bridge to a running Querya Desktop MCP host. +//! +//! Compatible with the Flutter endpoint file (`QUERYA_MCP_ENDPOINT` override). + +use querya_desktop_tauri_lib::mcp::shim::run_shim; +use std::env; +use std::process::ExitCode; + +#[tokio::main] +async fn main() -> ExitCode { + if env::args().any(|a| a == "--help" || a == "-h") { + eprintln!( + "Usage: querya-mcp\n\n\ + Connects an MCP client over stdio to the MCP server of a running\n\ + Querya Desktop. Takes no arguments; the endpoint file can be\n\ + overridden with QUERYA_MCP_ENDPOINT." + ); + return ExitCode::SUCCESS; + } + + let code = run_shim(None).await; + ExitCode::from(code as u8) +} diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index b40cb022..fd8466c4 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -1,6 +1,6 @@ mod commands; mod connection; -mod mcp; +pub mod mcp; mod profiles; mod secrets; mod ssh_tunnel; diff --git a/apps/tauri/src-tauri/src/mcp/mod.rs b/apps/tauri/src-tauri/src/mcp/mod.rs index a0545e8f..46c59b74 100644 --- a/apps/tauri/src-tauri/src/mcp/mod.rs +++ b/apps/tauri/src-tauri/src/mcp/mod.rs @@ -3,9 +3,11 @@ mod endpoint; mod host; mod server; +pub mod shim; #[allow(unused_imports)] pub use endpoint::McpEndpoint; pub use host::{McpController, McpError, McpStatus}; #[allow(unused_imports)] pub use server::QueryaMcpServer; +pub use shim::{run_shim, APP_NOT_RUNNING}; diff --git a/apps/tauri/src-tauri/src/mcp/server.rs b/apps/tauri/src-tauri/src/mcp/server.rs index 37b7ba33..67dfec7c 100644 --- a/apps/tauri/src-tauri/src/mcp/server.rs +++ b/apps/tauri/src-tauri/src/mcp/server.rs @@ -10,7 +10,6 @@ use rmcp::model::{ }; use rmcp::{schemars, tool, tool_handler, tool_router}; use serde::{Deserialize, Serialize}; -use serde_json::json; use std::sync::Arc; const MCP_MAX_ROWS: usize = 1000; diff --git a/apps/tauri/src-tauri/src/mcp/shim.rs b/apps/tauri/src-tauri/src/mcp/shim.rs new file mode 100644 index 00000000..efc1bf66 --- /dev/null +++ b/apps/tauri/src-tauri/src/mcp/shim.rs @@ -0,0 +1,230 @@ +//! Stdio → loopback bridge for external MCP clients (`querya-mcp`). + +use super::endpoint::McpEndpoint; +use std::path::PathBuf; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpStream; + +/// Message when Querya Desktop is not reachable (Flutter parity). +pub const APP_NOT_RUNNING: &str = "Querya Desktop is not running or its MCP server is off. Start Querya Desktop and enable the MCP server in Settings, then retry."; + +/// Forward stdin/stdout to the running Querya MCP host. +/// +/// Returns the process exit code (0 = clean, 1 = unavailable / lost). +pub async fn run_shim(endpoint_file: Option) -> i32 { + let path = endpoint_file.unwrap_or_else(McpEndpoint::default_path); + let endpoint = match McpEndpoint::read(&path) { + Ok(Some(ep)) => ep, + Ok(None) => { + eprintln!("querya-mcp: {APP_NOT_RUNNING} (endpoint: {})", path.display()); + return answer_unavailable().await; + } + Err(e) => { + eprintln!("querya-mcp: {APP_NOT_RUNNING} (endpoint: {}: {e})", path.display()); + return answer_unavailable().await; + } + }; + + let connect = TcpStream::connect(("127.0.0.1", endpoint.port)); + let mut socket = match tokio::time::timeout(Duration::from_secs(3), connect).await { + Ok(Ok(s)) => s, + Ok(Err(e)) => { + eprintln!( + "querya-mcp: {APP_NOT_RUNNING} (endpoint: {}: {e})", + path.display() + ); + return answer_unavailable().await; + } + Err(_) => { + eprintln!( + "querya-mcp: {APP_NOT_RUNNING} (endpoint: {}: connect timed out)", + path.display() + ); + return answer_unavailable().await; + } + }; + + if let Err(e) = socket.set_nodelay(true) { + eprintln!("querya-mcp: tcp_nodelay: {e}"); + } + + if let Err(e) = socket + .write_all(format!("{}\n", endpoint.token).as_bytes()) + .await + { + eprintln!("querya-mcp: connection to Querya Desktop lost: {e}"); + return 1; + } + + let (mut sock_read, mut sock_write) = socket.into_split(); + let mut stdin = tokio::io::stdin(); + let mut stdout = tokio::io::stdout(); + + let to_app = async { + let mut buf = vec![0u8; 65536]; + loop { + match stdin.read(&mut buf).await { + Ok(0) => { + let _ = sock_write.shutdown().await; + break; + } + Ok(n) => { + if sock_write.write_all(&buf[..n]).await.is_err() { + break; + } + } + Err(_) => break, + } + } + }; + + let from_app = async { + let mut buf = vec![0u8; 65536]; + loop { + match sock_read.read(&mut buf).await { + Ok(0) => break, + Ok(n) => { + if stdout.write_all(&buf[..n]).await.is_err() { + break; + } + let _ = stdout.flush().await; + } + Err(_) => break, + } + } + }; + + tokio::select! { + _ = to_app => {} + _ = from_app => {} + } + 0 +} + +async fn answer_unavailable() -> i32 { + let stdin = BufReader::new(tokio::io::stdin()); + let mut lines = stdin.lines(); + let mut stdout = tokio::io::stdout(); + while let Ok(Some(line)) = lines.next_line().await { + let id = serde_json::from_str::(&line) + .ok() + .and_then(|v| v.get("id").cloned()) + .filter(|id| !id.is_null()); + let Some(id) = id else { + continue; + }; + let err = serde_json::json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": -32000, "message": APP_NOT_RUNNING } + }); + let _ = stdout.write_all(format!("{err}\n").as_bytes()).await; + let _ = stdout.flush().await; + } + 1 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::connection::{ConnectionConfig, ConnectionManager, ConnectionRegistry}; + use crate::mcp::host::McpController; + use std::process::Stdio; + use std::sync::Arc; + use tokio::process::Command; + + #[test] + fn shim_initialize_through_running_host() { + if std::env::var_os("QUERYA_SKIP_MCP").is_some() { + return; + } + + let dir = std::env::temp_dir().join(format!( + "querya-mcp-shim-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&dir).unwrap(); + let db_path = dir.join("fixture.db"); + let ep_path = dir.join("mcp-endpoint.json"); + { + let conn = rusqlite::Connection::open(&db_path).unwrap(); + conn.execute_batch("CREATE TABLE t (id INTEGER); INSERT INTO t VALUES (1);") + .unwrap(); + } + + let registry = Arc::new(ConnectionRegistry::new()); + registry + .connect(ConnectionConfig::Sqlite { + path: db_path.to_string_lossy().into_owned(), + id: Some("shim-sqlite".into()), + }) + .unwrap(); + + crate::connection::runtime::block_on(async { + let ctrl = McpController::new(Arc::clone(®istry)); + let _ = ctrl.start_async(Some(ep_path.clone())).await.unwrap(); + + // Prefer the built bin when available; otherwise exercise library path. + let bin = std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(|d| d.join("querya-mcp"))); + let use_bin = bin.as_ref().map(|b| b.exists()).unwrap_or(false); + + let output = if use_bin { + let mut child = Command::new(bin.unwrap()) + .env("QUERYA_MCP_ENDPOINT", &ep_path) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn querya-mcp"); + let mut stdin = child.stdin.take().unwrap(); + let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"shim-test","version":"0"}}}"#; + use tokio::io::AsyncWriteExt as _; + stdin.write_all(format!("{init}\n").as_bytes()).await.unwrap(); + drop(stdin); + let out = child.wait_with_output().await.unwrap(); + String::from_utf8_lossy(&out.stdout).into_owned() + } else { + // Library-level: connect like the shim would. + let endpoint = McpEndpoint::read(&ep_path).unwrap().unwrap(); + let mut socket = TcpStream::connect(("127.0.0.1", endpoint.port)) + .await + .unwrap(); + socket + .write_all(format!("{}\n", endpoint.token).as_bytes()) + .await + .unwrap(); + let init = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"shim-test","version":"0"}}}"#; + socket + .write_all(format!("{init}\n").as_bytes()) + .await + .unwrap(); + let mut reader = BufReader::new(socket); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + line + }; + + assert!( + output.contains("querya-desktop") || output.contains("protocolVersion"), + "unexpected shim output: {output}" + ); + let _ = ctrl.stop_async().await; + }); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn missing_endpoint_is_none() { + let missing = std::env::temp_dir().join(format!( + "querya-mcp-missing-{}-{}.json", + std::process::id(), + uuid::Uuid::new_v4() + )); + assert!(McpEndpoint::read(&missing).unwrap().is_none()); + } +} From ceda2c8df11cb16338d6a6e2487cbbf3edbdfe5c Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 18:43:53 +0300 Subject: [PATCH 2/2] fix(mcp): restore json! import in tools test --- apps/tauri/src-tauri/src/mcp/server.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/tauri/src-tauri/src/mcp/server.rs b/apps/tauri/src-tauri/src/mcp/server.rs index 67dfec7c..d7d1b385 100644 --- a/apps/tauri/src-tauri/src/mcp/server.rs +++ b/apps/tauri/src-tauri/src/mcp/server.rs @@ -201,6 +201,7 @@ mod tests { use crate::connection::ConnectionConfig; use crate::mcp::endpoint::McpEndpoint; use crate::mcp::host::McpController; + use serde_json::json; use std::time::Duration; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::TcpStream;