use anyhow::{Context, anyhow};
use serde_json::{Value, json};
use trusty_common::memory_rpc::call_memory_tool_at;
pub fn tools_call_params(tool: &str, arguments: Value) -> Value {
json!({
"name": tool,
"arguments": arguments,
})
}
pub fn parse_tools_call_envelope(envelope: &Value) -> Option<Value> {
let text = envelope
.get("content")
.and_then(|c| c.get(0))
.and_then(|c0| c0.get("text"))
.and_then(|t| t.as_str())?;
serde_json::from_str(text).ok()
}
pub async fn call_tool_wrapped(
socket: &std::path::Path,
tool: &str,
arguments: Value,
) -> anyhow::Result<Value> {
let envelope = call_memory_tool_at(socket, "tools/call", tools_call_params(tool, arguments))
.await
.with_context(|| format!("tools/call '{tool}'"))?;
parse_tools_call_envelope(&envelope).ok_or_else(|| {
anyhow!("unexpected tools/call envelope shape from trusty-memory for '{tool}'")
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::uds_mock;
#[test]
fn tools_call_params_shape() {
let params = tools_call_params("memory_recall", json!({"palace": "p", "query": "q"}));
assert_eq!(params["name"], "memory_recall");
assert_eq!(params["arguments"]["palace"], "p");
assert_eq!(params["arguments"]["query"], "q");
}
#[test]
fn parse_tools_call_envelope_unwraps_stringified_content() {
let inner = json!({"palace": "p", "results": [{"content": "hello"}]}).to_string();
let envelope = json!({"content": [{"type": "text", "text": inner}]});
let body = parse_tools_call_envelope(&envelope).expect("should parse");
assert_eq!(body["palace"], "p");
assert_eq!(body["results"][0]["content"], "hello");
}
#[test]
fn parse_tools_call_envelope_none_on_missing_content() {
assert!(parse_tools_call_envelope(&json!({"not_content": []})).is_none());
}
#[test]
fn parse_tools_call_envelope_none_on_malformed_inner_json() {
let envelope = json!({"content": [{"type": "text", "text": "not valid json"}]});
assert!(parse_tools_call_envelope(&envelope).is_none());
}
#[tokio::test]
async fn call_tool_wrapped_round_trips_against_mock() {
let inner = json!({"status": "stored", "drawer_id": "d1"});
let daemon = uds_mock::spawn(uds_mock::always(uds_mock::tools_call_envelope(&inner))).await;
let result = call_tool_wrapped(daemon.socket(), "memory_remember", json!({"palace": "p"}))
.await
.expect("wrapped call should succeed");
assert_eq!(result["status"], "stored");
assert_eq!(result["drawer_id"], "d1");
}
#[tokio::test]
async fn call_tool_wrapped_errs_on_malformed_envelope() {
let daemon = uds_mock::spawn(uds_mock::always(
json!({"content": [{"type": "text", "text": "not json"}]}),
))
.await;
let err = call_tool_wrapped(daemon.socket(), "memory_remember", json!({"palace": "p"}))
.await
.expect_err("malformed envelope must surface as Err");
assert!(err.to_string().contains("unexpected tools/call envelope"));
}
}