trusty_code/memory_envelope.rs
1//! Shared trusty-memory `tools/call` envelope helpers (#2424).
2//!
3//! Why: trusty-memory's JSON-RPC surface direct-dispatches only the methods
4//! in its `TOOL_METHODS` allowlist (`crates/trusty-memory/src/transport/
5//! rpc.rs`); everything else — notably every `chat_*` tool — is reachable
6//! ONLY via the MCP-style `tools/call` envelope. The #2343 soak
7//! (2026-07-11) found `memory_sink::write_turn`'s direct-method dispatch of
8//! `chat_turn_append` failing `-32601 Method not found` on 100% of turns
9//! (#2424), while #2348's `recall_session` — which already used the
10//! `tools/call` envelope — worked. This module is the SINGLE shared
11//! implementation of that spike-verified envelope shape (build the
12//! `{"name", "arguments"}` params; unwrap the STRINGIFIED JSON blob the
13//! daemon returns inside `result.content[0].text`) so the write side
14//! (`session::memory_sink`) and the read side (`tools::recall_session`) can
15//! never drift apart again.
16//! What: [`tools_call_params`] builds the request params;
17//! [`parse_tools_call_envelope`] unwraps a response envelope;
18//! [`call_tool_wrapped`] composes both around
19//! `trusty_common::mcp::memory_rpc::call_memory_tool_at` for callers that
20//! want a one-shot "call this tool, give me its parsed result" helper.
21//! Test: `memory_envelope::tests::*`.
22
23use anyhow::{Context, anyhow};
24use serde_json::{Value, json};
25use trusty_common::mcp::memory_rpc::call_memory_tool_at;
26
27/// Build the `params` object for a JSON-RPC `tools/call` request.
28///
29/// Why: keeps the MCP `{"name": <tool>, "arguments": <args>}` convention in
30/// exactly one place — a typo'd key here (e.g. `"args"`) would silently
31/// break every trusty-memory write, which is precisely the failure class
32/// #2424 is about.
33/// What: wraps `tool` and `arguments` into the MCP `tools/call` params
34/// shape trusty-memory's dispatcher expects.
35/// Test: `tests::tools_call_params_shape`.
36pub fn tools_call_params(tool: &str, arguments: Value) -> Value {
37 json!({
38 "name": tool,
39 "arguments": arguments,
40 })
41}
42
43/// Extract and parse the inner tool-result JSON from a `tools/call`
44/// response envelope.
45///
46/// Why: isolates the spike-verified unwrap (issue #2348: the daemon returns
47/// the tool result as a STRINGIFIED JSON blob inside
48/// `result.content[0].text`, not a nested `Value`) as one shared, testable
49/// step. Previously private to `tools::recall_session`
50/// (`parse_recall_envelope`); promoted here so `session::memory_sink` can
51/// reuse it (#2424).
52/// What: `envelope` is the raw `result` field of the JSON-RPC response
53/// (i.e. `call_memory_tool_at`'s `Ok` payload for a `tools/call` request).
54/// Returns `Some(parsed_body)` on a well-formed envelope, `None` otherwise
55/// (never panics on an unexpected shape).
56/// Test: `tests::parse_tools_call_envelope_unwraps_stringified_content`,
57/// `tests::parse_tools_call_envelope_none_on_missing_content`,
58/// `tests::parse_tools_call_envelope_none_on_malformed_inner_json`.
59pub fn parse_tools_call_envelope(envelope: &Value) -> Option<Value> {
60 let text = envelope
61 .get("content")
62 .and_then(|c| c.get(0))
63 .and_then(|c0| c0.get("text"))
64 .and_then(|t| t.as_str())?;
65 serde_json::from_str(text).ok()
66}
67
68/// Call one trusty-memory tool through the `tools/call` envelope and return
69/// its parsed inner result.
70///
71/// Why: the one-shot composition the turn recorder's dual-write needs —
72/// after #2424 every `memory_sink` write goes through this so the parsed
73/// result it inspects (e.g. `memory_remember`'s `"status":"skipped"`
74/// detection, #2363) has the SAME shape it had under the old direct
75/// dispatch, keeping the caller's success/skipped logic unchanged.
76/// What: builds the params via [`tools_call_params`], POSTs via
77/// `call_memory_tool_at(base_url, "tools/call", ..)`, and unwraps the
78/// response via [`parse_tools_call_envelope`]. A JSON-RPC error (the shape
79/// trusty-memory returns when the inner tool itself fails — its dispatcher
80/// converts tool errors via `JsonRpcResponse::from_anyhow`) surfaces as
81/// `Err` from `call_memory_tool_at`; an unparseable envelope surfaces as
82/// its own `Err` so fail-open callers can warn on it distinctly.
83/// Test: `tests::call_tool_wrapped_round_trips_against_mock`,
84/// `tests::call_tool_wrapped_errs_on_malformed_envelope`; exercised
85/// end-to-end by `session::memory_sink::tests::*` and
86/// `tools::recall_session::tests::*`.
87pub async fn call_tool_wrapped(
88 base_url: &str,
89 tool: &str,
90 arguments: Value,
91) -> anyhow::Result<Value> {
92 let envelope = call_memory_tool_at(base_url, "tools/call", tools_call_params(tool, arguments))
93 .await
94 .with_context(|| format!("tools/call '{tool}'"))?;
95 parse_tools_call_envelope(&envelope).ok_or_else(|| {
96 anyhow!("unexpected tools/call envelope shape from trusty-memory for '{tool}'")
97 })
98}
99
100// ── Tests ─────────────────────────────────────────────────────────────────────
101
102#[cfg(test)]
103mod tests {
104 use axum::routing::post;
105 use axum::{Json, Router};
106 use tokio::net::TcpListener;
107
108 use super::*;
109
110 #[test]
111 fn tools_call_params_shape() {
112 let params = tools_call_params("memory_recall", json!({"palace": "p", "query": "q"}));
113 assert_eq!(params["name"], "memory_recall");
114 assert_eq!(params["arguments"]["palace"], "p");
115 assert_eq!(params["arguments"]["query"], "q");
116 }
117
118 #[test]
119 fn parse_tools_call_envelope_unwraps_stringified_content() {
120 let inner = json!({"palace": "p", "results": [{"content": "hello"}]}).to_string();
121 let envelope = json!({"content": [{"type": "text", "text": inner}]});
122 let body = parse_tools_call_envelope(&envelope).expect("should parse");
123 assert_eq!(body["palace"], "p");
124 assert_eq!(body["results"][0]["content"], "hello");
125 }
126
127 #[test]
128 fn parse_tools_call_envelope_none_on_missing_content() {
129 assert!(parse_tools_call_envelope(&json!({"not_content": []})).is_none());
130 }
131
132 #[test]
133 fn parse_tools_call_envelope_none_on_malformed_inner_json() {
134 let envelope = json!({"content": [{"type": "text", "text": "not valid json"}]});
135 assert!(parse_tools_call_envelope(&envelope).is_none());
136 }
137
138 /// Spin up a one-route mock `/rpc` server replying with `reply` wrapped
139 /// (or not) per the closure, and return its base URL.
140 async fn spawn_mock(result: Value) -> String {
141 async fn handle(
142 axum::extract::State(result): axum::extract::State<Value>,
143 Json(_body): Json<Value>,
144 ) -> Json<Value> {
145 Json(json!({"jsonrpc": "2.0", "id": 1, "result": result}))
146 }
147 let app = Router::new().route("/rpc", post(handle)).with_state(result);
148 let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind mock");
149 let addr = listener.local_addr().expect("addr");
150 tokio::spawn(async move {
151 let _ = axum::serve(listener, app).await;
152 });
153 format!("http://{addr}")
154 }
155
156 #[tokio::test]
157 async fn call_tool_wrapped_round_trips_against_mock() {
158 let inner = json!({"status": "stored", "drawer_id": "d1"}).to_string();
159 let base_url = spawn_mock(json!({"content": [{"type": "text", "text": inner}]})).await;
160 let result = call_tool_wrapped(&base_url, "memory_remember", json!({"palace": "p"}))
161 .await
162 .expect("wrapped call should succeed");
163 assert_eq!(result["status"], "stored");
164 assert_eq!(result["drawer_id"], "d1");
165 }
166
167 #[tokio::test]
168 async fn call_tool_wrapped_errs_on_malformed_envelope() {
169 let base_url = spawn_mock(json!({"content": [{"type": "text", "text": "not json"}]})).await;
170 let err = call_tool_wrapped(&base_url, "memory_remember", json!({"palace": "p"}))
171 .await
172 .expect_err("malformed envelope must surface as Err");
173 assert!(err.to_string().contains("unexpected tools/call envelope"));
174 }
175}