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::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//!
23//! [`tools_call_params`]: crate::memory_envelope::tools_call_params
24//! [`parse_tools_call_envelope`]: crate::memory_envelope::parse_tools_call_envelope
25//! [`call_tool_wrapped`]: crate::memory_envelope::call_tool_wrapped
26
27use anyhow::{Context, anyhow};
28use serde_json::{Value, json};
29use trusty_common::memory_rpc::call_memory_tool_at;
30
31/// Build the `params` object for a JSON-RPC `tools/call` request.
32///
33/// Why: keeps the MCP `{"name": <tool>, "arguments": <args>}` convention in
34/// exactly one place — a typo'd key here (e.g. `"args"`) would silently
35/// break every trusty-memory write, which is precisely the failure class
36/// #2424 is about.
37/// What: wraps `tool` and `arguments` into the MCP `tools/call` params
38/// shape trusty-memory's dispatcher expects.
39/// Test: `tests::tools_call_params_shape`.
40pub fn tools_call_params(tool: &str, arguments: Value) -> Value {
41 json!({
42 "name": tool,
43 "arguments": arguments,
44 })
45}
46
47/// Extract and parse the inner tool-result JSON from a `tools/call`
48/// response envelope.
49///
50/// Why: isolates the spike-verified unwrap (issue #2348: the daemon returns
51/// the tool result as a STRINGIFIED JSON blob inside
52/// `result.content[0].text`, not a nested `Value`) as one shared, testable
53/// step. Previously private to `tools::recall_session`
54/// (`parse_recall_envelope`); promoted here so `session::memory_sink` can
55/// reuse it (#2424).
56/// What: `envelope` is the raw `result` field of the JSON-RPC response
57/// (i.e. `call_memory_tool_at`'s `Ok` payload for a `tools/call` request).
58/// Returns `Some(parsed_body)` on a well-formed envelope, `None` otherwise
59/// (never panics on an unexpected shape).
60/// Test: `tests::parse_tools_call_envelope_unwraps_stringified_content`,
61/// `tests::parse_tools_call_envelope_none_on_missing_content`,
62/// `tests::parse_tools_call_envelope_none_on_malformed_inner_json`.
63pub fn parse_tools_call_envelope(envelope: &Value) -> Option<Value> {
64 let text = envelope
65 .get("content")
66 .and_then(|c| c.get(0))
67 .and_then(|c0| c0.get("text"))
68 .and_then(|t| t.as_str())?;
69 serde_json::from_str(text).ok()
70}
71
72/// Call one trusty-memory tool through the `tools/call` envelope and return
73/// its parsed inner result.
74///
75/// Why: the one-shot composition the turn recorder's dual-write needs —
76/// after #2424 every `memory_sink` write goes through this so the parsed
77/// result it inspects (e.g. `memory_remember`'s `"status":"skipped"`
78/// detection, #2363) has the SAME shape it had under the old direct
79/// dispatch, keeping the caller's success/skipped logic unchanged.
80/// What: builds the params via [`tools_call_params`], POSTs via
81/// `call_memory_tool_at(socket, "tools/call", ..)`, and unwraps the
82/// response via [`parse_tools_call_envelope`]. A JSON-RPC error (the shape
83/// trusty-memory returns when the inner tool itself fails — its dispatcher
84/// converts tool errors via `JsonRpcResponse::from_anyhow`) surfaces as
85/// `Err` from `call_memory_tool_at`; an unparseable envelope surfaces as
86/// its own `Err` so fail-open callers can warn on it distinctly.
87/// Test: `tests::call_tool_wrapped_round_trips_against_mock`,
88/// `tests::call_tool_wrapped_errs_on_malformed_envelope`; exercised
89/// end-to-end by `session::memory_sink::tests::*` and
90/// `tools::recall_session::tests::*`.
91pub async fn call_tool_wrapped(
92 socket: &std::path::Path,
93 tool: &str,
94 arguments: Value,
95) -> anyhow::Result<Value> {
96 let envelope = call_memory_tool_at(socket, "tools/call", tools_call_params(tool, arguments))
97 .await
98 .with_context(|| format!("tools/call '{tool}'"))?;
99 parse_tools_call_envelope(&envelope).ok_or_else(|| {
100 anyhow!("unexpected tools/call envelope shape from trusty-memory for '{tool}'")
101 })
102}
103
104// ── Tests ─────────────────────────────────────────────────────────────────────
105
106#[cfg(test)]
107mod tests {
108
109 use super::*;
110 use crate::uds_mock;
111
112 #[test]
113 fn tools_call_params_shape() {
114 let params = tools_call_params("memory_recall", json!({"palace": "p", "query": "q"}));
115 assert_eq!(params["name"], "memory_recall");
116 assert_eq!(params["arguments"]["palace"], "p");
117 assert_eq!(params["arguments"]["query"], "q");
118 }
119
120 #[test]
121 fn parse_tools_call_envelope_unwraps_stringified_content() {
122 let inner = json!({"palace": "p", "results": [{"content": "hello"}]}).to_string();
123 let envelope = json!({"content": [{"type": "text", "text": inner}]});
124 let body = parse_tools_call_envelope(&envelope).expect("should parse");
125 assert_eq!(body["palace"], "p");
126 assert_eq!(body["results"][0]["content"], "hello");
127 }
128
129 #[test]
130 fn parse_tools_call_envelope_none_on_missing_content() {
131 assert!(parse_tools_call_envelope(&json!({"not_content": []})).is_none());
132 }
133
134 #[test]
135 fn parse_tools_call_envelope_none_on_malformed_inner_json() {
136 let envelope = json!({"content": [{"type": "text", "text": "not valid json"}]});
137 assert!(parse_tools_call_envelope(&envelope).is_none());
138 }
139
140 #[tokio::test]
141 async fn call_tool_wrapped_round_trips_against_mock() {
142 let inner = json!({"status": "stored", "drawer_id": "d1"});
143 let daemon = uds_mock::spawn(uds_mock::always(uds_mock::tools_call_envelope(&inner))).await;
144 let result = call_tool_wrapped(daemon.socket(), "memory_remember", json!({"palace": "p"}))
145 .await
146 .expect("wrapped call should succeed");
147 assert_eq!(result["status"], "stored");
148 assert_eq!(result["drawer_id"], "d1");
149 }
150
151 #[tokio::test]
152 async fn call_tool_wrapped_errs_on_malformed_envelope() {
153 let daemon = uds_mock::spawn(uds_mock::always(
154 json!({"content": [{"type": "text", "text": "not json"}]}),
155 ))
156 .await;
157 let err = call_tool_wrapped(daemon.socket(), "memory_remember", json!({"palace": "p"}))
158 .await
159 .expect_err("malformed envelope must surface as Err");
160 assert!(err.to_string().contains("unexpected tools/call envelope"));
161 }
162}