use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use serde_json::Value;
use trusty_common::uds::ConnectRetry;
use crate::{Request, Response, error_codes};
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct UdsBridgeConfig {
pub socket: PathBuf,
pub daemon_label: String,
pub streaming_methods: Vec<String>,
pub request_timeout: Duration,
pub max_frame_bytes: u64,
pub bridge_version: String,
}
impl UdsBridgeConfig {
pub fn new(socket: impl Into<PathBuf>, daemon_label: impl Into<String>) -> Self {
Self {
socket: socket.into(),
daemon_label: daemon_label.into(),
streaming_methods: Vec::new(),
request_timeout: DEFAULT_REQUEST_TIMEOUT,
max_frame_bytes: trusty_common::uds::MAX_FRAME_BYTES,
bridge_version: env!("CARGO_PKG_VERSION").to_string(),
}
}
#[must_use]
pub fn with_bridge_version(mut self, version: impl Into<String>) -> Self {
self.bridge_version = version.into();
self
}
#[must_use]
pub fn with_streaming_methods<I, S>(mut self, methods: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.streaming_methods = methods.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
#[must_use]
pub fn with_max_frame_bytes(mut self, max_frame_bytes: u64) -> Self {
self.max_frame_bytes = max_frame_bytes;
self
}
}
type RequestRewriter = Arc<dyn Fn(Value) -> Value + Send + Sync>;
type SocketResolver = Arc<dyn Fn() -> anyhow::Result<PathBuf> + Send + Sync>;
type LocalHandler = Arc<dyn Fn(&Request) -> Option<Value> + Send + Sync>;
pub struct DaemonBridgeJsonRpc {
config: UdsBridgeConfig,
rewriter: Option<RequestRewriter>,
resolver: Option<SocketResolver>,
local: Option<LocalHandler>,
first_dial: AtomicBool,
}
impl std::fmt::Debug for DaemonBridgeJsonRpc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DaemonBridgeJsonRpc")
.field("config", &self.config)
.field("rewriter", &self.rewriter.is_some())
.field("resolver", &self.resolver.is_some())
.field("local", &self.local.is_some())
.finish()
}
}
impl DaemonBridgeJsonRpc {
pub fn new(config: UdsBridgeConfig) -> Self {
Self {
config,
rewriter: None,
resolver: None,
local: None,
first_dial: AtomicBool::new(true),
}
}
#[must_use]
pub fn with_socket_resolver<F>(mut self, resolve: F) -> Self
where
F: Fn() -> anyhow::Result<PathBuf> + Send + Sync + 'static,
{
self.resolver = Some(Arc::new(resolve));
self
}
#[must_use]
pub fn with_local_handler<F>(mut self, answer_locally: F) -> Self
where
F: Fn(&Request) -> Option<Value> + Send + Sync + 'static,
{
self.local = Some(Arc::new(answer_locally));
self
}
#[must_use]
pub fn with_request_rewriter<F>(mut self, rewrite: F) -> Self
where
F: Fn(Value) -> Value + Send + Sync + 'static,
{
self.rewriter = Some(Arc::new(rewrite));
self
}
pub fn socket(&self) -> &Path {
&self.config.socket
}
fn resolve_socket(&self) -> Result<PathBuf, String> {
match &self.resolver {
Some(resolve) => resolve().map_err(|e| format!("{e:#}")),
None => Ok(self.config.socket.clone()),
}
}
pub async fn answer(&self, req: Request) -> Response {
if is_notification(&req) {
return Response::suppressed();
}
let id = req.id.clone();
if let Some(answer_locally) = &self.local
&& let Some(result) = answer_locally(&req)
{
return Response::ok(id, result);
}
let envelope = normalise_jsonrpc(request_to_value(&req));
let socket = match self.resolve_socket() {
Ok(socket) => socket,
Err(cause) => {
eprintln!("daemon bridge: socket resolution failed: {cause}");
return Response::err(
id,
error_codes::INTERNAL_ERROR,
format!(
"the {} socket path could not be resolved (bridge {}): {cause}",
self.config.daemon_label, self.config.bridge_version
),
);
}
};
if let Some(method) = effective_method(&envelope)
&& self.config.streaming_methods.iter().any(|m| m == method)
{
return Response::err(
id,
error_codes::INVALID_REQUEST,
format!(
"{method} answers as a stream, which MCP stdio cannot carry \
(one response per request). Dial {} directly with a framed \
streaming client to read it.",
socket.display()
),
);
}
let envelope = match &self.rewriter {
Some(rewrite) => normalise_jsonrpc(rewrite(envelope)),
None => envelope,
};
match self.forward(&socket, &envelope).await {
Ok(reply) => self.map_reply(&socket, id, reply),
Err(cause) => {
eprintln!("daemon bridge: transport error: {cause}");
Response::err(
id,
error_codes::INTERNAL_ERROR,
format!(
"the {} daemon at {} could not be reached (bridge {}): \
{cause}. The next request is dialled fresh, so this \
recovers on its own once the daemon is back.",
self.config.daemon_label,
socket.display(),
self.config.bridge_version
),
)
}
}
}
async fn forward(
&self,
socket: &Path,
envelope: &Value,
) -> Result<Value, trusty_common::uds::UdsRpcError> {
trusty_common::uds::send_framed_request_retrying(
socket,
envelope,
self.config.request_timeout,
self.config.max_frame_bytes,
self.next_retry_policy(),
)
.await
}
fn next_retry_policy(&self) -> ConnectRetry {
if self.first_dial.swap(false, Ordering::Relaxed) {
ConnectRetry::startup()
} else {
ConnectRetry::per_request()
}
}
fn map_reply(&self, socket: &Path, request_id: Option<Value>, reply: Value) -> Response {
let id = reply
.get("id")
.cloned()
.filter(|v| !v.is_null())
.or(request_id);
if let Some(result) = reply.get("result").cloned() {
return Response::ok(id, result);
}
if let Some(error) = reply.get("error") {
let code = error
.get("code")
.and_then(Value::as_i64)
.map(|c| c as i32)
.unwrap_or(error_codes::INTERNAL_ERROR);
let message = error
.get("message")
.and_then(Value::as_str)
.unwrap_or("unknown daemon error");
return Response::err(id, code, message);
}
Response::err(
id,
error_codes::INTERNAL_ERROR,
format!(
"the {} daemon at {} replied with something that is not a JSON-RPC \
response (no result and no error): {reply}",
self.config.daemon_label,
socket.display()
),
)
}
pub async fn run_stdio(self) -> anyhow::Result<()> {
let bridge = Arc::new(self);
crate::run_stdio_loop(move |req| {
let bridge = Arc::clone(&bridge);
async move { bridge.answer(req).await }
})
.await
}
}
pub async fn run_stdio_bridge(config: UdsBridgeConfig) -> anyhow::Result<()> {
DaemonBridgeJsonRpc::new(config).run_stdio().await
}
fn is_notification(req: &Request) -> bool {
req.id.is_none() || req.method.starts_with("notifications/")
}
fn request_to_value(req: &Request) -> Value {
serde_json::to_value(req).unwrap_or_else(|_| serde_json::json!({}))
}
fn normalise_jsonrpc(mut envelope: Value) -> Value {
if let Some(obj) = envelope.as_object_mut() {
obj.insert("jsonrpc".to_string(), Value::String("2.0".to_string()));
}
envelope
}
fn effective_method(envelope: &Value) -> Option<&str> {
let method = envelope.get("method")?.as_str()?;
if method == "tools/call" {
return envelope
.get("params")
.and_then(|p| p.get("name"))
.and_then(Value::as_str)
.or(Some(method));
}
Some(method)
}
#[cfg(test)]
#[path = "daemon_bridge_json_rpc_tests.rs"]
mod tests;