MCP: classify inbound responses through SDK with fresh authorization
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 37m3s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-11-13 00:41:28 +00:00
1 parent 66bb135398
commit 65144fd8c6
7 files changed
+628 -47

No files matched your search

@@ -27,7 +27,7 @@ impl DispatchEnvelope {
}
}
/// Call only after `validate_jsonrpc_envelope`; responses keep their existing non-SDK path.
/// Call only after `validate_jsonrpc_envelope`; responses use the separate response SDK classifier.
/// Params and extensions stay in the raw message, not in this routing-only projection.
pub(crate) fn decode_dispatch_envelope(
message: &Value,
@@ -135,7 +135,7 @@ mod tests {
}
#[test]
fn incoming_success_and_error_responses_are_not_migrated() {
fn incoming_success_and_error_responses_do_not_enter_method_dispatch() {
for message in [
json!({"jsonrpc": "2.0", "id": 1, "result": {}}),
json!({"jsonrpc": "2.0", "id": "id", "error": {"code": -1, "message": "error"}}),
+2 -45
View File
@@ -32,6 +32,7 @@ mod logging;
mod prompts;
mod registry;
mod resources;
mod response_sdk;
mod signals;
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
@@ -91,50 +92,6 @@ fn is_valid_request_id(id: &Value) -> bool {
id.is_string() || id.is_number()
}
/// The pinned error object: `Error { code: number; message: string; data?: unknown }`.
fn is_valid_error_object(error: Option<&Value>) -> bool {
let Some(Value::Object(error)) = error else {
return false;
};
error.get("code").is_some_and(Value::is_number)
&& error.get("message").is_some_and(Value::is_string)
}
/// Classify a wire response (a message without `method`).
///
/// Pinned shapes are exclusive: a success response carries `result: Result` (an object) and a required
/// `id: RequestId`, an error response carries `error: Error` and may omit the id (a present id must
/// still be a `RequestId`). Both together, neither, a foreign id, a non-object `result` or a malformed
/// error object are all invalid requests rather than an acknowledgement.
///
/// The `result` value is required to be an object because the pinned `JSONRPCResultResponse` types it as
/// `Result`; the modern `resultType` member is deliberately **not** required here, because an incoming
/// response may come from a client implementing an earlier revision.
fn classify_wire_response(object: &serde_json::Map<String, Value>) -> Option<EnvelopeKind> {
match (object.contains_key("result"), object.contains_key("error")) {
(true, false) => {
if !matches!(object.get("result"), Some(Value::Object(_))) {
return None;
}
object
.get("id")
.filter(|id| is_valid_request_id(id))
.map(|_| EnvelopeKind::Response)
}
(false, true) => {
if !is_valid_error_object(object.get("error")) {
return None;
}
match object.get("id") {
None => Some(EnvelopeKind::Response),
Some(id) if is_valid_request_id(id) => Some(EnvelopeKind::Response),
Some(_) => None,
}
}
_ => None,
}
}
/// Pinned modern wire projection of a success result.
///
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
@@ -260,7 +217,7 @@ pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind,
}
}
Some(_) => Err(rejected(invalid_request_response())),
None => match classify_wire_response(object) {
None => match response_sdk::classify_response(message) {
Some(kind) => Ok(kind),
None => Err(rejected(invalid_request_response())),
},
@@ -0,0 +1,223 @@
//! SDK classification of inbound responses, without narrowing the admitted wire numbers.
use rmcp::model::{JsonRpcError, JsonRpcResponse};
use serde_json::{Value, json};
use super::EnvelopeKind;
enum ResponseEnvelope {
Success(JsonRpcResponse<Value>),
Error(JsonRpcError),
}
/// Only the no-method branch of the envelope guard calls this helper.
pub(super) fn classify_response(message: &Value) -> Option<EnvelopeKind> {
match decode_response(message)? {
ResponseEnvelope::Success(JsonRpcResponse { result, .. }) => {
// The generic SDK result must still satisfy the pinned object-only contract.
if !result.is_object() {
return None;
}
#[cfg(test)]
crate::app::dispatch_observer::sdk_inbound_response_consumed();
Some(EnvelopeKind::Response)
}
ResponseEnvelope::Error(JsonRpcError { .. }) => {
#[cfg(test)]
crate::app::dispatch_observer::sdk_inbound_error_consumed();
Some(EnvelopeKind::Response)
}
}
}
fn decode_response(message: &Value) -> Option<ResponseEnvelope> {
let object = message.as_object()?;
if object.get("jsonrpc")?.as_str()? != "2.0" || object.contains_key("method") {
return None;
}
let id = object.get("id");
if id.is_some_and(|id| !id.is_string() && !id.is_number()) {
return None;
}
let mut projection = json!({"jsonrpc": "2.0"});
if let Some(id) = id {
// SDK ids are string/i64; this surrogate stays in the classification-only clone.
projection["id"] = if id.is_number() && id.as_i64().is_none() {
json!(0)
} else {
id.clone()
};
}
match (object.get("result"), object.get("error")) {
(Some(result), None) if result.is_object() && id.is_some() => {
projection["result"] = result.clone();
let response = serde_json::from_value::<JsonRpcResponse<Value>>(projection).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_inbound_response_decoded();
Some(ResponseEnvelope::Success(response))
}
(None, Some(error)) if error.is_object() => {
let code = error.get("code")?;
if !code.is_number() || !error.get("message")?.is_string() {
return None;
}
projection["error"] = error.clone();
// SDK codes are i32; validate the original number before projecting only that field.
if code
.as_i64()
.and_then(|code| i32::try_from(code).ok())
.is_none()
{
projection["error"]["code"] = json!(0);
}
let error = serde_json::from_value::<JsonRpcError>(projection).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_inbound_error_decoded();
Some(ResponseEnvelope::Error(error))
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_response_shapes_without_constraining_params_or_extensions() {
for message in [
json!({"jsonrpc": "2.0", "id": "", "result": {}}),
json!({"jsonrpc": "2.0", "id": 1, "result": {"resultType": false},
"params": false, "extension": [null, 1]}),
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": ""}}),
json!({"jsonrpc": "2.0", "id": "id", "error": {
"code": -1, "message": "error", "data": [null, {"nested": true}]
}, "params": [], "extension": false}),
] {
let original = message.to_string();
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
assert_eq!(message.to_string(), original);
}
}
#[test]
fn rejects_invalid_shapes_before_sdk_projection() {
for message in [
Value::Null,
json!([]),
json!({"id": 1, "result": {}}),
json!({"jsonrpc": "1.0", "id": 1, "result": {}}),
json!({"jsonrpc": "2.0"}),
json!({"jsonrpc": "2.0", "result": {}}),
json!({"jsonrpc": "2.0", "id": 1, "result": {}, "error": null}),
json!({"jsonrpc": "2.0", "id": 1, "result": null}),
json!({"jsonrpc": "2.0", "id": 1, "result": []}),
json!({"jsonrpc": "2.0", "id": 1, "result": true}),
json!({"jsonrpc": "2.0", "error": null}),
json!({"jsonrpc": "2.0", "error": []}),
json!({"jsonrpc": "2.0", "error": {"message": "error"}}),
json!({"jsonrpc": "2.0", "error": {"code": "-1", "message": "error"}}),
json!({"jsonrpc": "2.0", "error": {"code": null, "message": "error"}}),
json!({"jsonrpc": "2.0", "error": {"code": true, "message": "error"}}),
json!({"jsonrpc": "2.0", "error": {"code": -1}}),
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": false}}),
json!({"jsonrpc": "2.0", "method": null, "id": 1, "result": {}}),
json!({"jsonrpc": "2.0", "method": "request", "id": 1, "result": {}}),
] {
assert_eq!(classify_response(&message), None, "{message}");
}
for id in [Value::Null, json!(true), json!([]), json!({})] {
for payload in [
json!({"result": {}}),
json!({"error": {"code": -1, "message": "e"}}),
] {
let mut message = payload;
message["jsonrpc"] = json!("2.0");
message["id"] = id.clone();
assert_eq!(classify_response(&message), None, "{message}");
}
}
}
#[test]
fn numeric_projection_preserves_raw_json_and_executes_typed_variants() {
let numbers = [
json!(i64::MIN),
json!(i64::MAX),
json!(u64::MAX),
json!(i32::MIN),
json!(i32::MAX),
json!(2147483648_i64),
json!(-2147483649_i64),
json!(1.25),
json!(1.0),
json!(-0.0),
json!(f64::MAX),
];
for number in numbers {
let sdk_id = if number.as_i64().is_some() {
number.clone()
} else {
json!(0)
};
let sdk_code = if number
.as_i64()
.and_then(|n| i32::try_from(n).ok())
.is_some()
{
number.clone()
} else {
json!(0)
};
for error in [false, true] {
let mut message = json!({"jsonrpc": "2.0", "id": number});
if error {
message["error"] = json!({"code": number, "message": "e", "data": number});
} else {
message["result"] = json!({"nested": [number, null]});
}
let original = message.to_string();
match decode_response(&message).expect("numeric wire shape decodes") {
ResponseEnvelope::Success(response) => {
assert!(!error);
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
assert_eq!(response.result, message["result"]);
}
ResponseEnvelope::Error(response) => {
assert!(error);
assert_eq!(serde_json::to_value(response.id).unwrap(), sdk_id);
assert_eq!(serde_json::to_value(response.error.code).unwrap(), sdk_code);
assert_eq!(response.error.data.as_ref(), Some(&number));
}
}
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
assert_eq!(message.to_string(), original);
}
}
}
#[test]
fn typed_error_keeps_optional_id_and_arbitrary_data() {
for data in [
Value::Null,
json!(true),
json!(1.0),
json!("text"),
json!([]),
json!({}),
] {
let message =
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "e", "data": data}});
let ResponseEnvelope::Error(error) = decode_response(&message).unwrap() else {
panic!("error must retain its SDK variant");
};
assert_eq!(error.id, None);
// SDK Option<Value> maps explicit null to None; classification never rewrites the wire.
assert_eq!(
error.error.data,
if data.is_null() { None } else { Some(data) }
);
assert_eq!(classify_response(&message), Some(EnvelopeKind::Response));
}
}
}