Files
crank/crates/crank-community-mcp/src/jsonrpc.rs
T
bsodfather 1b51d44121
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 30m13s
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
refactor(mcp): serialize success and error envelopes through SDK
2026-11-12 07:52:03 +00:00

215 lines
7.9 KiB
Rust

use rmcp::model::{
ErrorCode, ErrorData, JsonRpcError, JsonRpcResponse, JsonRpcVersion2_0, RequestId,
};
use serde_json::{Value, json};
/// The two approved MCP revisions (`docs/`-approved window of 2026-10-11).
pub const MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
pub const LEGACY_PROTOCOL_VERSION: &str = "2025-11-25";
/// Revisions that stay in the code base but are no longer advertised or served.
pub const WITHDRAWN_PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26"];
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] =
&[MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION];
/// Backwards-compatible name for the legacy session revision, kept because existing in-crate tests
/// and call sites refer to it. It is *not* an implicit default for an unidentified request.
pub const CURRENT_PROTOCOL_VERSION: &str = LEGACY_PROTOCOL_VERSION;
/// Request `_meta` keys used by the modern stateless era.
pub const META_PROTOCOL_VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";
pub const META_CLIENT_CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";
pub const META_CLIENT_INFO_KEY: &str = "io.modelcontextprotocol/clientInfo";
/// `_meta` key of the per-request log level (Story 3.18). SEP-2577 replaces the former
/// `logging/setLevel` request of the legacy era with this per-request opt-in.
pub const META_LOG_LEVEL_KEY: &str = "io.modelcontextprotocol/logLevel";
/// Result `_meta` key carrying the self-reported server identity (pinned `DiscoverResult`).
pub const META_SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo";
/// JSON-RPC error codes of the pinned modern revision.
pub const HEADER_MISMATCH_ERROR_CODE: i64 = -32020;
pub const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: i64 = -32022;
/// Header name carrying the negotiated revision on HTTP requests.
pub const HEADER_PROTOCOL_VERSION_NAME: &str = "MCP-Protocol-Version";
pub fn request_id(message: &Value) -> Value {
message.get("id").cloned().unwrap_or(Value::Null)
}
pub fn method_name(message: &Value) -> Option<&str> {
message.get("method").and_then(Value::as_str)
}
pub fn params(message: &Value) -> Value {
message
.get("params")
.cloned()
.unwrap_or_else(|| Value::Object(Default::default()))
}
pub fn is_notification(message: &Value) -> bool {
method_name(message).is_some() && message.get("id").is_none()
}
pub fn is_request(message: &Value) -> bool {
method_name(message).is_some() && message.get("id").is_some()
}
pub fn is_response(message: &Value) -> bool {
method_name(message).is_none()
&& (message.get("result").is_some() || message.get("error").is_some())
}
fn projected_sdk_id(id: &Value) -> RequestId {
match id {
Value::String(value) => RequestId::String(value.as_str().into()),
Value::Number(value) => RequestId::Number(value.as_i64().unwrap_or(0)),
_ => RequestId::Number(0),
}
}
pub fn jsonrpc_result(id: Value, result: Value) -> Value {
let sdk = JsonRpcResponse::<Value> {
jsonrpc: JsonRpcVersion2_0,
id: projected_sdk_id(&id),
result,
};
let mut wire = serde_json::to_value(sdk).expect("SDK response contains only JSON values");
#[cfg(test)]
crate::app::dispatch_observer::sdk_jsonrpc_response_serialized();
// SDK RequestId cannot preserve the full Value domain or floating-point form.
wire["id"] = id;
wire
}
pub fn jsonrpc_error(id: Value, code: i64, message: impl Into<String>) -> Value {
let (request_id, trace_id) = crank_observability::current_request_correlation();
let data = if request_id.is_some() && trace_id.is_some() {
Some(correlated_error_data(json!({})))
} else {
None
};
let sdk = JsonRpcError::new(
Some(projected_sdk_id(&id)),
ErrorData::new(
ErrorCode(i32::try_from(code).unwrap_or(0)),
message.into(),
data,
),
);
let mut wire = serde_json::to_value(sdk).expect("SDK error contains only JSON values");
#[cfg(test)]
crate::app::dispatch_observer::sdk_jsonrpc_error_serialized();
// Restore the helper's wider id/code contract before exposing the SDK envelope.
wire["id"] = id;
wire["error"]["code"] = Value::from(code);
wire
}
pub fn correlated_error_data(mut data: Value) -> Value {
if !data.is_object() {
data = json!({});
}
let (request_id, trace_id) = crank_observability::current_request_correlation();
if let Some(request_id) = request_id {
data["request_id"] = Value::String(request_id);
}
if let Some(trace_id) = trace_id {
data["trace_id"] = Value::String(trace_id);
}
data
}
pub fn negotiated_protocol_version(requested: &str) -> Option<&'static str> {
SUPPORTED_PROTOCOL_VERSIONS
.iter()
.copied()
.find(|version| *version == requested)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jsonrpc_preserves_helper_values_and_numeric_forms() {
let values = [
json!(""),
json!("Юникод"),
json!(i64::MIN),
json!(i64::MAX),
json!(9007199254740993_u64),
json!(u64::MAX),
json!(1.5),
json!(1.0),
json!(-0.0),
Value::Null,
json!(true),
json!([null, u64::MAX]),
json!({"extension": {"nested": null}}),
];
for id in &values {
for result in &values {
let actual = jsonrpc_result(id.clone(), result.clone());
let expected = json!({"jsonrpc": "2.0", "id": id, "result": result});
assert_eq!(actual, expected);
assert_eq!(actual.to_string(), expected.to_string());
}
for code in [
i64::MIN,
i64::from(i32::MIN) - 1,
i64::from(i32::MIN),
-32602,
0,
i64::from(i32::MAX),
i64::from(i32::MAX) + 1,
i64::MAX,
] {
for message in ["", "Ошибка Ю"] {
let actual = jsonrpc_error(id.clone(), code, message);
let expected = json!({"jsonrpc": "2.0", "id": id,
"error": {"code": code, "message": message}});
assert_eq!(actual, expected);
assert_eq!(actual.to_string(), expected.to_string());
}
}
}
}
#[tokio::test]
async fn jsonrpc_error_requires_complete_valid_correlation() {
use crank_observability::{current_request_correlation, with_request_correlation};
let request_id = "request-123";
let trace_id = "1234567890abcdef1234567890abcdef";
for (request, trace) in [("", ""), (request_id, ""), ("", trace_id)] {
with_request_correlation(request.into(), trace.into(), async {
assert_eq!(current_request_correlation(), (None, None));
assert_eq!(
jsonrpc_error(Value::Null, -32602, "error"),
json!({"jsonrpc": "2.0", "id": null,
"error": {"code": -32602, "message": "error"}})
);
})
.await;
}
with_request_correlation(request_id.into(), trace_id.into(), async {
assert_eq!(
jsonrpc_error(Value::Null, i64::MAX, "Ошибка"),
json!({"jsonrpc": "2.0", "id": null, "error": {
"code": i64::MAX, "message": "Ошибка",
"data": {"request_id": request_id, "trace_id": trace_id}}})
);
assert_eq!(
correlated_error_data(json!({"extension": [null, u64::MAX]})),
json!({"extension": [null, u64::MAX],
"request_id": request_id, "trace_id": trace_id})
);
})
.await;
assert_eq!(current_request_correlation(), (None, None));
}
}