use anyhow::{Context, anyhow};
use serde_json::{Value, json};
use trusty_common::mcp::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(
base_url: &str,
tool: &str,
arguments: Value,
) -> anyhow::Result<Value> {
let envelope = call_memory_tool_at(base_url, "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 axum::routing::post;
use axum::{Json, Router};
use tokio::net::TcpListener;
use super::*;
#[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());
}
async fn spawn_mock(result: Value) -> String {
async fn handle(
axum::extract::State(result): axum::extract::State<Value>,
Json(_body): Json<Value>,
) -> Json<Value> {
Json(json!({"jsonrpc": "2.0", "id": 1, "result": result}))
}
let app = Router::new().route("/rpc", post(handle)).with_state(result);
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind mock");
let addr = listener.local_addr().expect("addr");
tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
format!("http://{addr}")
}
#[tokio::test]
async fn call_tool_wrapped_round_trips_against_mock() {
let inner = json!({"status": "stored", "drawer_id": "d1"}).to_string();
let base_url = spawn_mock(json!({"content": [{"type": "text", "text": inner}]})).await;
let result = call_tool_wrapped(&base_url, "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 base_url = spawn_mock(json!({"content": [{"type": "text", "text": "not json"}]})).await;
let err = call_tool_wrapped(&base_url, "memory_remember", json!({"palace": "p"}))
.await
.expect_err("malformed envelope must surface as Err");
assert!(err.to_string().contains("unexpected tools/call envelope"));
}
}