Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/tauri/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ crate-type = ["staticlib", "cdylib", "rlib"]
name = "querya-mcp"
path = "src/bin/querya_mcp.rs"

[[bin]]
name = "querya-ext-echo"
path = "src/bin/querya_ext_echo.rs"

[build-dependencies]
tauri-build = { version = "2", features = [] }

Expand Down
77 changes: 77 additions & 0 deletions apps/tauri/src-tauri/src/bin/querya_ext_echo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//! Minimal echo extension for host round-trip tests (NDJSON JSON-RPC 2.0 over stdio).
//!
//! Methods: `system.handshake`, `system.ping`, `system.shutdown`, `echo.echo`.

use serde_json::{json, Value};
use std::io::{self, BufRead, Write};

fn main() {
let stdin = io::stdin();
let mut stdout = io::stdout();

for line in stdin.lock().lines() {
let Ok(line) = line else {
break;
};
if line.trim().is_empty() {
continue;
}
let Ok(req) = serde_json::from_str::<Value>(&line) else {
continue;
};
let id = req.get("id").cloned().unwrap_or(Value::Null);
let method = req.get("method").and_then(Value::as_str).unwrap_or("");
let params = req.get("params").cloned();

let response = match method {
"system.handshake" => {
let extension_id = params
.as_ref()
.and_then(|p| p.get("pluginId"))
.and_then(Value::as_str)
.unwrap_or("querya.echo");
ok(
id,
json!({
"protocolVersion": 1,
"extensionId": extension_id,
}),
)
}
"system.ping" => ok(id, json!("pong")),
"echo.echo" => ok(id, params.unwrap_or(Value::Null)),
"system.shutdown" => {
let line = ok(id, json!({ "ok": true }));
let _ = writeln!(stdout, "{line}");
let _ = stdout.flush();
break;
}
other => err(id, -32601, format!("method not found: {other}")),
};

if writeln!(stdout, "{response}").is_err() {
break;
}
if stdout.flush().is_err() {
break;
}
}
}

fn ok(id: Value, result: Value) -> String {
json!({
"jsonrpc": "2.0",
"id": id,
"result": result,
})
.to_string()
}

fn err(id: Value, code: i32, message: String) -> String {
json!({
"jsonrpc": "2.0",
"id": id,
"error": { "code": code, "message": message },
})
.to_string()
}
52 changes: 52 additions & 0 deletions apps/tauri/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ pub fn db_connect_redis(
}

#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub fn db_connect_mongo(
host: String,
port: u16,
Expand Down Expand Up @@ -960,3 +961,54 @@ pub fn mcp_status(
) -> Result<crate::mcp::McpStatus, crate::mcp::McpError> {
mcp.status()
}

/// Spawn an extension process and run `system.handshake` (#1903).
#[tauri::command]
pub async fn ext_host_start(
host: State<'_, std::sync::Arc<crate::extensions::ExtensionHost>>,
session_id: String,
executable: String,
args: Option<Vec<String>>,
handshake_params: Option<serde_json::Value>,
) -> Result<crate::extensions::ExtensionSessionInfo, String> {
host.start(
session_id,
std::path::PathBuf::from(executable),
args.unwrap_or_default(),
handshake_params.unwrap_or(serde_json::json!({})),
)
.await
}

