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