Files
crank/crates/crank-community-mcp/src/jsonrpc.rs
T
bsodfather a438c1df42
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
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) Failing after 1s
CI / Deploy (pull_request) Skipped
feat(epic3): безопасное structured logging MCP (Story 3.18)
Story 3.18 (#25) surface: клиент получает только закрытые structured
`notifications/message` выбранного уровня, без запросов, секретов и
internal causes.

- `logging` capability advertising в обеих поддерживаемых revisions;
  `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request);
- закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним
  safe detail; закрытый набор safe events, task-local request scope;
  bounded in-memory opt-in, без миграций;
- `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт;
- ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3),
  protocol::logging unit (12);
- проекция capability inventory/frozen oracle переведена на `logging`.

Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy,
python oracle 56 OK, capability inventory valid). Полный `just verify` —
NOT_RUN на story по validation-policy, остаётся на собранной фиче.
2026-10-25 12:50:00 +00:00

107 lines
3.7 KiB
Rust

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())
}
pub fn jsonrpc_result(id: Value, result: Value) -> Value {
json!({
"jsonrpc": "2.0",
"id": id,
"result": result
})
}
pub fn jsonrpc_error(id: Value, code: i64, message: impl Into<String>) -> Value {
let mut error = json!({
"code": code,
"message": message.into()
});
let (request_id, trace_id) = crank_observability::current_request_correlation();
if request_id.is_some() && trace_id.is_some() {
error["data"] = correlated_error_data(json!({}));
}
json!({
"jsonrpc": "2.0",
"id": id,
"error": error
})
}
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)
}