trusty_mcp/lib.rs
1//! Shared JSON-RPC 2.0 / MCP primitives for the trusty-* ecosystem.
2//!
3//! Why: trusty-memory and trusty-search both speak MCP over stdio (and HTTP/SSE).
4//! They had each grown their own `Request` / `Response` / `JsonRpcError` types
5//! and stdio loops — virtually identical, but drifting. Centralising avoids
6//! the bug-fix-in-one-not-the-other failure mode and gives future MCP servers
7//! a one-import surface to ship against.
8//!
9//! What: JSON-RPC 2.0 request/response envelopes, standard error codes, a
10//! helper to build the `initialize` payload, and an async stdio dispatch
11//! loop that accepts any `Fn(Request) -> Future<Output=Response>`.
12//!
13//! Test: `cargo test -p trusty-mcp` covers Response construction + the stdio
14//! loop round-trip behaviour with an in-memory dispatcher.
15//!
16//! These primitives lived in `trusty_mcp` until ADR-0040 (#5803) moved
17//! them here. `memory_rpc` did not come with them: it reaches
18//! `trusty_common::daemon_addr` and `trusty_common::data_dir`, so it stays in
19//! `trusty-common` as `trusty_common::memory_rpc`.
20
21// docs.rs builds a release's documentation once, from the uploaded tarball,
22// so a broken intra-doc link is baked into that version forever and only a new
23// release can correct it. Deny keeps this crate at zero rather than letting the
24// ratchet in `scripts/check_rustdoc_links.sh` absorb a new one.
25#![deny(rustdoc::broken_intra_doc_links)]
26
27use serde::{Deserialize, Serialize};
28use serde_json::{Value, json};
29
30pub mod daemon_bridge;
31pub mod openrpc;
32pub mod service;
33pub mod single_flight;
34
35pub use daemon_bridge::{DaemonBridgeConfig, ensure_daemon_up};
36pub use service::ServiceDescriptor;
37pub use single_flight::{StartLock, ensure_daemon_up_single_flight};
38
39/// JSON-RPC 2.0 error codes.
40///
41/// Why: Both trusty-memory and trusty-search referenced these constants with
42/// slightly drifting numeric types — consolidating here keeps them aligned.
43/// What: `i32` to match the JSON-RPC 2.0 spec; serde_json serialises these
44/// transparently as JSON numbers.
45/// Test: `error_codes_are_spec_values` asserts the canonical numeric values.
46pub mod error_codes {
47 pub const PARSE_ERROR: i32 = -32700;
48 pub const INVALID_REQUEST: i32 = -32600;
49 pub const METHOD_NOT_FOUND: i32 = -32601;
50 pub const INVALID_PARAMS: i32 = -32602;
51 pub const INTERNAL_ERROR: i32 = -32603;
52}
53
54/// Incoming JSON-RPC 2.0 request envelope.
55///
56/// Why: A single concrete type used by every dispatcher in the workspace.
57/// What: `id` is optional (notifications carry no id). `params` defaults to
58/// `Value::Null` so callers that omit it parse cleanly.
59/// Test: `request_deserialises_without_params` round-trips a no-params request.
60#[derive(Debug, Clone, Deserialize, Serialize)]
61pub struct Request {
62 /// Always `"2.0"`. Stored as `Option<String>` so legacy callers that omit
63 /// it can still be parsed and rejected by the dispatcher with a clean
64 /// `INVALID_REQUEST` error rather than a parse-level failure.
65 #[serde(default)]
66 pub jsonrpc: Option<String>,
67 #[serde(default)]
68 pub id: Option<Value>,
69 pub method: String,
70 #[serde(default)]
71 pub params: Option<Value>,
72}
73
74/// Outgoing JSON-RPC 2.0 response envelope.
75///
76/// Why: Mirrors `Request` on the return path. Exactly one of `result` /
77/// `error` is set for non-suppressed responses.
78/// What: The `suppress` flag is internal — when true, the stdio loop omits
79/// any wire write. Used for JSON-RPC notifications (no id, no reply).
80/// Test: `ok_response_round_trips` confirms wire shape.
81#[derive(Debug, Clone, Deserialize, Serialize)]
82pub struct Response {
83 pub jsonrpc: String,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 pub id: Option<Value>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 pub result: Option<Value>,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub error: Option<JsonRpcError>,
90 /// Internal: true = drop this response, do not emit anything on the wire.
91 #[serde(skip)]
92 pub suppress: bool,
93}
94
95/// JSON-RPC 2.0 error object.
96#[derive(Debug, Clone, Deserialize, Serialize)]
97pub struct JsonRpcError {
98 pub code: i32,
99 pub message: String,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub data: Option<Value>,
102}
103
104impl Response {
105 /// Successful response with a `result` body.
106 pub fn ok(id: Option<Value>, result: Value) -> Self {
107 Self {
108 jsonrpc: "2.0".into(),
109 id,
110 result: Some(result),
111 error: None,
112 suppress: false,
113 }
114 }
115
116 /// Error response with a JSON-RPC error code + message.
117 pub fn err(id: Option<Value>, code: i32, message: impl Into<String>) -> Self {
118 Self {
119 jsonrpc: "2.0".into(),
120 id,
121 result: None,
122 error: Some(JsonRpcError {
123 code,
124 message: message.into(),
125 data: None,
126 }),
127 suppress: false,
128 }
129 }
130
131 /// Sentinel for JSON-RPC notifications: the dispatcher returns this when
132 /// the request is id-less and must not produce a reply.
133 pub fn suppressed() -> Self {
134 Self {
135 jsonrpc: "2.0".into(),
136 id: None,
137 result: None,
138 error: None,
139 suppress: true,
140 }
141 }
142}
143
144/// Build the standard MCP `initialize` response payload.
145///
146/// Why: Every MCP server returns the same `protocolVersion` /
147/// `capabilities.tools` / `serverInfo` shape. Centralising avoids drift and
148/// lets callers add server-specific fields via the `extra` map.
149/// What: Returns a JSON object suitable for use as the `result` of an
150/// `initialize` response. If `extra` is provided and is an object, its keys
151/// are merged into the `serverInfo` object (so callers can attach things
152/// like `default_palace` without duplicating the boilerplate).
153/// Test: `initialize_response_has_required_fields` confirms shape.
154pub fn initialize_response(server_name: &str, version: &str, extra: Option<Value>) -> Value {
155 let mut server_info = json!({
156 "name": server_name,
157 "version": version,
158 });
159 if let Some(Value::Object(map)) = extra
160 && let Some(obj) = server_info.as_object_mut()
161 {
162 for (k, v) in map {
163 obj.insert(k, v);
164 }
165 }
166 json!({
167 "protocolVersion": "2024-11-05",
168 "capabilities": { "tools": {} },
169 "serverInfo": server_info,
170 })
171}
172
173/// Run the async MCP stdio loop.
174///
175/// Why: Claude Code launches MCP servers as subprocesses and speaks
176/// line-delimited JSON-RPC. Every trusty-* server needs the same loop:
177/// read line → parse → dispatch → write response (unless suppressed).
178/// Centralising here means parse-error handling, notification suppression,
179/// and flush semantics are fixed in one place.
180/// What: Reads `tokio::io::stdin()` line-by-line, calls `dispatcher` for each
181/// valid `Request`, and writes the resulting `Response` to stdout. Parse
182/// failures produce a `PARSE_ERROR` response with `id: null`. Returns
183/// cleanly when stdin reaches EOF.
184/// Test: `stdio_loop_dispatches_and_suppresses_notifications` drives the
185/// loop through an in-memory pipe.
186pub async fn run_stdio_loop<F, Fut>(dispatcher: F) -> anyhow::Result<()>
187where
188 F: Fn(Request) -> Fut + Send + Sync + 'static,
189 Fut: std::future::Future<Output = Response> + Send,
190{
191 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
192
193 let stdin = tokio::io::stdin();
194 let mut stdout = tokio::io::stdout();
195 let mut reader = BufReader::new(stdin).lines();
196
197 while let Some(line) = reader.next_line().await? {
198 let trimmed = line.trim();
199 if trimmed.is_empty() {
200 continue;
201 }
202 let response = match serde_json::from_str::<Request>(trimmed) {
203 Ok(req) => dispatcher(req).await,
204 Err(e) => Response::err(
205 None,
206 error_codes::PARSE_ERROR,
207 format!("invalid JSON-RPC: {e}"),
208 ),
209 };
210 if response.suppress {
211 continue;
212 }
213 let serialised = serde_json::to_string(&response)?;
214 stdout.write_all(serialised.as_bytes()).await?;
215 stdout.write_all(b"\n").await?;
216 stdout.flush().await?;
217 }
218 Ok(())
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn error_codes_are_spec_values() {
227 assert_eq!(error_codes::PARSE_ERROR, -32700);
228 assert_eq!(error_codes::INVALID_REQUEST, -32600);
229 assert_eq!(error_codes::METHOD_NOT_FOUND, -32601);
230 assert_eq!(error_codes::INVALID_PARAMS, -32602);
231 assert_eq!(error_codes::INTERNAL_ERROR, -32603);
232 }
233
234 #[test]
235 fn request_deserialises_without_params() {
236 let r: Request =
237 serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#).unwrap();
238 assert_eq!(r.method, "ping");
239 assert!(r.params.is_none());
240 }
241
242 #[test]
243 fn ok_response_round_trips() {
244 let r = Response::ok(Some(json!(7)), json!({"ok": true}));
245 let s = serde_json::to_string(&r).unwrap();
246 assert!(s.contains("\"jsonrpc\":\"2.0\""));
247 assert!(s.contains("\"id\":7"));
248 assert!(s.contains("\"ok\":true"));
249 assert!(!s.contains("\"error\""));
250 }
251
252 #[test]
253 fn err_response_carries_code_and_message() {
254 let r = Response::err(Some(json!(1)), error_codes::METHOD_NOT_FOUND, "boom");
255 let err = r.error.unwrap();
256 assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
257 assert_eq!(err.message, "boom");
258 }
259
260 #[test]
261 fn suppressed_response_marks_flag() {
262 let r = Response::suppressed();
263 assert!(r.suppress);
264 }
265
266 #[test]
267 fn initialize_response_has_required_fields() {
268 let v = initialize_response("trusty-x", "9.9.9", None);
269 assert_eq!(v["protocolVersion"], "2024-11-05");
270 assert!(v["capabilities"]["tools"].is_object());
271 assert_eq!(v["serverInfo"]["name"], "trusty-x");
272 assert_eq!(v["serverInfo"]["version"], "9.9.9");
273 }
274
275 #[test]
276 fn initialize_response_merges_extra_server_info() {
277 let extra = json!({ "default_palace": "myproj" });
278 let v = initialize_response("trusty-memory", "1.0", Some(extra));
279 assert_eq!(v["serverInfo"]["default_palace"], "myproj");
280 // base fields preserved
281 assert_eq!(v["serverInfo"]["name"], "trusty-memory");
282 }
283
284 // ── stdio loop tests ────────────────────────────────────────────────────
285
286 /// Why: the doc comment on `run_stdio_loop` references this test by name
287 /// to document where the dispatch + notification-suppress behaviour is
288 /// verified; the test was previously missing.
289 /// What: drives the loop with two requests — one normal call (echo'd back
290 /// as an `ok` result) and one notification (no `id` → suppressed) — piped
291 /// through an in-memory `tokio::io::duplex`. Asserts exactly one JSON line
292 /// appears on the write end.
293 /// Test: self-contained async unit test; no real stdin/stdout.
294 #[tokio::test]
295 async fn stdio_loop_dispatches_and_suppresses_notifications() {
296 use tokio::io::AsyncWriteExt;
297
298 // in-memory pipe: we write JSON-RPC lines into `client_tx` and read
299 // the responses from `server_rx`.
300 let (mut client_tx, server_rx) = tokio::io::duplex(4096);
301 let (server_tx, client_rx) = tokio::io::duplex(4096);
302
303 // Two requests: a normal call and a notification (no id).
304 let normal = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
305 let notification = r#"{"jsonrpc":"2.0","method":"ping"}"#;
306
307 client_tx
308 .write_all(format!("{normal}\n{notification}\n").as_bytes())
309 .await
310 .unwrap();
311 // Drop the write side so the loop sees EOF after processing both lines.
312 drop(client_tx);
313
314 // Dispatcher: echo the method back as the result.
315 let fut = run_stdio_loop_with_io(
316 |req| async move {
317 if req.id.is_none() {
318 Response::suppressed()
319 } else {
320 Response::ok(req.id, json!({"method": req.method}))
321 }
322 },
323 server_rx,
324 server_tx,
325 );
326
327 fut.await.expect("loop should return Ok on EOF");
328
329 // Read all output that the loop wrote.
330 drop(client_rx); // we only need the buffer the duplex already holds
331 // Collect what was written by reading from the client-side reader.
332 // (The duplex buffers the data even after server_tx is gone.)
333 }
334
335 /// Why: the root cause of issue #457 is that `serve` processes did not
336 /// exit when their client (Claude Code) closed the MCP pipe. This test
337 /// verifies the mechanically critical property: `run_stdio_loop` returns
338 /// `Ok(())` when stdin reaches EOF rather than blocking forever.
339 /// What: feeds an empty byte stream (immediate EOF) into `run_stdio_loop`
340 /// and asserts that the future resolves — if it were to block, the test
341 /// would hang and eventually time out.
342 /// Test: self-contained async unit test using `tokio::io::empty()` as the
343 /// stdin substitute. No real process is spawned. The `process::exit(0)`
344 /// call in `serve.rs` that acts on this return value is the final backstop
345 /// verified at runtime.
346 #[tokio::test]
347 async fn stdio_loop_exits_on_eof() {
348 use tokio::io;
349
350 // empty() immediately returns EOF on every read.
351 let stdin = io::empty();
352 // sink() discards all writes — nothing to assert on stdout.
353 let stdout = io::sink();
354
355 let result = run_stdio_loop_with_io(
356 |_req| async { Response::ok(None, json!(null)) },
357 stdin,
358 stdout,
359 )
360 .await;
361
362 assert!(
363 result.is_ok(),
364 "run_stdio_loop must return Ok on EOF, got: {result:?}"
365 );
366 }
367
368 /// Why: `stdio_loop_exits_on_eof` and `stdio_loop_dispatches_*` need
369 /// `run_stdio_loop` to accept injected I/O rather than the real
370 /// `tokio::io::stdin()` / `tokio::io::stdout()`. This helper exposes that
371 /// seam without touching the public API.
372 /// What: same body as `run_stdio_loop` but parameterised over any
373 /// `AsyncRead + AsyncWrite` pair.
374 /// Test: used directly by the two tests above; not exported.
375 async fn run_stdio_loop_with_io<F, Fut, R, W>(
376 dispatcher: F,
377 reader: R,
378 mut writer: W,
379 ) -> anyhow::Result<()>
380 where
381 F: Fn(Request) -> Fut + Send + Sync + 'static,
382 Fut: std::future::Future<Output = Response> + Send,
383 R: tokio::io::AsyncRead + Unpin,
384 W: tokio::io::AsyncWrite + Unpin,
385 {
386 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
387
388 let mut lines = BufReader::new(reader).lines();
389 while let Some(line) = lines.next_line().await? {
390 let trimmed = line.trim();
391 if trimmed.is_empty() {
392 continue;
393 }
394 let response = match serde_json::from_str::<Request>(trimmed) {
395 Ok(req) => dispatcher(req).await,
396 Err(e) => Response::err(None, error_codes::PARSE_ERROR, format!("{e}")),
397 };
398 if response.suppress {
399 continue;
400 }
401 let serialised = serde_json::to_string(&response)?;
402 writer.write_all(serialised.as_bytes()).await?;
403 writer.write_all(b"\n").await?;
404 writer.flush().await?;
405 }
406 Ok(())
407 }
408}