use schemars::JsonSchema;
use super::{JsonRpcClientNotification, JsonRpcRequest};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
#[serde(untagged)]
#[schemars(rename = "mcp.JsonRpcClientMessage")]
pub enum JsonRpcClientMessage {
Request(JsonRpcRequest),
Notification(JsonRpcClientNotification),
}
#[cfg(test)]
mod tests {
use super::super::{ClientNotificationMethod, ClientRequestMethod};
use super::*;
#[test]
fn id_present_is_request() {
let frame = serde_json::json!({
"jsonrpc": "2.0",
"id": 3,
"method": "ping",
});
let parsed: JsonRpcClientMessage =
serde_json::from_str(&frame.to_string()).unwrap();
assert!(matches!(
parsed,
JsonRpcClientMessage::Request(JsonRpcRequest::Ping { .. }),
));
}
#[test]
fn id_absent_is_notification() {
let frame = serde_json::json!({
"jsonrpc": "2.0",
"method": "notifications/initialized",
});
let parsed: JsonRpcClientMessage =
serde_json::from_str(&frame.to_string()).unwrap();
assert!(matches!(
parsed,
JsonRpcClientMessage::Notification(
JsonRpcClientNotification::Initialized { .. },
),
));
}
#[test]
fn null_id_is_notification() {
let frame = serde_json::json!({
"jsonrpc": "2.0",
"id": null,
"method": "ping",
});
let parsed: JsonRpcClientMessage =
serde_json::from_str(&frame.to_string()).unwrap();
assert!(matches!(
parsed,
JsonRpcClientMessage::Notification(
JsonRpcClientNotification::Fallback {
method: ClientNotificationMethod::Other(method),
..
},
) if method == "ping",
));
}
#[test]
fn bad_cancelled_params_is_ignorable_notification() {
let frame = serde_json::json!({
"jsonrpc": "2.0",
"method": "notifications/cancelled",
"params": {"requestId": {"bad": true}},
});
let parsed: JsonRpcClientMessage =
serde_json::from_str(&frame.to_string()).unwrap();
assert!(matches!(
parsed,
JsonRpcClientMessage::Notification(
JsonRpcClientNotification::Fallback {
method: ClientNotificationMethod::Cancelled(_),
..
},
),
));
}
#[test]
fn bad_params_request_keeps_id() {
let frame = serde_json::json!({
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {"no_name": true},
});
let parsed: JsonRpcClientMessage =
serde_json::from_str(&frame.to_string()).unwrap();
let JsonRpcClientMessage::Request(JsonRpcRequest::Fallback {
id,
method: ClientRequestMethod::CallTool(_),
..
}) = parsed
else {
panic!("expected Request(Fallback with CallTool marker)");
};
assert_eq!(id, super::super::RequestId::Number(6.into()));
}
}