From 77723cef715e658294cc5e6e6c7d0f5bf20090c5 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 18:39:42 +0300 Subject: [PATCH 1/2] feat(rust): MCP list_connections and run_query tools Wire rmcp tools to the live ConnectionRegistry so clients can list open SQL sessions and run read-only queries (sql_guard + row cap). Verified against an in-process SQLite fixture over the loopback MCP host. Closes #1901 --- "apps/tauri/src-tauri/\nnew = State" | 0 apps/tauri/src-tauri/Cargo.toml | 2 +- apps/tauri/src-tauri/src/commands.rs | 64 ++-- .../tauri/src-tauri/src/connection/manager.rs | 9 + apps/tauri/src-tauri/src/lib.rs | 5 +- apps/tauri/src-tauri/src/mcp/host.rs | 33 +- apps/tauri/src-tauri/src/mcp/server.rs | 308 +++++++++++++++++- 7 files changed, 369 insertions(+), 52 deletions(-) create mode 100644 "apps/tauri/src-tauri/\nnew = State" diff --git "a/apps/tauri/src-tauri/\nnew = State" "b/apps/tauri/src-tauri/\nnew = State" new file mode 100644 index 00000000..e69de29b diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index 82e377be..b6c70b2e 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -47,7 +47,7 @@ redis = { version = "0.27", features = ["aio", "tokio-comp"] } mongodb = "3.10.1" russh = { version = "0.65.1", features = ["default"] } rand = "0.10.4" -rmcp = { version = "3.10.0", features = ["server", "transport-async-rw"] } +rmcp = { version = "3.10.0", features = ["macros", "schemars", "server", "transport-async-rw"] } [profile.release] codegen-units = 1 diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index b9f2fd04..265b2f4a 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -60,7 +60,7 @@ pub struct ConnectMongoRequest { pub fn db_connect_sqlite( path: String, id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.connect(ConnectionConfig::Sqlite { path, id }) } @@ -73,7 +73,7 @@ pub fn db_connect_postgres( user: String, password: Option, id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.connect(ConnectionConfig::Postgres { host, @@ -93,7 +93,7 @@ pub fn db_connect_mysql( user: String, password: Option, id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.connect(ConnectionConfig::Mysql { host, @@ -113,7 +113,7 @@ pub fn db_connect_redis( username: Option, db: Option, id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.connect(ConnectionConfig::Redis { host, @@ -134,7 +134,7 @@ pub fn db_connect_mongo( password: Option, auth_source: Option, id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.connect(ConnectionConfig::Mongo { host, @@ -150,7 +150,7 @@ pub fn db_connect_mongo( #[tauri::command] pub fn mongo_ping( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_mongo(&id, |s| s.ping()) } @@ -158,7 +158,7 @@ pub fn mongo_ping( #[tauri::command] pub fn mongo_list_databases( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { registry.with_mongo(&id, |s| s.list_databases()) } @@ -167,7 +167,7 @@ pub fn mongo_list_databases( pub fn mongo_list_collections( id: ConnectionId, database: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { registry.with_mongo(&id, |s| s.list_collections(&database)) } @@ -179,7 +179,7 @@ pub fn mongo_find( collection: String, filter_json: Option, limit: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_mongo(&id, |s| { s.find( @@ -194,7 +194,7 @@ pub fn mongo_find( #[tauri::command] pub fn redis_ping( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_redis(&id, |s| s.ping()) } @@ -205,7 +205,7 @@ pub fn redis_scan( cursor: Option, pattern: Option, count: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_redis(&id, |s| { s.scan( @@ -220,7 +220,7 @@ pub fn redis_scan( pub fn redis_get( id: ConnectionId, key: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { registry.with_redis(&id, |s| s.get(&key)) } @@ -230,7 +230,7 @@ pub fn redis_set( id: ConnectionId, key: String, value: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result<(), ConnectionError> { registry.with_redis(&id, |s| s.set(&key, &value)) } @@ -239,7 +239,7 @@ pub fn redis_set( pub fn redis_key_metas( id: ConnectionId, keys: Vec, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { registry.with_redis(&id, |s| s.types_and_ttls(&keys)) } @@ -248,7 +248,7 @@ pub fn redis_key_metas( pub fn redis_read_key( id: ConnectionId, key: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_redis(&id, |s| s.read_key(&key)) } @@ -296,7 +296,7 @@ pub fn profiles_connect_sqlite( folder_id: Option, id: Option, store: State<'_, ProfileStore>, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { let display_name = { let t = name.trim(); @@ -350,7 +350,7 @@ pub fn profiles_connect_postgres( request: ConnectPostgresRequest, store: State<'_, ProfileStore>, secrets: State<'_, SharedSecretStore>, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { let ConnectPostgresRequest { name, @@ -448,7 +448,7 @@ pub fn profiles_connect_mysql( request: ConnectMysqlRequest, store: State<'_, ProfileStore>, secrets: State<'_, SharedSecretStore>, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { let ConnectMysqlRequest { name, @@ -545,7 +545,7 @@ pub fn profiles_connect_redis( request: ConnectRedisRequest, store: State<'_, ProfileStore>, secrets: State<'_, SharedSecretStore>, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { let ConnectRedisRequest { name, @@ -649,7 +649,7 @@ pub fn profiles_connect_mongo( request: ConnectMongoRequest, store: State<'_, ProfileStore>, secrets: State<'_, SharedSecretStore>, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { let ConnectMongoRequest { name, @@ -764,13 +764,13 @@ pub fn profiles_connect_mongo( #[tauri::command] pub fn db_disconnect( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result<(), ConnectionError> { registry.disconnect(&id) } #[tauri::command] -pub fn db_is_connected(id: ConnectionId, registry: State<'_, ConnectionRegistry>) -> bool { +pub fn db_is_connected(id: ConnectionId, registry: State<'_, std::sync::Arc>) -> bool { registry.is_connected(&id) } @@ -779,7 +779,7 @@ pub fn db_is_connected(id: ConnectionId, registry: State<'_, ConnectionRegistry> pub fn db_list_children( id: ConnectionId, parent_id: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { registry.list_children(&id, parent_id.as_deref()) } @@ -789,7 +789,7 @@ pub fn db_list_children( pub fn db_describe_object( id: ConnectionId, object_id: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.describe_object(&id, &object_id) } @@ -799,7 +799,7 @@ pub fn db_describe_object( pub fn db_postgres_object_detail( id: ConnectionId, object_id: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.postgres_object_detail(&id, &object_id) } @@ -808,7 +808,7 @@ pub fn db_postgres_object_detail( #[tauri::command] pub fn db_list_schemas( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { Ok(registry .list_children(&id, None)? @@ -821,7 +821,7 @@ pub fn db_list_schemas( #[tauri::command] pub fn db_list_tables( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result, ConnectionError> { let main = registry .list_children(&id, None)? @@ -851,7 +851,7 @@ pub fn db_list_tables( pub fn db_list_columns( id: ConnectionId, table: String, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_sqlite(&id, |s| s.list_columns(&table)) } @@ -860,7 +860,7 @@ pub fn db_list_columns( #[tauri::command] pub fn db_sqlite_overview( id: ConnectionId, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.with_sqlite(&id, |s| s.database_overview()) } @@ -872,7 +872,7 @@ pub fn db_erd_schema( schema: Option, focus: Option, depth: Option, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { registry.erd_schema( &id, @@ -895,7 +895,7 @@ pub fn db_execute_query( limit: Option, confirmed: Option, on_event: Channel, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result<(), ConnectionError> { let limit = limit.map(|n| n as usize); let confirmed = confirmed.unwrap_or(false); @@ -910,7 +910,7 @@ pub fn db_execute_query( #[tauri::command] pub fn db_apply_staging( request: StagingApplyRequest, - registry: State<'_, ConnectionRegistry>, + registry: State<'_, std::sync::Arc>, ) -> Result { apply_staging_request(®istry, request) } diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index 217e33be..adc925ce 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -414,6 +414,15 @@ impl ConnectionRegistry { } } + /// Live sessions currently open in the registry (id + driver). + pub fn list_sessions(&self) -> ConnectionResult> { + let guard = self.lock()?; + Ok(guard + .iter() + .map(|(id, session)| (id.clone(), session.driver())) + .collect()) + } + pub fn list_children( &self, id: &ConnectionId, diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index bd74bdd7..b40cb022 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -83,13 +83,14 @@ fn open_main_window(app: &tauri::App) -> tauri::Result<()> { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { + let registry = std::sync::Arc::new(ConnectionRegistry::new()); tauri::Builder::default() .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) - .manage(ConnectionRegistry::new()) + .manage(std::sync::Arc::clone(®istry)) .manage(KeyringSecretStore::shared()) .manage(SshTunnelRegistry::new()) - .manage(McpController::new()) + .manage(McpController::new(registry)) .setup(|app| { use tauri::Manager; let store = ProfileStore::open_default().map_err(|e| { diff --git a/apps/tauri/src-tauri/src/mcp/host.rs b/apps/tauri/src-tauri/src/mcp/host.rs index 04dd31ef..d8d79494 100644 --- a/apps/tauri/src-tauri/src/mcp/host.rs +++ b/apps/tauri/src-tauri/src/mcp/host.rs @@ -2,6 +2,7 @@ use super::endpoint::McpEndpoint; use super::server::QueryaMcpServer; +use crate::connection::ConnectionRegistry; use rmcp::ServiceExt; use serde::Serialize; use std::path::PathBuf; @@ -52,14 +53,17 @@ struct RunningHost { } /// Starts / stops the in-process MCP loopback server. -#[derive(Default)] pub struct McpController { + registry: Arc, inner: Mutex>, } impl McpController { - pub fn new() -> Self { - Self::default() + pub fn new(registry: Arc) -> Self { + Self { + registry, + inner: Mutex::new(None), + } } pub fn status(&self) -> Result { @@ -92,7 +96,7 @@ impl McpController { crate::connection::runtime::block_on(self.stop_async()) } - async fn start_async( + pub(crate) async fn start_async( &self, endpoint_path: Option, ) -> Result { @@ -131,6 +135,7 @@ impl McpController { let stop_flag = Arc::clone(&stop); let sessions = Arc::clone(&session_count); let accept_token = token.clone(); + let registry = Arc::clone(&self.registry); let accept_task = tokio::spawn(async move { loop { @@ -144,9 +149,16 @@ impl McpController { let token = accept_token.clone(); let sessions = Arc::clone(&sessions); let stop_flag = Arc::clone(&stop_flag); + let registry = Arc::clone(®istry); tokio::spawn(async move { - if let Err(e) = - handle_connection(socket, token, sessions, stop_flag).await + if let Err(e) = handle_connection( + socket, + token, + sessions, + stop_flag, + registry, + ) + .await { eprintln!("mcp session error: {e}"); } @@ -173,7 +185,7 @@ impl McpController { self.status() } - async fn stop_async(&self) -> Result { + pub(crate) async fn stop_async(&self) -> Result { let running = { let mut guard = self .inner @@ -195,6 +207,7 @@ async fn handle_connection( expected_token: String, session_count: Arc, stop: Arc, + registry: Arc, ) -> Result<(), McpError> { if stop.load(Ordering::SeqCst) { return Ok(()); @@ -219,7 +232,7 @@ async fn handle_connection( session_count.fetch_add(1, Ordering::SeqCst); let _guard = SessionGuard(session_count); - let server = QueryaMcpServer::new(); + let server = QueryaMcpServer::new(registry); let running = server .serve(socket) .await @@ -283,7 +296,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); crate::connection::runtime::block_on(async { - let ctrl = McpController::new(); + let ctrl = McpController::new(Arc::new(ConnectionRegistry::new())); let status = ctrl .start_async(Some(ep_path.clone())) .await @@ -368,7 +381,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); crate::connection::runtime::block_on(async { - let ctrl = McpController::new(); + let ctrl = McpController::new(Arc::new(ConnectionRegistry::new())); let status = ctrl.start_async(Some(ep_path.clone())).await.unwrap(); let port = status.port.unwrap(); let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); diff --git a/apps/tauri/src-tauri/src/mcp/server.rs b/apps/tauri/src-tauri/src/mcp/server.rs index 5a0e3828..37b7ba33 100644 --- a/apps/tauri/src-tauri/src/mcp/server.rs +++ b/apps/tauri/src-tauri/src/mcp/server.rs @@ -1,17 +1,154 @@ -//! Minimal in-process MCP server (initialize / ping). Tools land in #1901. +//! MCP tools: `list_connections` and `run_query` over the live ConnectionManager. +use crate::connection::{ + ConnectionId, ConnectionManager, ConnectionRegistry, DriverKind, QueryEvent, +}; +use rmcp::handler::server::wrapper::Parameters; use rmcp::handler::server::ServerHandler; -use rmcp::model::{Implementation, ServerCapabilities, ServerConfig}; +use rmcp::model::{ + CallToolResult, ContentBlock, Implementation, ServerCapabilities, ServerConfig, +}; +use rmcp::{schemars, tool, tool_handler, tool_router}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::sync::Arc; -#[derive(Clone, Default)] -pub struct QueryaMcpServer; +const MCP_MAX_ROWS: usize = 1000; + +#[derive(Clone)] +pub struct QueryaMcpServer { + registry: Arc, + tool_router: rmcp::handler::server::router::tool::ToolRouter, +} impl QueryaMcpServer { - pub fn new() -> Self { - Self + pub fn new(registry: Arc) -> Self { + Self { + registry, + tool_router: Self::tool_router(), + } } } +#[derive(Debug, Deserialize, schemars::JsonSchema)] +struct RunQueryArgs { + /// Connection id from `list_connections`. + connection_id: String, + /// Single read-only SQL statement. + sql: String, +} + +#[derive(Debug, Serialize)] +struct McpConnectionInfo { + id: String, + #[serde(rename = "type")] + driver: String, + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + database: Option, +} + +#[derive(Debug, Serialize)] +struct McpQueryResult { + columns: Vec, + rows: Vec>, + row_count: u64, + truncated: bool, +} + +#[tool_router] +impl QueryaMcpServer { + #[tool( + description = "List live SQL connections currently open in Querya Desktop (id, type, name)." + )] + fn list_connections(&self) -> Result { + let sessions = self + .registry + .list_sessions() + .map_err(|e| e.to_string())?; + let mut out = Vec::new(); + for (id, driver) in sessions { + // Redis/Mongo are not exposed via SQL MCP tools yet. + if matches!(driver, DriverKind::Redis | DriverKind::Mongo) { + continue; + } + let (name, database) = connection_label(&self.registry, &id, driver); + out.push(McpConnectionInfo { + id: id.as_str().to_owned(), + driver: driver.as_str().to_owned(), + name, + database, + }); + } + ok_json(&out) + } + + #[tool( + description = "Run a single read-only SQL statement on a live connection. Only SELECT / WITH / PRAGMA (schema) / EXPLAIN (no ANALYZE) / SHOW / DESCRIBE / VALUES." + )] + fn run_query( + &self, + Parameters(args): Parameters, + ) -> Result { + let id = ConnectionId::from(args.connection_id.trim()); + if !self.registry.is_connected(&id) { + return Err(format!("connection not found or not connected: {id}")); + } + let driver = self + .registry + .driver_of(&id) + .ok_or_else(|| format!("connection not found: {id}"))?; + if matches!(driver, DriverKind::Redis | DriverKind::Mongo) { + return Err(format!( + "run_query does not support {} connections", + driver.as_str() + )); + } + + let mut columns = Vec::new(); + let mut rows = Vec::new(); + let mut truncated = false; + let mut row_count = 0u64; + let mut error: Option = None; + + self.registry + .execute_query(&id, &args.sql, Some(MCP_MAX_ROWS), false, |ev| { + match ev { + QueryEvent::Columns { names } => columns = names, + QueryEvent::Rows { + rows: chunk, + offset: _, + } => { + rows.extend(chunk); + } + QueryEvent::Done { + row_count: n, + truncated: t, + .. + } => { + row_count = n; + truncated = t; + } + QueryEvent::Error { message } => error = Some(message), + } + Ok(()) + }) + .map_err(|e| e.to_string())?; + + if let Some(message) = error { + return Err(message); + } + + ok_json(&McpQueryResult { + columns, + rows, + row_count, + truncated, + }) + } +} + +#[tool_handler(router = self.tool_router)] impl ServerHandler for QueryaMcpServer { fn get_info(&self) -> ServerConfig { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) @@ -20,7 +157,164 @@ impl ServerHandler for QueryaMcpServer { env!("CARGO_PKG_VERSION"), )) .with_instructions( - "Querya Desktop MCP skeleton. Connection/query tools arrive in a follow-up.", + "Start with list_connections, then run_query for read-only SQL on a live connection.", + ) + } +} + +fn connection_label( + registry: &ConnectionRegistry, + id: &ConnectionId, + driver: DriverKind, +) -> (String, Option) { + match driver { + DriverKind::Sqlite => registry + .with_sqlite(id, |s| Ok((s.path().to_owned(), Some(s.path().to_owned())))) + .unwrap_or_else(|_| (id.as_str().to_owned(), None)), + DriverKind::Postgres => registry + .with_postgres(id, |s| { + Ok(( + format!("{}:{}/{}", s.host(), s.port(), s.database()), + Some(s.database().to_owned()), + )) + }) + .unwrap_or_else(|_| (id.as_str().to_owned(), None)), + DriverKind::Mysql => registry + .with_mysql(id, |s| { + Ok(( + format!("{}:{}/{}", s.host(), s.port(), s.database()), + Some(s.database().to_owned()), + )) + }) + .unwrap_or_else(|_| (id.as_str().to_owned(), None)), + DriverKind::Redis | DriverKind::Mongo => (id.as_str().to_owned(), None), + } +} + +fn ok_json(value: &T) -> Result { + let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; + Ok(CallToolResult::success(vec![ContentBlock::text(text)])) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::connection::ConnectionConfig; + use crate::mcp::endpoint::McpEndpoint; + use crate::mcp::host::McpController; + use std::time::Duration; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + use tokio::net::TcpStream; + + #[test] + fn list_connections_and_run_query_on_sqlite() { + if std::env::var_os("QUERYA_SKIP_MCP").is_some() { + return; + } + + let dir = std::env::temp_dir().join(format!( + "querya-mcp-tools-{}-{}", + 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 items (id INTEGER PRIMARY KEY, name TEXT); + INSERT INTO items (name) VALUES ('alpha'), ('beta');", ) + .unwrap(); + } + + let registry = Arc::new(ConnectionRegistry::new()); + let conn_id = registry + .connect(ConnectionConfig::Sqlite { + path: db_path.to_string_lossy().into_owned(), + id: Some("fixture-sqlite".into()), + }) + .unwrap(); + assert_eq!(conn_id.as_str(), "fixture-sqlite"); + + crate::connection::runtime::block_on(async { + let ctrl = McpController::new(Arc::clone(®istry)); + let status = ctrl + .start_async(Some(ep_path.clone())) + .await + .expect("start"); + let port = status.port.unwrap(); + let endpoint = McpEndpoint::read(&ep_path).unwrap().unwrap(); + + let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + stream + .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":"querya-test","version":"0.0.1"}}}"#; + stream + .write_all(format!("{init}\n").as_bytes()) + .await + .unwrap(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + reader + .get_mut() + .write_all(b"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n") + .await + .unwrap(); + + let list = r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_connections","arguments":{}}}"#; + reader + .get_mut() + .write_all(format!("{list}\n").as_bytes()) + .await + .unwrap(); + line.clear(); + tokio::time::timeout(Duration::from_secs(3), reader.read_line(&mut line)) + .await + .unwrap() + .unwrap(); + let list_v: serde_json::Value = serde_json::from_str(line.trim()).unwrap(); + let text = list_v["result"]["content"][0]["text"].as_str().unwrap(); + assert!( + text.contains("fixture-sqlite"), + "list_connections missing fixture: {text}" + ); + + let query = json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "run_query", + "arguments": { + "connection_id": "fixture-sqlite", + "sql": "SELECT name FROM items ORDER BY id" + } + } + }); + reader + .get_mut() + .write_all(format!("{query}\n").as_bytes()) + .await + .unwrap(); + line.clear(); + tokio::time::timeout(Duration::from_secs(3), reader.read_line(&mut line)) + .await + .unwrap() + .unwrap(); + let qv: serde_json::Value = serde_json::from_str(line.trim()).unwrap(); + let qtext = qv["result"]["content"][0]["text"].as_str().unwrap(); + assert!(qtext.contains("alpha") && qtext.contains("beta"), "{qtext}"); + + let _ = ctrl.stop_async().await; + }); + + let _ = std::fs::remove_dir_all(&dir); } } From a6172219b51b33f87270a4cb3a2e5fca6896607e Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Mon, 16 Nov 2026 18:40:36 +0300 Subject: [PATCH 2/2] chore: remove accidental sed artifact file --- "apps/tauri/src-tauri/\nnew = State" | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 "apps/tauri/src-tauri/\nnew = State" diff --git "a/apps/tauri/src-tauri/\nnew = State" "b/apps/tauri/src-tauri/\nnew = State" deleted file mode 100644 index e69de29b..00000000