use std::process::ExitCode;
use anyhow::Context;
use trusty_mcp::{UdsBridgeConfig, run_stdio_bridge};
const EXIT_USAGE: u8 = 2;
const MIB: u64 = 1024 * 1024;
struct Service {
app: &'static str,
streaming_methods: &'static [&'static str],
max_frame_bytes: u64,
}
const SERVICES: &[Service] = &[
Service {
app: "trusty-memory",
streaming_methods: &["memory.chat", "memory.activity_stream"],
max_frame_bytes: 32 * MIB,
},
Service {
app: "trusty-search",
streaming_methods: &[
"search.status.stream",
"search.index.reindex.stream",
"search.index.file_events",
],
max_frame_bytes: 64 * MIB,
},
Service {
app: "trusty-analyze",
streaming_methods: &[],
max_frame_bytes: 32 * MIB,
},
];
fn short_name(app: &str) -> &str {
app.strip_prefix("trusty-").unwrap_or(app)
}
fn lookup(arg: &str) -> Option<&'static Service> {
SERVICES
.iter()
.find(|s| s.app == arg || short_name(s.app) == arg)
}
enum Parsed {
Help,
Serve(&'static Service),
Usage(String),
}
fn parse<'a>(args: impl IntoIterator<Item = &'a str>) -> Parsed {
let mut args = args.into_iter();
let Some(first) = args.next() else {
return Parsed::Usage("a service is required".to_string());
};
if first == "-h" || first == "--help" {
return Parsed::Help;
}
let Some(service) = lookup(first) else {
return Parsed::Usage(format!(
"unknown service {first:?} — expected one of {}",
service_names().join(", ")
));
};
if let Some(extra) = args.next() {
return Parsed::Usage(format!(
"unexpected argument {extra:?} — the only argument is the service"
));
}
Parsed::Serve(service)
}
fn service_names() -> Vec<&'static str> {
SERVICES.iter().map(|s| short_name(s.app)).collect()
}
fn usage() -> String {
let mut out = String::from(
"trusty-mcp — stdio MCP bridge to a trusty daemon's Unix socket\n\
\n\
Usage:\n \
trusty-mcp <service>\n\
\n\
Services (either spelling):\n",
);
for service in SERVICES {
out.push_str(&format!(
" {:<10} {}\n",
short_name(service.app),
service.app
));
}
out.push_str(
"\n\
Reads line-delimited JSON-RPC 2.0 on stdin and writes one response per\n\
request to stdout; every diagnostic goes to stderr. It does not start the\n\
daemon — a request that arrives with nothing listening is answered with a\n\
JSON-RPC error carrying the request's id.\n\
\n\
Exit: 0 when stdin reaches EOF, 2 on a usage error, 1 on an I/O failure.\n",
);
out
}
async fn serve(service: &Service) -> anyhow::Result<()> {
let socket = trusty_common::daemon_socket_path(service.app)
.with_context(|| format!("could not resolve the {} socket path", service.app))?;
eprintln!(
"trusty-mcp: bridging stdio to {} at {}",
service.app,
socket.display()
);
run_stdio_bridge(
UdsBridgeConfig::new(socket, service.app)
.with_streaming_methods(service.streaming_methods.iter().copied())
.with_max_frame_bytes(service.max_frame_bytes),
)
.await
}
async fn run() -> anyhow::Result<ExitCode> {
let args: Vec<String> = std::env::args_os()
.skip(1)
.map(|a| a.to_string_lossy().into_owned())
.collect();
match parse(args.iter().map(String::as_str)) {
Parsed::Help => {
eprint!("{}", usage());
Ok(ExitCode::SUCCESS)
}
Parsed::Usage(problem) => {
eprintln!("trusty-mcp: {problem}");
eprint!("{}", usage());
Ok(ExitCode::from(EXIT_USAGE))
}
Parsed::Serve(service) => {
serve(service).await?;
Ok(ExitCode::SUCCESS)
}
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> ExitCode {
match run().await {
Ok(code) => code,
Err(cause) => {
eprintln!("trusty-mcp: {cause:#}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
fn sibling_source(rel: &str) -> Option<String> {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join(rel);
std::fs::read_to_string(path).ok()
}
fn string_array_const(src: &str, name: &str) -> Vec<String> {
let decl = format!("pub const {name}: &[&str] = &[");
let start = src
.find(&decl)
.unwrap_or_else(|| panic!("{name} is declared"))
+ decl.len();
let end = start + src[start..].find("];").expect("the array is terminated");
src[start..end]
.split('"')
.skip(1)
.step_by(2)
.map(str::to_string)
.collect()
}
fn str_const_literals(src: &str) -> Vec<String> {
src.lines()
.filter_map(|line| line.trim().strip_prefix("pub const "))
.filter_map(|rest| rest.split_once(": &str = "))
.filter_map(|(_, value)| value.trim().strip_prefix('"'))
.filter_map(|value| value.split('"').next())
.map(str::to_string)
.collect()
}
fn u64_const(src: &str, name: &str) -> u64 {
let decl = format!("pub const {name}: u64 = ");
let start = src
.find(&decl)
.unwrap_or_else(|| panic!("{name} is declared"))
+ decl.len();
let end = start + src[start..].find(';').expect("the declaration ends");
src[start..end]
.split('*')
.map(|part| {
part.trim()
.replace('_', "")
.parse::<u64>()
.expect("a product of integer literals")
})
.product()
}
fn service(app: &str) -> &'static Service {
lookup(app).expect("the service is in the table")
}
#[test]
fn the_table_matches_each_daemons_own_constants() {
if let Some(src) = sibling_source("trusty-memory/src/transport/uds.rs") {
assert_eq!(
string_array_const(&src, "STREAM_METHODS"),
service("memory").streaming_methods,
"trusty-memory's streaming methods drifted from this table"
);
assert_eq!(
u64_const(&src, "MAX_FRAME_BYTES"),
service("memory").max_frame_bytes,
"trusty-memory's frame budget drifted from this table"
);
}
if let Some(src) = sibling_source("trusty-search/src/service/rpc/streams.rs") {
assert_eq!(
str_const_literals(&src),
service("search").streaming_methods,
"trusty-search's streaming methods drifted from this table"
);
}
if let Some(src) = sibling_source("trusty-search/src/service/socket.rs") {
assert_eq!(
u64_const(&src, "MAX_FRAME_BYTES"),
service("search").max_frame_bytes,
"trusty-search's frame budget drifted from this table"
);
}
if let Some(src) = sibling_source("trusty-analyze/src/service/rpc.rs") {
assert_eq!(
u64_const(&src, "MAX_FRAME_BYTES"),
service("analyze").max_frame_bytes,
"trusty-analyze's frame budget drifted from this table"
);
}
}
#[test]
fn every_service_is_reachable_by_both_of_its_names() {
for row in SERVICES {
let long = lookup(row.app).expect("the app name resolves");
let short = lookup(short_name(row.app)).expect("the short name resolves");
assert_eq!(long.app, row.app);
assert_eq!(short.app, row.app);
}
}
#[test]
fn an_unknown_service_resolves_to_nothing() {
for arg in [
"",
"trusty-",
"mem",
"trusty-mcp",
"trusty-review",
"MEMORY",
] {
assert!(lookup(arg).is_none(), "{arg:?} must not resolve");
}
}
#[test]
fn no_arguments_is_a_usage_error() {
let Parsed::Usage(problem) = parse(std::iter::empty()) else {
panic!("an empty command line is a usage error");
};
assert!(problem.contains("service"), "{problem}");
}
#[test]
fn an_unknown_service_is_a_usage_error() {
let Parsed::Usage(problem) = parse(["review"]) else {
panic!("an unknown service is a usage error");
};
assert!(problem.contains("review"), "{problem}");
for name in service_names() {
assert!(problem.contains(name), "{problem} omits {name}");
}
}
#[test]
fn a_second_argument_is_a_usage_error() {
let Parsed::Usage(problem) = parse(["memory", "--socket=/tmp/x.sock"]) else {
panic!("an extra argument is a usage error");
};
assert!(problem.contains("--socket=/tmp/x.sock"), "{problem}");
}
#[test]
fn help_is_recognised() {
assert!(matches!(parse(["-h"]), Parsed::Help));
assert!(matches!(parse(["--help"]), Parsed::Help));
assert!(matches!(parse(["memory"]), Parsed::Serve(_)));
}
#[test]
fn usage_names_every_service() {
let text = usage();
for row in SERVICES {
assert!(text.contains(row.app), "usage omits {}", row.app);
assert!(
text.contains(short_name(row.app)),
"usage omits {}",
short_name(row.app)
);
}
assert!(text.contains("does not start the"), "{text}");
}
}