//! JSON-RPC 2.0 messages as MCP uses them on stdio: one message per line, //! no batches. //! //! Every line is untrusted. [`parse`] turns any input into an //! [`Incoming`] message or a ready error response and never panics; the //! response helpers always produce one valid line. use serde_json::{Map, Value, json}; /// Standard JSON-RPC error codes and the MCP codes Lutra emits. pub mod codes { /// The line is not valid JSON. pub const PARSE_ERROR: i64 = -32700; /// The JSON is not a valid request. pub const INVALID_REQUEST: i64 = -32600; /// No such method. pub const METHOD_NOT_FOUND: i64 = -32601; /// Bad params, an unknown tool or resource, or missing request /// metadata. pub const INVALID_PARAMS: i64 = -32602; /// The server failed. pub const INTERNAL_ERROR: i64 = -32603; /// The request names a protocol version the server does not support /// (MCP 2026-07-28). pub const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022; } /// One message read from the client. #[derive(Debug, Clone, PartialEq)] pub enum Incoming { /// A request, which gets exactly one response. Request { /// The id: a number or a string. id: Value, /// The method name. method: String, /// The params object; empty if absent. params: Map, }, /// A notification, which gets no response. Notification { /// The method name. method: String, }, /// A response to a request of ours; Lutra sends none, so it is /// ignored. Response, } /// Parses one line. /// /// # Errors /// The error response line to send back: a parse error for invalid /// JSON, invalid request for anything that is not a single JSON-RPC 2.0 /// message, invalid params for params that are not an object. pub fn parse(line: &str) -> Result { let value: Value = serde_json::from_str(line) .map_err(|e| error(&Value::Null, codes::PARSE_ERROR, &e.to_string(), None))?; let Value::Object(mut object) = value else { return Err(error( &Value::Null, codes::INVALID_REQUEST, "a message must be one JSON object (batches are not supported)", None, )); }; let id = object.remove("id"); let id_ok = matches!(id, Some(Value::Number(_) | Value::String(_))); let echo = if id_ok { id.clone().unwrap_or(Value::Null) } else { Value::Null }; if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { return Err(error( &echo, codes::INVALID_REQUEST, "jsonrpc must be \"2.0\"", None, )); } let method = match object.remove("method") { Some(Value::String(method)) => method, Some(_) => { return Err(error( &echo, codes::INVALID_REQUEST, "method must be a string", None, )); } None if object.contains_key("result") || object.contains_key("error") => { return Ok(Incoming::Response); } None => { return Err(error(&echo, codes::INVALID_REQUEST, "missing method", None)); } }; let params = match object.remove("params") { None | Some(Value::Null) => Map::new(), Some(Value::Object(params)) => params, Some(_) => { if id.is_none() { return Ok(Incoming::Notification { method }); } return Err(error( &echo, codes::INVALID_PARAMS, "params must be an object", None, )); } }; match id { None => Ok(Incoming::Notification { method }), Some(_) if !id_ok => Err(error( &Value::Null, codes::INVALID_REQUEST, "the id must be a number or a string", None, )), Some(id) => Ok(Incoming::Request { id, method, params }), } } /// A success response line. pub fn result(id: &Value, result: Value) -> String { encode(&json!({ "jsonrpc": "2.0", "id": id, "result": result })) } /// An error response line, with optional `data`. pub fn error(id: &Value, code: i64, message: &str, data: Option) -> String { let mut error = json!({ "code": code, "message": message }); if let (Some(data), Some(object)) = (data, error.as_object_mut()) { object.insert("data".into(), data); } encode(&json!({ "jsonrpc": "2.0", "id": id, "error": error })) } /// Serialises a message as one line. serde_json escapes control /// characters inside strings, so the line has no embedded newline. fn encode(message: &Value) -> String { serde_json::to_string(message).unwrap_or_else(|_| { String::from( r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"cannot encode the response"}}"#, ) }) } #[cfg(test)] mod tests { use super::*; fn err_code(line: &str) -> (Value, i64) { let response: Value = serde_json::from_str(&parse(line).unwrap_err()).unwrap(); ( response["id"].clone(), response["error"]["code"].as_i64().unwrap(), ) } #[test] fn parses_requests_and_notifications() { let m = parse(r#"{"jsonrpc":"2.0","id":7,"method":"tools/list"}"#).unwrap(); assert_eq!( m, Incoming::Request { id: json!(7), method: "tools/list".into(), params: Map::new() } ); let m = parse(r#"{"jsonrpc":"2.0","id":"a","method":"x","params":{"k":1}}"#).unwrap(); let Incoming::Request { id, params, .. } = m else { panic!() }; assert_eq!(id, json!("a")); assert_eq!(params["k"], 1); assert_eq!( parse(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).unwrap(), Incoming::Notification { method: "notifications/initialized".into() } ); assert_eq!( parse(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#).unwrap(), Incoming::Response ); } #[test] fn rejects_bad_messages() { assert_eq!(err_code("{"), (Value::Null, codes::PARSE_ERROR)); assert_eq!(err_code("[]"), (Value::Null, codes::INVALID_REQUEST)); assert_eq!( err_code(r#"{"id":1,"method":"x"}"#), (json!(1), codes::INVALID_REQUEST) ); assert_eq!( err_code(r#"{"jsonrpc":"2.0","id":null,"method":"x"}"#), (Value::Null, codes::INVALID_REQUEST) ); assert_eq!( err_code(r#"{"jsonrpc":"2.0","id":{},"method":"x"}"#), (Value::Null, codes::INVALID_REQUEST) ); assert_eq!( err_code(r#"{"jsonrpc":"2.0","id":2,"method":5}"#), (json!(2), codes::INVALID_REQUEST) ); assert_eq!( err_code(r#"{"jsonrpc":"2.0","id":3,"method":"x","params":[1]}"#), (json!(3), codes::INVALID_PARAMS) ); assert_eq!( err_code(r#"{"jsonrpc":"2.0","id":4}"#), (json!(4), codes::INVALID_REQUEST) ); } #[test] fn responses_are_single_lines() { let line = result(&json!(1), json!({"text": "a\nb"})); assert!(!line.contains('\n')); let line = error(&json!("x"), codes::INTERNAL_ERROR, "a\nb", Some(json!(1))); assert!(!line.contains('\n')); let value: Value = serde_json::from_str(&line).unwrap(); assert_eq!(value["error"]["data"], 1); } }