Add bounded JSON-RPC server envelopes

This commit is contained in:
Dylan M. Taylor committed 2026-11-15 11:51:16 +00:00
1 parent 55b1d7f3c5
commit e67d770c09
6 files changed
+380

No files matched your search

Generated
+7
View File
@@ -1969,6 +1969,13 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "craft-jxl"
version = "0.1.0"
+1
View File
@@ -88,6 +88,7 @@ craft-indd = { path = "crates/indd" }
craft-jmap = { path = "crates/jmap" }
craft-ical = { path = "crates/ical" }
craft-jpeg = { path = "crates/jpeg" }
craft-jsonrpc = { path = "crates/jsonrpc" }
craft-jxl = { path = "crates/jxl" }
craft-kiwi = { path = "crates/kiwi" }
craft-keymap = { path = "crates/keymap" }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "craft-jsonrpc"
description = "Bounded JSON-RPC 2.0 server envelopes without transport or application routing"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde_json = { workspace = true }
+27
View File
@@ -0,0 +1,27 @@
# craft-jsonrpc
`craft-jsonrpc` provides bounded JSON-RPC 2.0 server envelopes independently of a transport or an
application's method router. It can read a bounded newline-delimited message, parse it from bytes,
check request IDs and batch sizes, dispatch requests and notifications separately, and build
response envelopes. It does not start a server, choose an MCP protocol version, or interpret tool
names and arguments.
`Limits` defaults to 64 MiB per message and 4096 batch entries. `parse_json` checks the byte limit
before deserialization, and `process` rejects an oversized batch before calling any handler.
For newline-delimited transports, `read_line` bounds memory while reading; after an over-limit
line, the caller must close the stream or discard the rest of that line.
`serde_json`'s nesting limit remains in effect. Response sizes are the caller's responsibility.
A valid request receives the handler's result or error with its original string, integer, or null
ID. An omitted ID is a notification: it calls the separate notification handler and gets no reply.
Malformed batch entries receive an invalid-request error; an empty batch gets one error response;
a batch containing only notifications has no response. Invalid parameter shapes receive an
invalid-params error for requests and no reply for notifications. The handler decides whether
object or array parameters are valid for each method.
The caller may inspect the bounded parsed value before `process` to support an existing legacy
protocol. Parse failures and limit failures are returned explicitly so each transport can choose
its error and connection policy; `parse_error_response` builds the JSON-RPC parse error.
The envelope behavior is extracted from StencilCraft's JSON-lines MCP/control server. App-specific
method routing, legacy control requests, and MCP lifecycle policy stay with the app.
+186
View File
@@ -0,0 +1,186 @@
//! Bounded JSON-RPC 2.0 server envelopes without a transport or application router.
//!
//! Parse a bounded line with [`parse_json`], then pass the value to [`process`]. A host may
//! inspect the parsed value first for a legacy protocol. `process` validates envelopes, dispatches
//! requests and notifications separately, and constructs single or batch replies. The host owns
//! the transport, method semantics and response-size policy.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use serde_json::{Value, json};
use std::io::BufRead;
/// Bounds on a single JSON document and on the number of requests in a batch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
pub max_message_bytes: usize,
pub max_batch_items: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { max_message_bytes: 64 * 1024 * 1024, max_batch_items: 4096 }
}
}
/// Failure before dispatch. An over-limit batch is rejected before any callback is invoked.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ParseError {
MessageTooLarge,
InvalidJson,
BatchTooLarge,
}
impl std::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::MessageTooLarge => "JSON-RPC message exceeds the byte limit",
Self::InvalidJson => "invalid JSON",
Self::BatchTooLarge => "JSON-RPC batch exceeds the item limit",
})
}
}
impl std::error::Error for ParseError {}
/// Error reading a newline-delimited message. After `TooLong`, close or otherwise discard the
/// remaining input line before reading another message.
#[derive(Debug)]
pub enum LineError {
Io(std::io::Error),
TooLong,
}
impl std::fmt::Display for LineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(error) => write!(f, "message read failed: {error}"),
Self::TooLong => f.write_str("message exceeds the byte limit"),
}
}
}
impl std::error::Error for LineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::TooLong => None,
}
}
}
/// Read at most `max_bytes` before a newline, without allocating for an oversized line. The
/// newline is consumed but omitted from the returned bytes. EOF with no bytes returns `None`;
/// an empty line returns `Some(Vec::new())`.
pub fn read_line<R: BufRead>(reader: &mut R, max_bytes: usize) -> Result<Option<Vec<u8>>, LineError> {
let mut line = Vec::new();
loop {
let bytes = reader.fill_buf().map_err(LineError::Io)?;
if bytes.is_empty() {
return Ok((!line.is_empty()).then_some(line));
}
let newline = bytes.iter().position(|&byte| byte == b'\n');
let len = newline.unwrap_or(bytes.len());
if line.len().saturating_add(len) > max_bytes {
return Err(LineError::TooLong);
}
line.extend_from_slice(&bytes[..len]);
reader.consume(len + usize::from(newline.is_some()));
if newline.is_some() {
return Ok(Some(line));
}
}
}
/// Parse JSON after checking its byte length. `serde_json` also bounds nesting depth.
pub fn parse_json(bytes: &[u8], limits: Limits) -> Result<Value, ParseError> {
if bytes.len() > limits.max_message_bytes {
return Err(ParseError::MessageTooLarge);
}
serde_json::from_slice(bytes).map_err(|_| ParseError::InvalidJson)
}
/// A validated request or notification. A present null `id` is distinct from an omitted `id`.
#[derive(Clone, Copy, Debug)]
pub struct Request<'a> {
pub id: Option<&'a Value>,
pub method: &'a str,
pub params: Option<&'a Value>,
}
/// A JSON-RPC error returned by a method handler.
#[derive(Clone, Debug, PartialEq)]
pub struct RpcError {
pub code: i64,
pub message: String,
pub data: Option<Value>,
}
impl RpcError {
pub fn new(code: i64, message: impl Into<String>) -> Self {
Self { code, message: message.into(), data: None }
}
}
/// Build an error response, including optional error data.
pub fn error_response(id: Value, error: RpcError) -> Value {
let mut detail = json!({"code": error.code, "message": error.message});
if let (Some(data), Some(object)) = (error.data, detail.as_object_mut()) {
object.insert("data".into(), data);
}
json!({"jsonrpc": "2.0", "id": id, "error": detail})
}
/// Build the standard parse-error response for input that is not JSON.
pub fn parse_error_response() -> Value {
error_response(Value::Null, RpcError::new(-32700, "Parse error"))
}
fn invalid_request() -> Value {
error_response(Value::Null, RpcError::new(-32600, "Invalid Request"))
}
fn one<F, N>(value: &Value, on_request: &mut F, on_notification: &mut N) -> Option<Value>
where
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
N: FnMut(Request<'_>),
{
let Some(object) = value.as_object() else { return Some(invalid_request()) };
let id = object.get("id");
let valid_id = id.is_none_or(|v| v.is_null() || v.is_string() || v.is_i64() || v.is_u64());
let method = object.get("method").and_then(Value::as_str);
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || method.is_none() || !valid_id {
return Some(invalid_request());
}
let Some(method) = method else { return Some(invalid_request()) };
let request = Request { id, method, params: object.get("params") };
if request.params.is_some_and(|v| !v.is_object() && !v.is_array()) {
return id.map(|id| error_response(id.clone(), RpcError::new(-32602, "Invalid params")));
}
let Some(id) = id else {
on_notification(request);
return None;
};
Some(match on_request(request) {
Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
Err(error) => error_response(id.clone(), error),
})
}
/// Process a parsed JSON-RPC message. Notifications never receive a response. Invalid batch
/// entries produce individual errors; an empty batch produces one invalid-request response.
/// A batch over the limit returns [`ParseError::BatchTooLarge`] without invoking either callback.
pub fn process<F, N>(value: &Value, limits: Limits, mut on_request: F, mut on_notification: N) -> Result<Option<Value>, ParseError>
where
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
N: FnMut(Request<'_>),
{
let Some(batch) = value.as_array() else { return Ok(one(value, &mut on_request, &mut on_notification)) };
if batch.len() > limits.max_batch_items {
return Err(ParseError::BatchTooLarge);
}
if batch.is_empty() {
return Ok(Some(invalid_request()));
}
let responses: Vec<_> = batch.iter().filter_map(|v| one(v, &mut on_request, &mut on_notification)).collect();
Ok((!responses.is_empty()).then_some(Value::Array(responses)))
}
+145
View File
@@ -0,0 +1,145 @@
use craft_jsonrpc::{Limits, ParseError, RpcError, parse_error_response, parse_json, process};
use serde_json::{Value, json};
#[test]
fn batches_preserve_ids_order_and_suppress_notification_replies() {
let input = json!([
{"jsonrpc": "2.0", "method": "notifications/initialized"},
{"jsonrpc": "2.0", "id": "a", "method": "ping"},
{"jsonrpc": "2.0", "id": 2, "method": "unknown"},
17,
{"jsonrpc": "2.0", "id": null, "method": "ping"}
]);
let mut notifications = Vec::new();
let result = process(
&input,
Limits::default(),
|request| match request.method {
"ping" => Ok(json!({})),
_ => Err(RpcError::new(-32601, "Method not found")),
},
|request| notifications.push(request.method.to_owned()),
)
.unwrap()
.unwrap();
assert_eq!(notifications, ["notifications/initialized"]);
assert_eq!(
result,
json!([
{"jsonrpc":"2.0", "id":"a", "result":{}},
{"jsonrpc":"2.0", "id":2, "error":{"code":-32601,"message":"Method not found"}},
{"jsonrpc":"2.0", "id":null, "error":{"code":-32600,"message":"Invalid Request"}},
{"jsonrpc":"2.0", "id":null, "result":{}}
])
);
}
#[test]
fn notifications_never_receive_responses_including_all_notification_batches() {
let input = json!([
{"jsonrpc":"2.0", "method":"tools/call", "params":{"name":"mutating"}},
{"jsonrpc":"2.0", "method":"notifications/initialized"}
]);
let mut requests = 0;
let mut notices = 0;
let result = process(
&input,
Limits::default(),
|_| {
requests += 1;
Ok(Value::Null)
},
|_| notices += 1,
)
.unwrap();
assert!(result.is_none());
assert_eq!(requests, 0);
assert_eq!(notices, 2);
}
#[test]
fn invalid_envelopes_and_params_return_standard_errors() {
for id in [json!(1.5), json!(true), json!([]), json!({})] {
let input = json!({"jsonrpc":"2.0", "id":id, "method":"ping"});
let reply = process(&input, Limits::default(), |_| panic!("invalid id dispatched"), |_| panic!("invalid id notified")).unwrap().unwrap();
assert_eq!(reply["id"], Value::Null);
assert_eq!(reply["error"]["code"], -32600);
}
for input in [json!({}), json!({"jsonrpc":"1.0", "id":1, "method":"ping"}), json!({"jsonrpc":"2.0", "id":1}), json!([])] {
let reply =
process(&input, Limits::default(), |_| panic!("invalid request dispatched"), |_| panic!("invalid notification")).unwrap().unwrap();
assert_eq!(reply["error"]["code"], -32600);
}
let input = json!({"jsonrpc":"2.0", "id":4, "method":"ping", "params":17});
let reply = process(&input, Limits::default(), |_| panic!("invalid params dispatched"), |_| {}).unwrap().unwrap();
assert_eq!(reply["id"], 4);
assert_eq!(reply["error"]["code"], -32602);
let notification = json!({"jsonrpc":"2.0", "method":"notice", "params":17});
assert!(process(&notification, Limits::default(), |_| panic!("invalid request"), |_| panic!("invalid notification")).unwrap().is_none());
}
#[test]
fn arrays_are_valid_params_and_errors_can_include_data() {
let input = json!({"jsonrpc":"2.0", "id":-7, "method":"test", "params":[1, 2]});
let reply = process(
&input,
Limits::default(),
|request| {
assert_eq!(request.params, Some(&json!([1, 2])));
let mut error = RpcError::new(-32000, "failure");
error.data = Some(json!({"why":"example"}));
Err(error)
},
|_| {},
)
.unwrap()
.unwrap();
assert_eq!(reply, json!({"jsonrpc":"2.0", "id":-7, "error":{"code":-32000,"message":"failure","data":{"why":"example"}}}));
}
#[test]
fn parse_and_batch_limits_apply_before_dispatch() {
let limits = Limits { max_message_bytes: 3, max_batch_items: 1 };
assert_eq!(parse_json(b"null", limits), Err(ParseError::MessageTooLarge));
assert_eq!(parse_json(b"123", limits).unwrap(), json!(123));
assert_eq!(parse_json(b"{", limits), Err(ParseError::InvalidJson));
assert_eq!(parse_error_response()["error"]["code"], -32700);
let input = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}, {"jsonrpc":"2.0", "method":"notice"}]);
assert_eq!(
process(&input, limits, |_| panic!("over-limit batch dispatched"), |_| panic!("over-limit batch notified")),
Err(ParseError::BatchTooLarge)
);
let one = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}]);
assert_eq!(process(&one, limits, |_| Ok(json!({})), |_| {}).unwrap().unwrap().as_array().unwrap().len(), 1);
}
#[test]
fn invalid_utf8_and_excessive_nesting_are_rejected() {
assert_eq!(parse_json(&[0xff], Limits::default()), Err(ParseError::InvalidJson));
let nested = format!("{}0{}", "[".repeat(200), "]".repeat(200));
assert_eq!(parse_json(nested.as_bytes(), Limits::default()), Err(ParseError::InvalidJson));
}
#[test]
fn bounded_line_read_handles_chunks_empty_lines_and_eof() {
use std::io::{BufReader, Cursor};
let mut reader = BufReader::with_capacity(2, Cursor::new(b"abc\n\nxy"));
assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"abc".to_vec()));
assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(Vec::new()));
assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"xy".to_vec()));
assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), None);
let mut too_long = BufReader::with_capacity(2, Cursor::new(b"abcd\n"));
assert!(matches!(craft_jsonrpc::read_line(&mut too_long, 3), Err(craft_jsonrpc::LineError::TooLong)));
}
#[test]
fn bounded_line_read_propagates_io_errors() {
struct Broken;
impl std::io::Read for Broken {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("broken"))
}
}
let mut reader = std::io::BufReader::new(Broken);
assert!(matches!(craft_jsonrpc::read_line(&mut reader, 1), Err(craft_jsonrpc::LineError::Io(_))));
}