#[tauri::command]
pub async fn ext_host_call(
host: State<'_, std::sync::Arc<crate::extensions::ExtensionHost>>,
session_id: String,
method: String,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value, String> {
host.call(&session_id, &method, params).await
}

#[tauri::command]
pub async fn ext_host_ping(
host: State<'_, std::sync::Arc<crate::extensions::ExtensionHost>>,
session_id: String,
) -> Result<serde_json::Value, String> {
host.ping(&session_id).await
}

#[tauri::command]
pub async fn ext_host_stop(
host: State<'_, std::sync::Arc<crate::extensions::ExtensionHost>>,
session_id: String,
) -> Result<(), String> {
host.stop(&session_id).await
}

#[tauri::command]
pub async fn ext_host_list(
host: State<'_, std::sync::Arc<crate::extensions::ExtensionHost>>,
) -> Result<Vec<crate::extensions::ExtensionSessionInfo>, String> {
Ok(host.list().await)
}
6 changes: 1 addition & 5 deletions apps/tauri/src-tauri/src/connection/mongo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,7 @@ pub fn open_mongo(params: MongoConnectParams) -> ConnectionResult<MongoSession>

Ok(MongoSession {
id,
host: if host.contains("://") {
host.to_owned()
} else {
host.to_owned()
},
host: host.to_owned(),
port: params.port,
database,
client: Arc::new(Mutex::new(Some(client))),
Expand Down
167 changes: 167 additions & 0 deletions apps/tauri/src-tauri/src/extensions/host.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
//! Extension process host: spawn + handshake/ping/shutdown over NDJSON JSON-RPC.

use super::rpc::{JsonRpcStdioClient, RpcError};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::process::{Child, Command};
use tokio::sync::Mutex;

const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15);
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionSessionInfo {
pub session_id: String,
pub extension_id: String,
pub protocol_version: Value,
pub executable: String,
}

struct LiveSession {
info: ExtensionSessionInfo,
child: Child,
rpc: Arc<JsonRpcStdioClient>,
}

/// In-process registry of running extension sessions.
#[derive(Default)]
pub struct ExtensionHost {
sessions: Mutex<HashMap<String, LiveSession>>,
}

impl ExtensionHost {
pub fn new() -> Self {
Self::default()
}

/// Spawn `executable` with `args`, run `system.handshake`, return session info.
pub async fn start(
&self,
session_id: String,
executable: PathBuf,
args: Vec<String>,
handshake_params: Value,
) -> Result<ExtensionSessionInfo, String> {
{
let guard = self.sessions.lock().await;
if guard.contains_key(&session_id) {
return Err(format!("extension session already running: {session_id}"));
}
}

let mut child = Command::new(&executable)
.args(&args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| format!("spawn extension process: {e}"))?;

let stdin = child
.stdin
.take()
.ok_or_else(|| "extension stdin unavailable".to_string())?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "extension stdout unavailable".to_string())?;

let rpc = Arc::new(JsonRpcStdioClient::new(stdin, stdout));

let handshake = rpc
.send_request_timeout(
"system.handshake",
Some(handshake_params),
HANDSHAKE_TIMEOUT,
)
.await
.map_err(|e| format!("system.handshake failed: {e}"))?;

let extension_id = handshake
.get("extensionId")
.or_else(|| handshake.get("pluginId"))
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_owned();
let protocol_version = handshake
.get("protocolVersion")
.cloned()
.unwrap_or(json!(1));

let info = ExtensionSessionInfo {
session_id: session_id.clone(),
extension_id,
protocol_version,
executable: executable.display().to_string(),
};

let mut guard = self.sessions.lock().await;
guard.insert(
session_id,
LiveSession {
info: info.clone(),
child,
rpc,
},
);
Ok(info)
}

pub async fn call(
&self,
session_id: &str,
method: &str,
params: Option<Value>,
) -> Result<Value, String> {
let rpc = {
let guard = self.sessions.lock().await;
let session = guard
.get(session_id)
.ok_or_else(|| format!("unknown extension session: {session_id}"))?;
Arc::clone(&session.rpc)
};
rpc.send_request(method, params)
.await
.map_err(|e: RpcError| e.message)
}

pub async fn ping(&self, session_id: &str) -> Result<Value, String> {
self.call(session_id, "system.ping", None).await
}

pub async fn stop(&self, session_id: &str) -> Result<(), String> {
let mut session = {
let mut guard = self.sessions.lock().await;
guard
.remove(session_id)
.ok_or_else(|| format!("unknown extension session: {session_id}"))?
};

let _ = session
.rpc
.send_request_timeout("system.shutdown", None, SHUTDOWN_TIMEOUT)
.await;
session.rpc.close().await;

match tokio::time::timeout(SHUTDOWN_TIMEOUT, session.child.wait()).await {
Ok(Ok(_)) => Ok(()),
Ok(Err(e)) => Err(format!("wait for extension exit: {e}")),
Err(_) => {
let _ = session.child.kill().await;
Ok(())
}
}
}

pub async fn list(&self) -> Vec<ExtensionSessionInfo> {
let guard = self.sessions.lock().await;
guard.values().map(|s| s.info.clone()).collect()
}
}
6 changes: 6 additions & 0 deletions apps/tauri/src-tauri/src/extensions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//! Extension host: spawn child processes and speak Flutter-compatible NDJSON JSON-RPC.

pub mod host;
pub mod rpc;

pub use host::{ExtensionHost, ExtensionSessionInfo};
Loading
Loading