Files
crank/crates/crank-community-mcp/src/protocol/mod.rs
T
bsodfather 65144fd8c6
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
MCP: classify inbound responses through SDK with fresh authorization
2026-11-13 00:41:28 +00:00

811 lines
34 KiB
Rust

//! Era resolution and the small static server-capability registration for the MCP endpoint.
//!
//! Scope: exactly two approved revisions — `2026-07-28` (modern stateless) and `2025-11-25` (legacy
//! session). Withdrawn revisions (`2025-06-18`, `2025-03-26`) are rejected safely and are never an
//! implicit identity. There is no command bus, plugin surface or experimental configuration here: a
//! single registration source feeds the advertised capability descriptor.
use std::sync::OnceLock;
use axum::{
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use serde::Deserialize as _;
use serde_json::{Value, json};
use crate::jsonrpc::{
HEADER_MISMATCH_ERROR_CODE, LEGACY_PROTOCOL_VERSION, META_CLIENT_CAPABILITIES_KEY,
META_CLIENT_INFO_KEY, META_PROTOCOL_VERSION_KEY, MODERN_PROTOCOL_VERSION,
SUPPORTED_PROTOCOL_VERSIONS, UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE, correlated_error_data,
jsonrpc_error, method_name, params, request_id,
};
use crate::session::SessionState;
use crate::transport::{json_response, protocol_version_from_headers, singleton_header};
mod command;
mod completion;
mod dispatch_sdk;
mod lifecycle_sdk;
mod logging;
mod prompts;
mod registry;
mod resources;
mod response_sdk;
mod signals;
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
pub(crate) use command::{
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
ToolsListCommand, ToolsOutcome, handle_tools_command,
};
pub(crate) use completion::{
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
handle_completion_command,
};
pub(crate) use lifecycle_sdk::{
discover_result, initialize_params, initialize_result, initialized_notification, ping_result,
};
pub(crate) use logging::{
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
in_carried_scope, modern_request_level, note, scoped as logging_scope, set_active_level,
set_sse_acceptable, take_notifications,
};
pub(crate) use prompts::{
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
};
pub(crate) use resources::{
ResourceReadCommand, ResourceTemplatesListError, ResourcesCommand, ResourcesListCommand,
ResourcesOutcome, handle_resources_command, list_resource_templates,
};
pub(crate) use signals::{
FilterOutcome, INVALID_LISTEN_FILTER, ListenParams, Signals, StreamRegistry, Watch, Wire,
acknowledged_frame, frames_stream, spawn as spawn_signal_watch, subscription_id,
};
/// Resolved era of an incoming POST request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RequestEra {
Modern,
Legacy,
}
/// Envelope class of an incoming POST message, decided by the single JSON-RPC envelope guard.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EnvelopeKind {
/// A request: `method` plus a valid request id.
Request,
/// A notification: `method` without an id.
Notification,
/// A response to a server-initiated request: no `method`, a `result` or `error`.
Response,
}
/// The JSON-RPC literal that every message on both eras must carry.
const JSONRPC_VERSION: &str = "2.0";
/// The pinned modern schema types a request id as `RequestId = string | number`.
fn is_valid_request_id(id: &Value) -> bool {
id.is_string() || id.is_number()
}
/// Pinned modern wire projection of a success result.
///
/// `JSONRPCResultResponse.result` is a `Result`, and this revision requires the `resultType` member
/// ("Servers implementing this protocol version MUST include this field"). Every result this server
/// produces is a synchronous, fully computed result, so the value is `complete`. The projection is a
/// no-op for the legacy revision, whose earlier schema has no such member, and it only ever adds the
/// required member — the business payload is passed through untouched.
pub(crate) fn project_modern_result(protocol_version: &str, result: Value) -> Value {
if protocol_version != MODERN_PROTOCOL_VERSION {
return result;
}
let Value::Object(mut object) = result else {
return result;
};
object
.entry("resultType".to_owned())
.or_insert_with(|| Value::String("complete".to_owned()));
Value::Object(object)
}
/// The same projection for a result that extends `CacheableResult` (`tools/list`): the pinned schema
/// makes `ttlMs` and `cacheScope` mandatory there as well. No cache policy exists for this slice, so the
/// conservative and honest hints are `0` (immediately stale) and `private` (scoped to the authorized
/// agent); this adds no caching framework.
pub(crate) fn project_modern_cacheable_result(protocol_version: &str, result: Value) -> Value {
let result = project_modern_result(protocol_version, result);
if protocol_version != MODERN_PROTOCOL_VERSION {
return result;
}
let Value::Object(mut object) = result else {
return result;
};
object.entry("ttlMs".to_owned()).or_insert_with(|| json!(0));
object
.entry("cacheScope".to_owned())
.or_insert_with(|| Value::String("private".to_owned()));
Value::Object(object)
}
/// Minimal `serde` helper for a field the advertised schema types as an **object**: a JSON object is
/// accepted as is, while a missing key, `null`, an array or a scalar is a deserialization error. It is
/// the shared shape check for the tool-call parameter objects (the top-level `arguments` of `tools/call`
/// and the nested `arguments` of the `call_tool` proxy), so both eras reject the same invalid shapes
/// before any approval or outbound work.
pub(crate) fn deserialize_object_only<'de, D>(deserializer: D) -> Result<Value, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
match value {
Value::Object(map) => Ok(Value::Object(map)),
other => Err(serde::de::Error::custom(format!(
"`arguments` must be an object, got {}",
json_type_name(&other)
))),
}
}
pub(crate) fn json_type_name(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
/// `400` + `-32600`. JSON-RPC requires the response id to be null for an invalid request, so a value
/// that could not be validated is never echoed back.
fn invalid_request_response() -> Response {
let error = jsonrpc_error(Value::Null, -32600, "invalid JSON-RPC request".to_owned());
json_response(StatusCode::BAD_REQUEST, error, None, None)
}
/// The response id for a message whose JSON-RPC envelope has **not** necessarily been validated yet.
///
/// The session-carrier projections (`ambiguous_session_carrier_response`,
/// `malformed_carrier_response`) reject a request for its carrier and therefore run *before* the
/// single envelope guard, so the body id they read may still be an invalid kind
/// (`object`/`boolean`/`array`). JSON-RPC requires the response id to be null whenever the request
/// could not be validated — the same convention `invalid_request_response` uses — so an id that is
/// not a `RequestId` is never echoed back. A valid `string`/`number` id is preserved unchanged, an
/// absent id stays null, and this changes nothing for a caller that already passed the guard (such a
/// message can only carry a valid id or none at all).
fn safe_response_id(message: &Value) -> Value {
let id = request_id(message);
if is_valid_request_id(&id) {
id
} else {
Value::Null
}
}
/// The one JSON-RPC envelope guard: the body must be a well-formed JSON-RPC message before any era
/// resolution, dispatch, approval or outbound request happens. JSON extraction succeeding only proves
/// the body was syntactically valid JSON, which is a different property from envelope validity.
pub(crate) fn validate_jsonrpc_envelope(message: &Value) -> Result<EnvelopeKind, Rejection> {
let Some(object) = message.as_object() else {
return Err(rejected(invalid_request_response()));
};
match object.get("jsonrpc") {
Some(Value::String(version)) if version == JSONRPC_VERSION => {}
_ => return Err(rejected(invalid_request_response())),
}
match object.get("method") {
Some(Value::String(method)) if !method.trim().is_empty() => {
if let Some(Value::Object(_)) | None = object.get("params") {
} else {
return Err(rejected(invalid_request_response()));
}
match object.get("id") {
None => Ok(EnvelopeKind::Notification),
Some(id) if is_valid_request_id(id) => Ok(EnvelopeKind::Request),
// A present but invalid id is neither a valid request nor a notification: it must
// never be acknowledged as one.
Some(_) => Err(rejected(invalid_request_response())),
}
}
Some(_) => Err(rejected(invalid_request_response())),
None => match response_sdk::classify_response(message) {
Some(kind) => Ok(kind),
None => Err(rejected(invalid_request_response())),
},
}
}
/// A live transport session is operational only under the supported legacy revision.
///
/// Sessions are persisted, so a session created under a withdrawn revision can still be found in the
/// store. It must be rejected with a safe error instead of being served as a live legacy session,
/// even when the request carries no version header.
pub(crate) fn validate_session_revision(session: &SessionState) -> Result<(), StatusCode> {
if session.protocol_version == LEGACY_PROTOCOL_VERSION {
Ok(())
} else {
Err(StatusCode::BAD_REQUEST)
}
}
/// Admit the session-lifecycle HTTP methods (`GET`/`DELETE`) only for the legacy era.
///
/// The modern revision removed the standalone GET stream endpoint and is stateless, so an explicit
/// modern identity answers `405` instead of reaching the legacy session lifecycle. An unknown,
/// withdrawn or unreadable revision is a safe admission error. Only a verified legacy session — a
/// legacy revision header, or no header at all with the identity taken from the session itself — may
/// continue into the session branch.
pub(crate) fn session_lifecycle_admission(headers: &HeaderMap) -> Result<(), Rejection> {
match protocol_version_from_headers(headers) {
Err(status) => Err(rejected(status.into_response())),
Ok(None) => Ok(()),
Ok(Some(version)) if version == LEGACY_PROTOCOL_VERSION => Ok(()),
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION => {
Err(rejected(StatusCode::METHOD_NOT_ALLOWED.into_response()))
}
Ok(Some(_)) => Err(rejected(StatusCode::BAD_REQUEST.into_response())),
}
}
/// Identity resolved from the request before any method dispatch.
#[derive(Clone, Debug)]
pub(crate) struct RequestIdentity {
pub(crate) era: RequestEra,
/// Negotiated revision when the request itself carries one (modern requests and legacy
/// `initialize`). Legacy subsequent requests identify the revision through their session instead.
pub(crate) version: Option<String>,
}
/// Ready-made rejection, boxed because a response is much larger than the identity it replaces.
type Rejection = Box<Response>;
fn rejected(response: Response) -> Rejection {
Box::new(response)
}
/// The one registration source for the advertised server capabilities, indexed by the revision the
/// caller serves. Advertisement equals what is implemented: later capabilities are added to the
/// static registration by their owning story, not pre-declared here. Both the modern
/// `discover_result` and the legacy `handle_initialize` pass the revision they serve, so a
/// single-era declaration never leaks into the other era (R6).
pub(crate) fn advertised_server_capabilities(revision: &str) -> Value {
request_registration().map_or_else(
|| Value::Object(serde_json::Map::new()),
|registration| registration.registry().advertised_capabilities(revision),
)
}
pub(crate) use registry::{CapabilityRegistry, DispatchDecision, Kind, MethodHandler};
/// The descriptor vocabulary and tables of the static registration, re-exported for the
/// BUILD-internal registration test seam (spec sections 6.3/7.2): the in-crate observer tests add one
/// inert private descriptor to a copy of these tables and prove that the real dispatch and
/// advertisement move with it. The production registration itself is unchanged.
#[cfg(test)]
pub(crate) use registry::{
CAPABILITY_DESCRIPTORS, CapabilityId, CapabilityIdDescriptor, FeatureSet, HeaderSet,
METHOD_DESCRIPTORS, MethodDescriptor, Roster,
};
/// The one owning registration of this endpoint (R5/D-3), held by the protocol layer both era
/// adapters go through.
///
/// The snapshot is validated once and then reused, so dispatch and advertisement are derived from
/// the *same* registration and cannot drift; the adapters keep no method list of their own. An
/// invalid static table registers nothing at all (fail-closed): every dispatch is refused instead of
/// being served from a table that contradicts itself. The table itself is proven valid by
/// `protocol::registry::tests::`.
static CAPABILITY_REGISTRY: OnceLock<Option<CapabilityRegistry>> = OnceLock::new();
/// The validated registration snapshot of this endpoint.
pub(crate) fn capability_registry() -> Option<&'static CapabilityRegistry> {
CAPABILITY_REGISTRY
.get_or_init(|| {
CapabilityRegistry::new(
registry::CAPABILITY_DESCRIPTORS,
registry::METHOD_DESCRIPTORS,
)
.ok()
})
.as_ref()
}
/// The registration a request is served with: the production snapshot, unless the in-crate observer
/// test installed one for this request (`app::dispatch_observer`, `#[cfg(test)]` only). The seam
/// exists so the add/remove proof runs against the *real* router instead of a registry unit query.
fn request_registration() -> Option<RegistrationHandle> {
#[cfg(test)]
if let Some(registration) = crate::app::dispatch_observer::installed_registration() {
return Some(RegistrationHandle::Test(registration));
}
capability_registry().map(RegistrationHandle::Production)
}
enum RegistrationHandle {
Production(&'static CapabilityRegistry),
#[cfg(test)]
Test(std::sync::Arc<CapabilityRegistry>),
}
impl RegistrationHandle {
fn registry(&self) -> &CapabilityRegistry {
match self {
Self::Production(registration) => registration,
#[cfg(test)]
Self::Test(registration) => registration,
}
}
}
/// The registration-backed dispatch entry point shared by both era adapters (R5/D-3).
///
/// A method no descriptor owns has no handler, and a method whose owning capability is not eligible
/// in the requested revision is a wrong-era request: neither can reach a service or make an outbound
/// call, because both adapters dispatch on this decision.
pub(crate) fn dispatch_decision(method: &str, revision: &str) -> DispatchDecision {
request_registration().map_or(DispatchDecision::Unregistered, |registration| {
registration.registry().dispatch_decision(method, revision)
})
}
fn error_response(message: &Value, code: i64, text: String) -> Response {
json_response(
StatusCode::BAD_REQUEST,
jsonrpc_error(safe_response_id(message), code, text),
None,
None,
)
}
/// Header carrying the invoked method on modern HTTP requests (required for every modern request).
pub(crate) const HEADER_MCP_METHOD: &str = "Mcp-Method";
/// Declared `Mcp-Method` value of a modern request.
///
/// Conflicting duplicate values are an ambiguous method declaration and are rejected as a header
/// mismatch instead of resolving to the first value; identical duplicates collapse to one value.
pub(crate) fn declared_mcp_method<'a>(
headers: &'a HeaderMap,
message: &Value,
) -> Result<Option<&'a str>, Rejection> {
singleton_header(headers, HEADER_MCP_METHOD)
.map_err(|_| rejected(modern_header_mismatch_response(message)))
}
/// Header carrying `params.name` on modern `tools/call` requests.
pub(crate) const HEADER_MCP_NAME: &str = "Mcp-Name";
const BASE64_SENTINEL_PREFIX: &str = "=?base64?";
const BASE64_SENTINEL_SUFFIX: &str = "?=";
/// `400` + `-32020` for a modern request whose declared method header is missing or mismatched.
pub(crate) fn modern_header_mismatch_response(message: &Value) -> Response {
header_mismatch_response(message, "`Mcp-Method` must match the invoked method")
}
/// `400` + `-32020` for a modern request that carries a session header. The modern revision is
/// stateless, so a session carrier is a conflicting identity — it is rejected before any session
/// lookup, rate-limit accounting or dispatch, and it is never silently ignored.
pub(crate) fn modern_carrier_conflict_response(message: &Value) -> Response {
header_mismatch_response(
message,
"the negotiated revision is stateless and does not accept a session header",
)
}
/// `202 Accepted` with no body: a notification carries no `id`, so nothing is dispatched.
pub(crate) fn modern_notification_response() -> Response {
StatusCode::ACCEPTED.into_response()
}
/// Era-correct answer for a method that the modern era does not implement.
pub(crate) fn modern_method_not_found_response(message: &Value) -> Response {
json_response(
StatusCode::NOT_FOUND,
jsonrpc_error(
request_id(message),
-32601,
"method not found for the negotiated revision".to_owned(),
),
None,
None,
)
}
/// Decode a modern header value: the pinned sentinel `=?base64?…?=` is decoded, anything else is
/// taken literally. An unreadable sentinel value yields `None` and is rejected as a mismatch.
fn decode_header_value(raw: &str) -> Option<String> {
let Some(encoded) = raw.strip_prefix(BASE64_SENTINEL_PREFIX) else {
return Some(raw.to_owned());
};
let encoded = encoded.strip_suffix(BASE64_SENTINEL_SUFFIX)?;
let bytes = STANDARD.decode(encoded).ok()?;
String::from_utf8(bytes).ok()
}
/// Validate the required `Mcp-Name` header against the body value.
///
/// Pinned modern rules: the header is required for `tools/call`, the sentinel-encoded form must be
/// decoded before the comparison, and the comparison is case-sensitive.
pub(crate) fn validate_modern_request_name(
message: &Value,
headers: &HeaderMap,
body_name: &str,
) -> Result<(), Rejection> {
let Some(raw) = singleton_header(headers, HEADER_MCP_NAME)
.map_err(|_| header_mismatch_response(message, "the `Mcp-Name` header is ambiguous"))?
else {
return Err(rejected(header_mismatch_response(
message,
"the required `Mcp-Name` header is missing",
)));
};
let Some(decoded) = decode_header_value(raw) else {
return Err(rejected(header_mismatch_response(
message,
"the `Mcp-Name` header value cannot be decoded",
)));
};
if decoded != body_name {
return Err(rejected(header_mismatch_response(
message,
&format!(
"the `Mcp-Name` header value '{decoded}' does not match the body value '{body_name}'"
),
)));
}
Ok(())
}
fn unsupported_version_response(message: &Value, requested: &str) -> Response {
let supported: Vec<&str> = SUPPORTED_PROTOCOL_VERSIONS.to_vec();
let mut error = jsonrpc_error(
request_id(message),
UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE,
format!("unsupported protocol version {requested}"),
);
error["error"]["data"] = correlated_error_data(json!({
"requested": requested,
"supported": supported,
}));
json_response(StatusCode::BAD_REQUEST, error, None, None)
}
fn header_mismatch_response(message: &Value, details: &str) -> Response {
let mut error = jsonrpc_error(
safe_response_id(message),
HEADER_MISMATCH_ERROR_CODE,
"protocol identity mismatch".to_owned(),
);
// Merge into the correlation data instead of replacing it: the request/trace correlation that
// `jsonrpc_error` already attached must survive the added detail.
error["error"]["data"] = correlated_error_data(json!({ "details": details }));
json_response(StatusCode::BAD_REQUEST, error, None, None)
}
/// Era-correct structured rejection for a malformed or ambiguous `MCP-Protocol-Version` carrier
/// (`protocol-era-matrix.md` row 17).
///
/// The carrier is exactly what failed to parse, so it cannot identify the era. The era is read from
/// the rest of the request instead: a request carrying a modern identity marker is answered in the
/// modern shape (`400` + `-32020` `HeaderMismatch`), anything else stays legacy and is answered with
/// the legacy-shaped structured error. A malformed carrier is never re-labelled as a modern
/// unsupported-revision answer (`-32022` is reserved for a well-formed but unknown *effective*
/// identity), and no era is guessed from the malformed value itself.
fn malformed_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
const DETAILS: &str = "the `MCP-Protocol-Version` header value is malformed or ambiguous";
if declares_modern_identity(headers, message) {
header_mismatch_response(message, DETAILS)
} else {
error_response(message, -32602, DETAILS.to_owned())
}
}
/// Era-correct structured rejection for an ambiguous `MCP-Session-Id` carrier (matrix row 17).
///
/// A conflicting duplicate session carrier cannot identify the era, exactly like a malformed
/// version carrier, and the callers that read it (`GET`/`DELETE`/`POST`) currently answer a bare
/// `400` with an empty body. For a POST that carries a JSON-RPC envelope the request must instead be
/// answered with the era-correct structured diagnostic: the era is read from the **non-ambiguous**
/// part of the request, never guessed from (or resolved to) one of the conflicting values.
///
/// The session-lifecycle methods keep their own admission path (`GET`/`DELETE` stay HTTP) and never
/// reach this projection.
pub(crate) fn ambiguous_session_carrier_response(headers: &HeaderMap, message: &Value) -> Response {
const DETAILS: &str = "the `MCP-Session-Id` header value is ambiguous";
if declares_modern_identity(headers, message) {
header_mismatch_response(message, DETAILS)
} else {
error_response(message, -32602, DETAILS.to_owned())
}
}
/// Whether the non-carrier part of the request identifies the modern era.
///
/// Used only to pick the era-correct shape for a carrier diagnostic, never to admit a request. Any
/// one of these markers is enough, because each is unambiguous on its own:
/// - an unambiguously present, supported modern `MCP-Protocol-Version` header — a modern header never
/// routes the request into the legacy branch (matrix row 3). A conflicting duplicate or an
/// unreadable value resolves to `Err` and therefore cannot choose the era by one of its values
/// (row 17);
/// - the `Mcp-Method` request header (required by every modern request, absent on a legacy one);
/// - a request-scoped `_meta` client identity (with or without its version field).
fn declares_modern_identity(headers: &HeaderMap, message: &Value) -> bool {
if matches!(
protocol_version_from_headers(headers),
Ok(Some(version)) if version == MODERN_PROTOCOL_VERSION
) {
return true;
}
if singleton_header(headers, HEADER_MCP_METHOD)
.ok()
.flatten()
.is_some()
{
return true;
}
let params = params(message);
let meta = params.get("_meta");
declares_modern_metadata(meta)
|| matches!(meta, Some(Value::Object(meta)) if meta.contains_key(META_PROTOCOL_VERSION_KEY))
}
/// Whether a request `_meta` object carries a modern-specific client identity key.
///
/// Used to recognise a modern identity that is missing its required version carrier (matrix row 4)
/// and to pick the era-correct shape for a carrier diagnostic. It never admits a request: a modern
/// identity still requires the version header and the complete request-scoped metadata.
fn declares_modern_metadata(meta: Option<&Value>) -> bool {
let Some(Value::Object(meta)) = meta else {
return false;
};
[META_CLIENT_CAPABILITIES_KEY, META_CLIENT_INFO_KEY]
.iter()
.any(|key| meta.contains_key(*key))
}
/// The modern era requires the full per-request client identity in `params._meta`:
/// `protocolVersion` (string), `clientCapabilities` (object) and `clientInfo` (object with a
/// non-empty `name` and `version`). Every failure is a header/metadata mismatch (`-32020`).
fn validate_modern_metadata(meta: Option<&Value>, message: &Value) -> Result<(), Rejection> {
let Some(Value::Object(meta)) = meta else {
return Err(rejected(header_mismatch_response(
message,
"modern requests require request `_meta` metadata",
)));
};
match meta.get(META_PROTOCOL_VERSION_KEY) {
Some(Value::String(version)) if version == MODERN_PROTOCOL_VERSION => {}
Some(Value::String(_)) | None => {
return Err(rejected(header_mismatch_response(
message,
"modern requests require `_meta` protocolVersion",
)));
}
Some(_) => {
return Err(rejected(header_mismatch_response(
message,
"body protocol version must be a string",
)));
}
}
if !meta
.get(META_CLIENT_CAPABILITIES_KEY)
.is_some_and(Value::is_object)
{
return Err(rejected(header_mismatch_response(
message,
"modern requests require request `_meta` client capabilities",
)));
}
// `clientInfo` is **optional** in the pinned `RequestMetaObject` (a client SHOULD send it, but an
// absent value is valid), so an omitted value is accepted. A value that **is** present must still
// satisfy its `Implementation` shape: an object with a non-empty `name` and `version`. The two
// required metadata carriers above are not weakened by this.
if let Some(client_info) = meta.get(META_CLIENT_INFO_KEY) {
let Some(client_info) = client_info.as_object() else {
return Err(rejected(header_mismatch_response(
message,
"modern request `_meta` clientInfo must be an object",
)));
};
for key in ["name", "version"] {
let present = client_info
.get(key)
.and_then(Value::as_str)
.is_some_and(|value| !value.trim().is_empty());
if !present {
return Err(rejected(header_mismatch_response(
message,
"modern requests require `_meta` clientInfo name and version",
)));
}
}
}
Ok(())
}
/// Resolve the era and the request identity.
///
/// Rules (binding precedence rows of `protocol-era-matrix.md`):
/// - header and body identity present but different → `-32020` (mismatch takes precedence);
/// - a modern identity requires the version header and the full body `_meta` client identity,
/// otherwise `-32020`;
/// - an unknown or withdrawn identity → `-32022` with the supported list (never an implicit default),
/// except on a session-based `initialize`, which is answered legacy-shaped;
/// - `initialize` belongs to the legacy session era only: a modern revision in its parameters is
/// rejected instead of minting a session;
/// - a legacy `initialize` body version outside the approved window → rejected without minting a
/// session and without echoing a withdrawn revision as the served identity;
/// - `_meta` that already carries a modern-specific client identity key without any version carrier →
/// `-32020` header validation failure, never a legacy admission;
/// - no identity at all stays "no identity": the legacy session path decides, and nothing is guessed.
pub(crate) fn resolve_request_identity(
headers: &HeaderMap,
message: &Value,
) -> Result<RequestIdentity, Rejection> {
let header_version = match protocol_version_from_headers(headers) {
Ok(version) => version,
// A conflicting duplicate carrier or an unreadable value means the request names no usable
// revision; a present-but-blank value is the same class. Matrix row 17 requires the
// era-correct structured diagnostic for that class instead of a bare `400`, and the epoch
// cannot be read from the malformed value itself — only from the rest of the request.
Err(_) => return Err(rejected(malformed_carrier_response(headers, message))),
};
if let Some(version) = header_version.as_deref()
&& version.trim().is_empty()
{
return Err(rejected(malformed_carrier_response(headers, message)));
}
let body_params = params(message);
let meta = body_params.get("_meta");
let meta_version = match meta {
Some(Value::Object(meta)) => match meta.get(META_PROTOCOL_VERSION_KEY) {
Some(Value::String(version)) => Some(version.clone()),
Some(_) => {
return Err(rejected(header_mismatch_response(
message,
"body protocol version must be a string",
)));
}
None => None,
},
Some(_) => {
return Err(rejected(header_mismatch_response(
message,
"request _meta must be an object",
)));
}
None => None,
};
if let (Some(header), Some(meta_version)) = (header_version.as_deref(), meta_version.as_deref())
&& header != meta_version
{
return Err(rejected(header_mismatch_response(
message,
"header and body protocol versions differ",
)));
}
// `initialize` mints a session, and only the legacy revision is session-based. A modern revision
// here is rejected before any session is created, whichever carrier declares it.
if matches!(method_name(message), Some("initialize"))
&& body_params
.get("protocolVersion")
.and_then(Value::as_str)
.is_some_and(|requested| requested == MODERN_PROTOCOL_VERSION)
{
return Err(rejected(error_response(
message,
-32602,
format!(
"revision {MODERN_PROTOCOL_VERSION} is not a session-based revision; it does not use initialize"
),
)));
}
let effective = header_version.clone().or_else(|| meta_version.clone());
// `_meta` that already names a modern-specific client identity key is a modern request whose
// required version carrier is missing, not a legacy request: admitting it as legacy would
// execute it through the legacy session path (matrix row 4). This condition is independent of
// whatever version the request header names — an explicit legacy version header does not turn
// such a request into a legacy admission (matrix row 16, mixed carriers are rejected for the era
// identified by the dominant carrier) — so the guard runs before the effective identity is
// matched and is a header-validation failure before any adapter or session admission.
if meta_version.is_none() && declares_modern_metadata(meta) {
return Err(rejected(header_mismatch_response(
message,
"modern requests require `_meta` protocolVersion",
)));
}
let Some(effective) = effective else {
if matches!(method_name(message), Some("initialize")) {
let requested = body_params
.get("protocolVersion")
.and_then(Value::as_str)
.unwrap_or_default();
if crate::jsonrpc::negotiated_protocol_version(requested).is_none() {
return Err(rejected(error_response(
message,
-32602,
format!("unsupported protocol version {requested}"),
)));
}
return Ok(RequestIdentity {
era: RequestEra::Legacy,
version: Some(requested.to_owned()),
});
}
return Ok(RequestIdentity {
era: RequestEra::Legacy,
version: None,
});
};
match effective.as_str() {
MODERN_PROTOCOL_VERSION => {
// The modern era negotiates per request: the version header is required, and the body
// metadata must carry the complete request-scoped client identity.
if header_version.is_none() {
return Err(rejected(header_mismatch_response(
message,
"modern requests require the negotiated protocol version header",
)));
}
validate_modern_metadata(meta, message)?;
Ok(RequestIdentity {
era: RequestEra::Modern,
version: Some(MODERN_PROTOCOL_VERSION.to_owned()),
})
}
LEGACY_PROTOCOL_VERSION => Ok(RequestIdentity {
era: RequestEra::Legacy,
version: Some(LEGACY_PROTOCOL_VERSION.to_owned()),
}),
// A legacy `initialize` negotiates its revision through `params.protocolVersion` and is
// rejected **legacy-shaped**: the modern `-32022` contract describes a modern per-request
// identity and must not be imposed on the session-based era (matrix row 14). The rejected
// revision is still never served, echoed or minted, and no exact legacy code is invented —
// this is the same answer the header-less `initialize` already receives.
other => {
if matches!(method_name(message), Some("initialize")) {
return Err(rejected(error_response(
message,
-32602,
format!("unsupported protocol version {other}"),
)));
}
Err(rejected(unsupported_version_response(message, other)))
}
}
}