Compare commits

...
Author SHA1 Message Date
bsodfather 0de1e94df4 MCP: dispatch incoming requests and notifications through SDK envelopes
CI / UI Checks (pull_request) Successful in 14s
CI / Rust Checks (pull_request) Successful in 35m55s
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
2026-11-12 21:53:24 +00:00
bsodfather 156a849087 refactor(mcp): consume SDK initialized notification in legacy handshake
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 33m16s
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
2026-11-12 19:06:52 +00:00
bsodfather 326f209bc5 refactor(mcp): route runtime ping through rmcp request and result
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 29m49s
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
2026-11-12 16:30:34 +00:00
bsodfather 8068fd7910 refactor(mcp): parse legacy initialize protocol version through SDK
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 31m1s
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
2026-11-12 13:43:04 +00:00
bsodfather 2f9c4cb568 refactor(mcp): serialize negotiation results through rmcp SDK
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 31m21s
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 2s
CI / Deploy (pull_request) Skipped
2026-11-12 10:48:24 +00:00
19 changed files with 2379 additions and 95 deletions

No files matched your search

+39 -23
View File
@@ -5,17 +5,14 @@
//! Moved verbatim out of `app.rs` (Story 3.6, kanban t_987bf309); it is called from
//! `app/endpoint.rs`, so the entry points are `pub(super)`. No behaviour changed.
use super::request::{InitializeParams, ToolCallParams};
use super::request::ToolCallParams;
use super::response::take_confirmation_token;
use super::rmcp_dispatch::{
handle_resources_command, handle_tools_command, list_resource_templates,
};
use crate::{
auth::VerifiedMachineCredential,
jsonrpc::{
is_notification, jsonrpc_error, jsonrpc_result, method_name, negotiated_protocol_version,
params, request_id,
},
jsonrpc::{jsonrpc_error, jsonrpc_result, negotiated_protocol_version, params, request_id},
protocol::{
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler,
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
@@ -81,7 +78,20 @@ pub(super) async fn handle_modern_request(
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
// already run at this point, so this early return cannot admit a malformed identity or a session
// conflict, and the notification is never dispatched.
if is_notification(message) {
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
Ok(Some(envelope)) => envelope,
_ => {
return internal_jsonrpc_error(
message,
"admitted dispatch envelope could not be decoded",
);
}
};
let method = envelope.method();
let notification = envelope.is_notification();
#[cfg(test)]
super::dispatch_observer::sdk_dispatch_envelope_consumed();
if notification {
return crate::protocol::modern_notification_response();
}
@@ -89,15 +99,14 @@ pub(super) async fn handle_modern_request(
Ok(declared_method) => declared_method,
Err(response) => return *response,
};
if declared_method != method_name(message) {
if declared_method != method {
return crate::protocol::modern_header_mismatch_response(message);
}
// R5/F5: the same registration-backed dispatch as the legacy adapter. The handler is decided by
// the owning registration (not by a literal method list inside this adapter), and a method whose
// capability is not eligible in this revision is never served here.
let dispatch =
crate::protocol::dispatch_decision(method_name(message).unwrap_or_default(), version);
let dispatch = crate::protocol::dispatch_decision(method.unwrap_or_default(), version);
match dispatch {
DispatchDecision::Allowed {
handler: MethodHandler::Discover,
@@ -121,7 +130,7 @@ pub(super) async fn handle_modern_request(
request_id(message),
crate::protocol::project_modern_result(
version,
json!({ "protocolVersion": version }),
crate::protocol::ping_result(&json!({"method": "ping"}), version),
),
),
response_mode,
@@ -777,7 +786,8 @@ pub(super) async fn handle_initialize(
message: &Value,
response_mode: ResponseMode,
) -> Response {
let initialize_params: InitializeParams = match serde_json::from_value(params(message)) {
let raw_params = params(message);
let initialize_params = match crate::protocol::initialize_params(&raw_params) {
Ok(value) => value,
Err(_error) => {
return transport_response(
@@ -789,7 +799,10 @@ pub(super) async fn handle_initialize(
);
}
};
let Some(protocol_version) = negotiated_protocol_version(&initialize_params.protocol_version)
#[cfg(test)]
super::dispatch_observer::sdk_initialize_input_consumed(&initialize_params);
let Some(protocol_version) =
negotiated_protocol_version(initialize_params.protocol_version.as_str())
else {
// A revision outside the approved window is rejected without minting a session and without
// echoing any withdrawn revision as the served identity.
@@ -810,9 +823,9 @@ pub(super) async fn handle_initialize(
};
let now = OffsetDateTime::now_utc();
let expires_at = add_millis(now, TRANSPORT_SESSION_TTL_MS);
let supports_elicitation = initialize_params
.capabilities
.get("elicitation")
let supports_elicitation = raw_params
.get("capabilities")
.and_then(|capabilities| capabilities.get("elicitation"))
.is_some_and(Value::is_object);
let session_id = match state
.sessions
@@ -835,14 +848,7 @@ pub(super) async fn handle_initialize(
StatusCode::OK,
jsonrpc_result(
request_id(message),
json!( {
"protocolVersion": protocol_version,
"capabilities": crate::protocol::advertised_server_capabilities(protocol_version),
"serverInfo": {
"name": SERVER_NAME,
"version": SERVER_VERSION
}
}),
crate::protocol::initialize_result(protocol_version, SERVER_NAME, SERVER_VERSION),
),
response_mode,
Some(&session_id),
@@ -854,6 +860,7 @@ pub(super) async fn handle_initialized_notification(
state: Arc<AppState>,
path: &AgentRoutePath,
headers: &HeaderMap,
notification: rmcp::model::ClientNotification,
) -> Response {
match session_id_from_headers(headers) {
Ok(Some(session_id)) => match state.sessions.get(&session_id).await {
@@ -861,6 +868,15 @@ pub(super) async fn handle_initialized_notification(
if session.workspace_slug == path.workspace_slug
&& session.agent_slug == path.agent_slug =>
{
let rmcp::model::ClientNotification::InitializedNotification(initialized) =
notification
else {
unreachable!("initialized handler requires the SDK initialized variant")
};
#[cfg(test)]
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
#[cfg(not(test))]
let _ = initialized;
match state
.sessions
.mark_initialized(&session_id, OffsetDateTime::now_utc())
@@ -73,9 +73,45 @@ pub(crate) struct CounterSet {
sdk_signal_notification: AtomicUsize,
sdk_jsonrpc_response: AtomicUsize,
sdk_jsonrpc_error: AtomicUsize,
sdk_ping_request: AtomicUsize,
sdk_ping_result: AtomicUsize,
sdk_dispatch_decoded: AtomicUsize,
sdk_dispatch_consumed: AtomicUsize,
sdk_initialized_decoded: AtomicUsize,
sdk_initialized_consumed: AtomicUsize,
sdk_initialize_input: AtomicUsize,
sdk_initialize_result: AtomicUsize,
sdk_discover_result: AtomicUsize,
}
impl CounterSet {
pub(crate) fn sdk_dispatch_decoded(&self) -> usize {
self.sdk_dispatch_decoded.load(Ordering::SeqCst)
}
pub(crate) fn sdk_dispatch_consumed(&self) -> usize {
self.sdk_dispatch_consumed.load(Ordering::SeqCst)
}
pub(crate) fn sdk_initialized_decoded(&self) -> usize {
self.sdk_initialized_decoded.load(Ordering::SeqCst)
}
pub(crate) fn sdk_initialized_consumed(&self) -> usize {
self.sdk_initialized_consumed.load(Ordering::SeqCst)
}
pub(crate) fn sdk_ping_request(&self) -> usize {
self.sdk_ping_request.load(Ordering::SeqCst)
}
pub(crate) fn sdk_ping_result(&self) -> usize {
self.sdk_ping_result.load(Ordering::SeqCst)
}
pub(crate) fn sdk_initialize_input(&self) -> usize {
self.sdk_initialize_input.load(Ordering::SeqCst)
}
pub(crate) fn sdk_initialize_result(&self) -> usize {
self.sdk_initialize_result.load(Ordering::SeqCst)
}
pub(crate) fn sdk_discover_result(&self) -> usize {
self.sdk_discover_result.load(Ordering::SeqCst)
}
pub(crate) fn sdk_jsonrpc_response(&self) -> usize {
self.sdk_jsonrpc_response.load(Ordering::SeqCst)
}
@@ -377,6 +413,70 @@ pub(crate) fn sdk_jsonrpc_error_serialized() {
#[path = "../rmcp_envelopes_runtime_tests.rs"]
mod rmcp_envelopes_runtime_tests;
/// Mark only after successfully serializing a real rmcp InitializeResult.
pub(crate) fn sdk_initialize_result_serialized() {
increment(|counters| &counters.sdk_initialize_result);
}
/// Mark only after successfully serializing a real rmcp DiscoverResult.
pub(crate) fn sdk_discover_result_serialized() {
increment(|counters| &counters.sdk_discover_result);
}
#[path = "../rmcp_lifecycle_negotiation_runtime_tests.rs"]
mod rmcp_lifecycle_negotiation_runtime_tests;
/// Mark only where SDK protocol_version is consumed by initialize negotiation, not at DTO creation.
pub(crate) fn sdk_initialize_input_consumed(_params: &rmcp::model::InitializeRequestParams) {
increment(|counters| &counters.sdk_initialize_input);
}
#[path = "../rmcp_initialize_input_runtime_tests.rs"]
mod rmcp_initialize_input_runtime_tests;
/// Mark only where a real SDK PingRequest is consumed by the shared runtime ping seam.
pub(crate) fn sdk_ping_request_consumed(_request: &rmcp::model::PingRequest) {
increment(|counters| &counters.sdk_ping_request);
}
/// Mark only after successfully serializing the real SDK ping result.
pub(crate) fn sdk_ping_result_serialized() {
increment(|counters| &counters.sdk_ping_result);
}
#[path = "../rmcp_ping_runtime_tests.rs"]
mod rmcp_ping_runtime_tests;
/// Mark immediately after typed method-projection decode, not variant consumption.
pub(crate) fn sdk_initialized_notification_decoded(
_notification: &rmcp::model::InitializedNotification,
) {
increment(|counters| &counters.sdk_initialized_decoded);
}
/// Mark inside the matched SDK variant, after guards and immediately before session mutation.
pub(crate) fn sdk_initialized_notification_consumed(
_notification: &rmcp::model::InitializedNotification,
) {
increment(|counters| &counters.sdk_initialized_consumed);
}
#[path = "../rmcp_initialized_runtime_tests.rs"]
mod rmcp_initialized_runtime_tests;
/// Mark after successful SDK envelope decode, independently of routing consumption.
pub(crate) fn sdk_dispatch_envelope_decoded() {
increment(|counters| &counters.sdk_dispatch_decoded);
}
/// Mark only when decoded method/kind selects the existing registry-backed route.
pub(crate) fn sdk_dispatch_envelope_consumed() {
increment(|counters| &counters.sdk_dispatch_consumed);
}
#[path = "../rmcp_dispatch_runtime_tests.rs"]
mod rmcp_dispatch_runtime_tests;
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
let _ = OBSERVER.try_with(|counters| {
counter(counters).fetch_add(1, Ordering::SeqCst);
@@ -30,10 +30,7 @@ use super::rmcp_dispatch::{
use super::{AgentRoutePath, AppState};
use crate::{
auth::VerifiedMachineCredential,
jsonrpc::{
LEGACY_PROTOCOL_VERSION, is_notification, is_request, jsonrpc_error, jsonrpc_result,
method_name, params, request_id,
},
jsonrpc::{LEGACY_PROTOCOL_VERSION, jsonrpc_error, jsonrpc_result, params, request_id},
protocol::{
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
@@ -65,10 +62,20 @@ pub(super) async fn handle_legacy_request(
// `protocol::registry` and is read through `dispatch_decision`, so a newly registered method
// really reaches its handler and removing a descriptor removes the dispatch.
let registration_revision = protocol_version.unwrap_or(LEGACY_PROTOCOL_VERSION);
let dispatch = crate::protocol::dispatch_decision(
method_name(message).unwrap_or_default(),
registration_revision,
);
let envelope = match crate::protocol::decode_dispatch_envelope(message) {
Ok(Some(envelope)) => envelope,
_ => {
return internal_jsonrpc_error(
message,
"admitted dispatch envelope could not be decoded",
);
}
};
let method = envelope.method();
let dispatch =
crate::protocol::dispatch_decision(method.unwrap_or_default(), registration_revision);
#[cfg(test)]
super::dispatch_observer::sdk_dispatch_envelope_consumed();
match dispatch {
// G2: the *registered kind* of the matched method, not the envelope shape, decides which
// legacy lifecycle action runs. `initialize` is a request and `notifications/initialized` is a
@@ -78,17 +85,23 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Method,
} if is_request(message) => handle_initialize(state, path, message, response_mode).await,
} if envelope.is_request() => handle_initialize(state, path, message, response_mode).await,
DispatchDecision::Allowed {
handler: MethodHandler::Lifecycle,
kind: Kind::Notification,
} if is_notification(message) => {
handle_initialized_notification(state, path, headers).await
} if envelope.is_notification() => {
handle_initialized_notification(
state,
path,
headers,
crate::protocol::initialized_notification(message),
)
.await
}
DispatchDecision::Allowed {
handler: MethodHandler::Ping,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -98,7 +111,10 @@ pub(super) async fn handle_legacy_request(
StatusCode::OK,
jsonrpc_result(
request_id(message),
json!({ "protocolVersion": session.protocol_version }),
crate::protocol::ping_result(
&json!({"method": "ping"}),
&session.protocol_version,
),
),
response_mode,
None,
@@ -108,7 +124,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::ToolList,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -177,7 +193,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::ToolCall,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -235,13 +251,13 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::Cancelled,
kind: Kind::Notification,
} if is_notification(message) => {
} if envelope.is_notification() => {
handle_cancelled_notification(&state, path, headers, message, credential).await
}
DispatchDecision::Allowed {
handler: MethodHandler::ResourceList,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -310,7 +326,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::ResourceRead,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -391,7 +407,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::ResourceTemplateList,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -463,7 +479,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::PromptList,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -528,7 +544,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::PromptGet,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -626,7 +642,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::Completion,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -705,7 +721,7 @@ pub(super) async fn handle_legacy_request(
DispatchDecision::Allowed {
handler: MethodHandler::LoggingSetLevel,
..
} if is_request(message) => {
} if envelope.is_request() => {
let session = match require_initialized_session(&state, path, headers, message).await {
Ok(session) => session,
Err(response) => return response,
@@ -751,10 +767,10 @@ pub(super) async fn handle_legacy_request(
}
// A notification whose method the registration does not map to this adapter's handlers is
// acknowledged without being dispatched, exactly as before.
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
_ if envelope.is_notification() => StatusCode::ACCEPTED.into_response(),
// Every remaining decision (unregistered, wrong era, or a handler this adapter does not
// serve) is a method-level rejection: no handler, no service entry, no outbound call.
_ => match method_name(message) {
_ => match method {
Some(method) => transport_response(
StatusCode::OK,
jsonrpc_error(
@@ -1,14 +1,6 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct InitializeParams {
#[serde(rename = "protocolVersion")]
pub(super) protocol_version: String,
#[serde(default)]
pub(super) capabilities: Value,
}
#[derive(Debug, Serialize, Deserialize)]
pub(super) struct ToolCallParams {
pub(super) name: String,
@@ -122,6 +122,17 @@ pub(super) struct CountedSessionStore {
counters: Arc<SessionCounters>,
}
impl CountedSessionStore {
pub(super) fn snapshot(&self) -> SessionOps {
self.counters.snapshot()
}
/// Inspect retained state without incrementing the HTTP request's session-read oracle.
pub(super) async fn retained(&self, id: &str) -> Option<SessionState> {
self.inner.get(id).await.unwrap()
}
}
#[async_trait::async_trait]
impl TransportSessionStore for CountedSessionStore {
async fn create(
@@ -0,0 +1,151 @@
//! Generic SDK envelopes for routing after the authoritative Crank admission guard.
use rmcp::model::{JsonRpcNotification, JsonRpcRequest};
use serde_json::{Value, json};
#[derive(Debug)]
pub(crate) enum DispatchEnvelope {
Request(JsonRpcRequest<Value>),
Notification(JsonRpcNotification<Value>),
}
impl DispatchEnvelope {
pub(crate) fn method(&self) -> Option<&str> {
let payload = match self {
Self::Request(envelope) => &envelope.request,
Self::Notification(envelope) => &envelope.notification,
};
payload.get("method").and_then(Value::as_str)
}
pub(crate) fn is_request(&self) -> bool {
matches!(self, Self::Request(_))
}
pub(crate) fn is_notification(&self) -> bool {
matches!(self, Self::Notification(_))
}
}
/// Call only after `validate_jsonrpc_envelope`; responses keep their existing non-SDK path.
/// Params and extensions stay in the raw message, not in this routing-only projection.
pub(crate) fn decode_dispatch_envelope(
message: &Value,
) -> Result<Option<DispatchEnvelope>, serde_json::Error> {
let Some(method) = message.get("method") else {
return Ok(None);
};
let mut projection = json!({"jsonrpc": message.get("jsonrpc"), "method": method});
let envelope = if let Some(id) = message.get("id") {
// SDK ids are string/i64; the surrogate must never leave this routing-only envelope.
projection["id"] = if id.is_number() && id.as_i64().is_none() {
json!(0)
} else {
id.clone()
};
DispatchEnvelope::Request(serde_json::from_value(projection)?)
} else {
DispatchEnvelope::Notification(serde_json::from_value(projection)?)
};
#[cfg(test)]
crate::app::dispatch_observer::sdk_dispatch_envelope_decoded();
Ok(Some(envelope))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arbitrary_method_ignores_params_and_mixed_extra_fields() {
for params in [
None,
Some(json!({})),
Some(json!({
"_meta": {"clientInfo": false}, "extension": [null, 3]
})),
] {
let mut message = json!({
"jsonrpc": "2.0", "id": "request", "method": "private/arbitrary",
"result": false, "error": [1], "extension": {"anything": true}
});
if let Some(params) = params {
message["params"] = params;
}
let original = message.clone();
let envelope = decode_dispatch_envelope(&message)
.expect("admitted request decodes")
.expect("request envelope");
assert_eq!(envelope.method(), Some("private/arbitrary"));
assert!(envelope.is_request());
assert!(!envelope.is_notification());
let DispatchEnvelope::Request(request) = envelope else {
panic!("request must retain its SDK variant");
};
assert_eq!(request.request, json!({"method": "private/arbitrary"}));
assert_eq!(message, original);
}
}
#[test]
fn request_ids_preserve_raw_value_and_only_surrogate_sdk_incompatible_numbers() {
for (id, sdk_id) in [
(json!("string-id"), json!("string-id")),
(json!(i64::MIN), json!(i64::MIN)),
(json!(i64::MAX), json!(i64::MAX)),
(json!(u64::MAX), json!(0)),
(json!(1.25), json!(0)),
(json!(1.0), json!(0)),
] {
let message = json!({"jsonrpc": "2.0", "id": id, "method": "arbitrary"});
let original = message.clone();
let DispatchEnvelope::Request(request) = decode_dispatch_envelope(&message)
.expect("admitted id decodes")
.expect("request envelope")
else {
panic!("id-bearing method must be a request");
};
assert_eq!(serde_json::to_value(request.id).expect("SDK id"), sdk_id);
assert_eq!(message, original);
assert_eq!(message.to_string(), original.to_string());
}
}
#[test]
fn notification_kind_is_independent_of_method_and_ignored_fields() {
let message = json!({
"jsonrpc": "2.0", "method": "private/arbitrary", "params": {},
"result": {}, "error": {}, "extension": 42
});
let original = message.clone();
let envelope = decode_dispatch_envelope(&message)
.expect("notification decodes")
.expect("notification envelope");
assert_eq!(envelope.method(), Some("private/arbitrary"));
assert!(!envelope.is_request());
assert!(envelope.is_notification());
let DispatchEnvelope::Notification(notification) = envelope else {
panic!("notification must retain its SDK variant");
};
assert_eq!(
notification.notification,
json!({"method": "private/arbitrary"})
);
assert_eq!(message, original);
}
#[test]
fn incoming_success_and_error_responses_are_not_migrated() {
for message in [
json!({"jsonrpc": "2.0", "id": 1, "result": {}}),
json!({"jsonrpc": "2.0", "id": "id", "error": {"code": -1, "message": "error"}}),
json!({"jsonrpc": "2.0", "error": {"code": -1, "message": "error"}}),
] {
assert!(
decode_dispatch_envelope(&message)
.expect("response bypass")
.is_none()
);
}
}
}
@@ -0,0 +1,129 @@
//! Typed negotiation results; admission and session lifecycle remain in the HTTP adapter.
use rmcp::model::{
CacheScope, DiscoverResult, Implementation, InitializeRequestParams, InitializeResult,
PingRequest, ProtocolVersion, ServerCapabilities, ServerResult,
};
use serde_json::Value;
use super::advertised_server_capabilities;
use crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS;
pub(crate) fn initialize_params(
params: &Value,
) -> Result<InitializeRequestParams, serde_json::Error> {
// Only protocolVersion was validated here; ignored client fields must not acquire SDK constraints.
serde_json::from_value(serde_json::json!({
"protocolVersion": params.get("protocolVersion"),
"capabilities": {},
"clientInfo": {"name": "", "version": ""}
}))
}
fn protocol_version(revision: &str) -> ProtocolVersion {
serde_json::from_value(Value::String(revision.to_owned()))
.expect("served protocol revisions are strings")
}
fn capabilities(advertised: &Value) -> ServerCapabilities {
serde_json::from_value(advertised.clone())
.expect("registry capability fragments match SDK capability shapes")
}
fn restore_registry_extensions(result: &mut Value, advertised: Value) {
let capabilities = result["capabilities"]
.as_object_mut()
.expect("SDK server capabilities serialize as an object");
// SDK ServerCapabilities has no flattened map for extra registry capability names.
for (name, settings) in advertised
.as_object()
.expect("registry capabilities are an object")
{
capabilities
.entry(name.clone())
.or_insert_with(|| settings.clone());
}
}
pub(crate) fn initialized_notification(message: &Value) -> rmcp::model::ClientNotification {
// Admission already checked the envelope; ignored params must not acquire SDK constraints.
let notification: rmcp::model::InitializedNotification =
serde_json::from_value(serde_json::json!({"method": message["method"]}))
.expect("registry dispatched a validated initialized notification");
#[cfg(test)]
crate::app::dispatch_observer::sdk_initialized_notification_decoded(&notification);
notification.into()
}
pub(crate) fn ping_result(message: &Value, revision: &str) -> Value {
// Ping params were ignored after admission; do not add SDK constraints to extensions.
let request: PingRequest = serde_json::from_value(serde_json::json!({
"method": message["method"]
}))
.expect("registry dispatched a validated ping request");
#[cfg(test)]
crate::app::dispatch_observer::sdk_ping_request_consumed(&request);
let result = match rmcp::model::ClientRequest::from(request) {
rmcp::model::ClientRequest::PingRequest(_) => ServerResult::empty(()),
_ => unreachable!("typed ping can only dispatch ping"),
};
let mut result = serde_json::to_value(result).expect("SDK ping result is serializable");
#[cfg(test)]
crate::app::dispatch_observer::sdk_ping_result_serialized();
// Crank keeps the admitted/session revision in addition to the SDK's empty ping result.
result["protocolVersion"] = Value::String(revision.to_owned());
result
}
pub(crate) fn initialize_result(revision: &str, name: &str, version: &str) -> Value {
let advertised = advertised_server_capabilities(revision);
let result = InitializeResult::new(capabilities(&advertised))
.with_protocol_version(protocol_version(revision))
.with_server_info(Implementation::new(name, version));
let mut result = serde_json::to_value(result)
.expect("SDK initialize result with registry capabilities is serializable");
#[cfg(test)]
crate::app::dispatch_observer::sdk_initialize_result_serialized();
restore_registry_extensions(&mut result, advertised);
result
}
pub(crate) fn discover_result(revision: &str, name: &str, version: &str) -> Value {
let advertised = advertised_server_capabilities(revision);
let result = DiscoverResult::new(
SUPPORTED_PROTOCOL_VERSIONS
.iter()
.map(|revision| protocol_version(revision))
.collect(),
capabilities(&advertised),
)
.with_server_info(Implementation::new(name, version))
.with_ttl_ms(0)
.with_cache_scope(CacheScope::Private);
let mut result = serde_json::to_value(result)
.expect("SDK discovery result with registry capabilities is serializable");
#[cfg(test)]
crate::app::dispatch_observer::sdk_discover_result_serialized();
restore_registry_extensions(&mut result, advertised);
result
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn lifecycle_sdk_retains_extra_registry_capabilities_without_replacing_sdk_fields() {
let advertised =
json!({"tools":{"listChanged":false}, "inert_test_capability":{"enabled":true}});
let mut result = serde_json::to_value(InitializeResult::new(capabilities(&advertised)))
.expect("typed result serializes");
assert_eq!(
result["capabilities"],
json!({"tools":{"listChanged":false}})
);
restore_registry_extensions(&mut result, advertised.clone());
assert_eq!(result["capabilities"], advertised);
}
}
+7 -17
View File
@@ -26,12 +26,16 @@ use crate::transport::{json_response, protocol_version_from_headers, singleton_h
mod command;
mod completion;
mod dispatch_sdk;
mod lifecycle_sdk;
mod logging;
mod prompts;
mod registry;
mod resources;
mod signals;
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
pub(crate) use command::{
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
ToolsListCommand, ToolsOutcome, handle_tools_command,
@@ -40,6 +44,9 @@ 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,
@@ -844,20 +851,3 @@ pub(crate) fn resolve_request_identity(
}
}
}
/// The pinned `DiscoverResult` for `server/discover` of the revision the caller serves.
pub(crate) fn discover_result(revision: &str, server_name: &str, server_version: &str) -> Value {
json!({
"resultType": "complete",
"supportedVersions": SUPPORTED_PROTOCOL_VERSIONS,
"capabilities": advertised_server_capabilities(revision),
"_meta": {
crate::jsonrpc::META_SERVER_INFO_KEY: {
"name": server_name,
"version": server_version,
}
},
"ttlMs": 0,
"cacheScope": "private"
})
}
@@ -0,0 +1,330 @@
//! #107 generic dispatch: existing wire GREEN precedes independent SDK RED assertions.
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
use super::{CounterSet, Snapshot, observe, support::*};
use serde_json::{Value, json};
use std::sync::{Arc, atomic::Ordering};
#[path = "rmcp_dispatch_test_support.rs"]
mod fixtures;
use fixtures::*;
async fn success_control() -> Vec<[usize; 2]> {
let h = endpoint().await;
let mut deltas = vec![];
for revision in [LEGACY_REVISION, MODERN_REVISION] {
let session = prepared(&h, revision).await;
for accept in ["application/json", "text/event-stream, application/json"] {
for id in [
json!("dispatch/Ю"),
json!(18446744073709551615u64),
json!(3.25),
] {
for method in ["tools/list", "ping"] {
let mut message = payload(revision, method, id.clone());
// Legacy params remain absent; modern identity metadata remains mandatory.
message["extension"] = json!({"future":[null,true]});
message["result"] = json!({"ignored":true});
message["error"] = json!({"ignored":"not an error envelope"});
let before = sdk(&h.counters);
let ops = h.sessions.snapshot();
let entries = h.counters.snapshot();
let response = request(&h, revision, session.as_deref(), accept, message)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
assert!(response.headers().get("MCP-Session-Id").is_none());
let wire = body(response, accept.starts_with("text/event-stream")).await;
assert_eq!(wire["jsonrpc"], "2.0");
assert_eq!(wire["id"], id, "lossless response correlation");
assert!(wire.get("error").is_none(), "{wire}");
if method == "tools/list" {
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
assert_eq!(wire["result"]["tools"].as_array().unwrap().len(), 1);
} else {
let result = if revision == MODERN_REVISION {
json!({"protocolVersion":revision,"resultType":"complete"})
} else {
json!({"protocolVersion":revision})
};
assert_eq!(wire, json!({"jsonrpc":"2.0","id":id,"result":result}));
}
if revision == MODERN_REVISION {
assert_eq!(wire["result"]["resultType"], "complete");
assert_eq!(h.sessions.snapshot(), ops, "no modern session access");
}
assert_deltas(
method,
entries,
h.counters.snapshot(),
Snapshot::new(
1,
usize::from(revision == MODERN_REVISION),
usize::from(revision == LEGACY_REVISION),
usize::from(method == "tools/list"),
),
);
assert_eq!(h.started.load(Ordering::SeqCst), 0);
let after = sdk(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
}
}
}
}
eprintln!(
"existing GREEN 24 HTTP requests after legacy handshake / modern discovery; SDK deltas={deltas:?}"
);
deltas
}
#[tokio::test]
async fn wire_positive_control_json_sse_ids_tolerance_and_routes() {
success_control().await;
}
#[tokio::test]
async fn sdk_envelope_decoded_on_successful_http() {
let deltas = success_control().await;
assert_eq!(
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
vec![1; 24],
"successful HTTP must decode a real SDK request envelope"
);
}
#[tokio::test]
async fn sdk_envelope_consumed_for_registry_routing_on_successful_http() {
let deltas = success_control().await;
assert_eq!(
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
vec![1; 24],
"decoded SDK method/kind must drive registry routing, not decode-and-discard"
);
}
async fn notification_control() -> Vec<[usize; 2]> {
let h = endpoint().await;
let response = request(
&h,
LEGACY_REVISION,
None,
"application/json",
legacy_initialize(1),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
let session = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
let _ = body(response, false).await;
for method in ["notifications/initialized", "unknown/notification"] {
let mut wrong_kind = json!({"jsonrpc":"2.0","id":"wrong-kind","method":method});
let ops = h.sessions.snapshot();
let response = request(
&h,
LEGACY_REVISION,
Some(&session),
"application/json",
wrong_kind.clone(),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(body(response, false).await["error"]["code"], -32601);
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
wrong_kind.as_object_mut().unwrap().remove("id");
if method.starts_with("unknown") {
ack(request(
&h,
LEGACY_REVISION,
Some(&session),
"application/json",
wrong_kind,
)
.send()
.await
.unwrap())
.await;
assert!(!h.sessions.retained(&session).await.unwrap().initialized);
}
}
let before = sdk(&h.counters);
ack(request(
&h,
LEGACY_REVISION,
Some(&session),
"application/json",
initialized_notification(),
)
.send()
.await
.unwrap())
.await;
assert!(h.sessions.retained(&session).await.unwrap().initialized);
let after = sdk(&h.counters);
let mut deltas = vec![[after[0] - before[0], after[1] - before[1]]];
let ops = h.sessions.snapshot();
let entries = h.counters.snapshot();
for method in [
"notifications/initialized",
"unknown/notification",
"tools/call",
] {
let mut message = payload(MODERN_REVISION, method, json!(1));
message.as_object_mut().unwrap().remove("id");
let mut req = request(&h, MODERN_REVISION, None, "application/json", message)
.build()
.unwrap();
req.headers_mut().remove("Mcp-Method");
req.headers_mut().remove("Mcp-Name");
let before = sdk(&h.counters);
ack(reqwest::Client::new().execute(req).await.unwrap()).await;
let after = sdk(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
}
assert_eq!(h.sessions.snapshot(), ops);
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
assert_eq!(h.started.load(Ordering::SeqCst), 0);
eprintln!("existing GREEN notification kind/state/early ACK; SDK deltas={deltas:?}");
deltas
}
#[tokio::test]
async fn notification_order_and_legacy_registered_kind_wire_control() {
notification_control().await;
}
#[tokio::test]
async fn sdk_notification_kind_consumed_on_successful_http() {
assert_eq!(
notification_control().await,
vec![[1, 1]; 4],
"SDK notification variant must drive legacy handshake / modern early ACK"
);
}
#[tokio::test]
async fn rejection_controls_never_enter_service_or_outbound() {
let h = endpoint().await;
for revision in [LEGACY_REVISION, MODERN_REVISION] {
let session = prepared(&h, revision).await;
let base = payload(revision, "tools/list", json!("reject"));
let mut malformed = base.clone();
malformed["jsonrpc"] = json!("1.0");
let mut bad_params = base.clone();
bad_params["params"] = json!([]);
let mut bad_meta = base.clone();
bad_meta["params"] = json!({"_meta":false});
let unknown = payload(revision, "unknown/request", json!("reject"));
let wrong_era = payload(
revision,
if revision == MODERN_REVISION {
"initialize"
} else {
"server/discover"
},
json!("reject"),
);
for (message, status, code) in [
(malformed, 400, -32600),
(bad_params, 400, -32600),
(bad_meta, 400, -32020),
(
unknown,
if revision == MODERN_REVISION {
404
} else {
200
},
-32601,
),
(
wrong_era,
if revision == MODERN_REVISION {
404
} else {
200
},
-32601,
),
] {
let entries = h.counters.snapshot();
let ops = h.sessions.snapshot();
let response = request(
&h,
revision,
session.as_deref(),
"application/json",
message.clone(),
)
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), status, "{revision} {message}");
let wire = body(response, false).await;
assert_eq!(wire["error"]["code"], code, "{revision} {message}: {wire}");
assert!(wire.get("result").is_none());
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
assert_eq!(h.started.load(Ordering::SeqCst), 0);
if revision == MODERN_REVISION {
assert_eq!(h.sessions.snapshot(), ops);
}
}
}
for (header, value) in [("Mcp-Method", "ping"), ("Mcp-Name", "wrong-tool")] {
let ops = h.sessions.snapshot();
let entries = h.counters.snapshot();
let message = json!({"jsonrpc":"2.0","id":"headers","method":"tools/call","params":{"name":TOOL_NAME,"arguments":{"email":"dispatch@example.com"},"_meta":modern_meta()}});
let response = request(&h, MODERN_REVISION, None, "application/json", message)
.header(header, value)
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
assert!(body(response, false).await.get("error").is_some());
assert_eq!(h.sessions.snapshot(), ops);
assert_eq!(h.counters.snapshot().tools_service, entries.tools_service);
assert_eq!(h.started.load(Ordering::SeqCst), 0);
}
let ops = h.sessions.snapshot();
let response = request(
&h,
"2099-01-01",
None,
"application/json",
payload(LEGACY_REVISION, "tools/list", json!(1)),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
assert!(body(response, false).await.get("error").is_some());
assert_eq!(h.sessions.snapshot(), ops);
assert_eq!(h.started.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn observer_independent_positive_control() {
let a = Arc::new(CounterSet::default());
let b = Arc::new(CounterSet::default());
super::sdk_dispatch_envelope_decoded();
super::sdk_dispatch_envelope_consumed();
assert_eq!(sdk(&a), [0, 0]);
tokio::join!(
observe(a.clone(), async {
super::sdk_dispatch_envelope_decoded();
}),
observe(b.clone(), async {
super::sdk_dispatch_envelope_consumed();
})
);
assert_eq!(sdk(&a), [1, 0]);
assert_eq!(sdk(&b), [0, 1]);
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
}
@@ -0,0 +1,103 @@
//! Narrow HTTP helpers; all app/auth/catalog/upstream fixtures remain shared.
use super::*;
pub(super) async fn endpoint() -> Endpoint {
crank_test_support::postgres_schema_url_for_task("dispatch_owner", "t_e862066c").await;
Endpoint::started().await
}
pub(super) fn sdk(c: &CounterSet) -> [usize; 2] {
[c.sdk_dispatch_decoded(), c.sdk_dispatch_consumed()]
}
pub(super) fn payload(revision: &str, method: &str, id: Value) -> Value {
let mut message = json!({"jsonrpc":"2.0","id":id,"method":method});
if revision == MODERN_REVISION {
message["params"] = json!({"_meta":modern_meta()});
}
message
}
pub(super) fn request(
h: &Endpoint,
revision: &str,
session: Option<&str>,
accept: &str,
message: Value,
) -> reqwest::RequestBuilder {
h.request(revision, session, &h.key, accept, message)
.header("x-request-id", "dispatch-atdd")
.header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
}
pub(super) async fn body(response: reqwest::Response, sse: bool) -> Value {
assert_eq!(response.headers()["x-request-id"], "dispatch-atdd");
assert_eq!(
response.headers()["x-trace-id"],
"11111111111111111111111111111111"
);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with(if sse {
"text/event-stream"
} else {
"application/json"
})
);
let raw = tokio::time::timeout(std::time::Duration::from_secs(6), response.text())
.await
.unwrap()
.unwrap();
if sse {
let frames: Vec<Value> = raw
.lines()
.filter_map(|l| l.strip_prefix("data:"))
.map(|l| serde_json::from_str(l.trim()).unwrap())
.collect();
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
frames.into_iter().next().unwrap()
} else {
serde_json::from_str(&raw).unwrap()
}
}
pub(super) async fn ack(response: reqwest::Response) {
assert_eq!(response.status(), 202);
assert!(response.headers().get("content-type").is_none());
assert!(response.headers().get("MCP-Session-Id").is_none());
assert!(response.bytes().await.unwrap().is_empty());
}
pub(super) async fn prepared(h: &Endpoint, revision: &str) -> Option<String> {
if revision == LEGACY_REVISION {
return h.session(revision).await;
}
let ops = h.sessions.snapshot();
let response = request(
h,
revision,
None,
"application/json",
payload(revision, "server/discover", json!(1)),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
assert!(response.headers().get("MCP-Session-Id").is_none());
let wire = body(response, false).await;
assert_eq!(
wire["result"]["supportedVersions"],
json!([MODERN_REVISION, LEGACY_REVISION])
);
assert_eq!(wire["result"]["resultType"], "complete");
assert!(wire.get("error").is_none(), "{wire}");
assert_eq!(h.sessions.snapshot(), ops);
None
}
@@ -1,28 +1,11 @@
//! #107 envelope migration: independent real HTTP wire and SDK participation controls.
use super::{CounterSet, observe, support::*};
use axum::{body::Body, response::Response};
use futures_util::{StreamExt, stream};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
// Reuse the existing real build_app, published catalog, auth and loopback execution fixture.
#[path = "rmcp_progress_cancel_http_support.rs"]
#[allow(dead_code)]
mod fixtures;
use fixtures::Endpoint;
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
let (parts, body) = response.into_parts();
let body = stream::unfold(
(body.into_data_stream(), counters),
|(mut body, counters)| async move {
observe(counters.clone(), body.next())
.await
.map(|chunk| (chunk, (body, counters)))
},
);
Response::from_parts(parts, Body::from_stream(body))
}
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
fn counts(c: &CounterSet) -> [usize; 2] {
[c.sdk_jsonrpc_response(), c.sdk_jsonrpc_error()]
@@ -0,0 +1,416 @@
//! #107 initialize input: existing wire tolerance GREEN, independent SDK-consumption RED.
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
use super::{CounterSet, Snapshot, observe, support::*};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
const ACCEPTS: [&str; 2] = ["application/json", "text/event-stream, application/json"];
const TRACE: &str = "11111111111111111111111111111111";
async fn endpoint() -> Endpoint {
crank_test_support::postgres_schema_url_for_task("initialize_input_owner", "t_ffc30fcd").await;
Endpoint::started().await
}
async fn post(h: &Endpoint, params: Option<Value>, accept: &str) -> reqwest::Response {
let mut payload = json!({"jsonrpc":"2.0","id":"initialize/Ю","method":"initialize"});
if let Some(params) = params {
payload["params"] = params;
}
h.request(LEGACY_REVISION, None, &h.key, accept, payload)
.header("x-request-id", "initialize-input")
.header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
.send()
.await
.unwrap()
}
async fn body(response: reqwest::Response, sse: bool) -> Value {
assert_eq!(response.headers()["x-request-id"], "initialize-input");
assert_eq!(response.headers()["x-trace-id"], TRACE);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with(if sse {
"text/event-stream"
} else {
"application/json"
})
);
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
.await
.unwrap()
.unwrap();
if sse {
let frames: Vec<Value> = raw
.lines()
.filter_map(|line| line.strip_prefix("data:"))
.map(|data| serde_json::from_str(data.trim()).unwrap())
.collect();
assert_eq!(frames.len(), 1, "exactly one terminal SSE frame: {raw}");
frames.into_iter().next().unwrap()
} else {
serde_json::from_str(&raw).unwrap()
}
}
fn valid_shapes() -> Vec<(&'static str, Value, bool)> {
let mut cases = vec![(
"capabilities omitted",
json!({"protocolVersion":LEGACY_REVISION}),
false,
)];
for (name, caps, elicitation) in [
("null capabilities", Value::Null, false),
("boolean capabilities", json!(true), false),
("number capabilities", json!(7), false),
("string capabilities", json!("caps"), false),
("array capabilities", json!([{"elicitation":{}}]), false),
("empty capabilities", json!({}), false),
("null elicitation", json!({"elicitation":null}), false),
("boolean elicitation", json!({"elicitation":true}), false),
("number elicitation", json!({"elicitation":1}), false),
("string elicitation", json!({"elicitation":"yes"}), false),
("array elicitation", json!({"elicitation":[]}), false),
("empty elicitation object", json!({"elicitation":{}}), true),
(
"extended elicitation",
json!({"elicitation":{"form":{},"future":42},"future":[1]}),
true,
),
] {
cases.push((
name,
json!({"protocolVersion":LEGACY_REVISION,"capabilities":caps}),
elicitation,
));
}
for info in [
Value::Null,
json!(42),
json!([]),
json!({"name":false,"version":null}),
json!({"name":"client","version":"1","future":true}),
] {
cases.push((
"ignored clientInfo and extensions",
json!({"protocolVersion":LEGACY_REVISION,
"clientInfo":info,"unknown":{"nested":[null,1]},"_meta":{"future":true}}),
false,
));
}
cases
}
async fn valid_control() -> Vec<usize> {
let h = endpoint().await;
let mut deltas = vec![];
for accept in ACCEPTS {
for (name, params, elicitation) in valid_shapes() {
let ops = h.sessions.snapshot();
let admission = h.counters.snapshot();
let sdk = h.counters.sdk_initialize_input();
let response = post(&h, Some(params), accept).await;
assert_eq!(response.status(), 200, "{name}");
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
let id = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
assert!(!id.is_empty());
let wire = body(response, accept.starts_with("text/event-stream")).await;
assert_eq!(wire["jsonrpc"], "2.0");
assert_eq!(wire["id"], "initialize/Ю");
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
assert!(wire.get("error").is_none());
assert_deltas(
name,
admission,
h.counters.snapshot(),
Snapshot::new(1, 0, 1, 0),
);
assert_session_ops(
name,
ops,
h.sessions.snapshot(),
SessionOps {
get: 0,
create: 1,
mark_initialized: 0,
},
);
let state = h
.sessions
.retained(&id)
.await
.expect("retained session, not a discarded DTO");
assert_eq!(state.id, id);
assert_eq!(state.protocol_version, LEGACY_REVISION);
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
assert_eq!(state.agent_slug, AGENT_SLUG);
assert_eq!(state.supports_elicitation, elicitation, "{name}");
assert!(!state.initialized);
assert_eq!(state.updated_at, state.created_at);
assert_eq!(
(state.expires_at.unwrap() - state.created_at).whole_milliseconds(),
86_400_000
);
deltas.push(h.counters.sdk_initialize_input() - sdk);
let response = h
.request(
LEGACY_REVISION,
Some(&id),
&h.key,
"application/json",
initialized_notification(),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 202);
assert!(response.bytes().await.unwrap().is_empty());
assert!(h.sessions.retained(&id).await.unwrap().initialized);
let response = h
.request(
LEGACY_REVISION,
Some(&id),
&h.key,
"application/json",
json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
let result = json_body(response).await;
assert!(
result.get("error").is_none(),
"initialized opens a protected request: {result}"
);
assert_eq!(result["result"]["tools"][0]["name"], TOOL_NAME);
eprintln!("existing GREEN {name}; accept={accept}; elicitation={elicitation}");
}
}
eprintln!("SDK input consumption deltas={deltas:?}");
deltas
}
#[tokio::test]
async fn rmcp_initialize_input_wire_tolerance_and_retained_sessions() {
valid_control().await;
}
#[tokio::test]
async fn rmcp_initialize_input_sdk_consumed_by_negotiation() {
let deltas = valid_control().await;
assert!(!deltas.is_empty());
assert_eq!(
deltas,
vec![1; valid_shapes().len() * ACCEPTS.len()],
"real HTTP initialize must consume SDK InitializeRequestParams.protocol_version in negotiation"
);
}
// Current HTTP envelope admission rejects sequence params before serde's derived struct decoder.
// Pin that observed boundary instead of imposing a new object-only check in the SDK decoder.
#[tokio::test]
async fn rmcp_initialize_input_wire_invalid_shapes_and_admission() {
let h = endpoint().await;
for accept in ACCEPTS {
for params in [
None,
Some(json!({})),
Some(json!({"protocolVersion":null})),
Some(json!({"protocolVersion":true})),
Some(json!({"protocolVersion":42})),
Some(json!({"protocolVersion":[]})),
Some(json!({"protocolVersion":{}})),
] {
rejection(
&h,
params,
accept,
200,
-32602,
"invalid initialize parameters",
false,
)
.await;
}
for params in [
json!(null),
json!(true),
json!(42),
json!("bad"),
json!([]),
json!([LEGACY_REVISION]),
json!([LEGACY_REVISION, {}]),
json!([LEGACY_REVISION, {}, {}]),
] {
rejection(
&h,
Some(params),
accept,
400,
-32600,
"invalid JSON-RPC request",
true,
)
.await;
}
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
rejection(
&h,
Some(json!({"protocolVersion":version})),
accept,
400,
-32602,
&format!("unsupported protocol version {version}"),
false,
)
.await;
}
for meta in [Value::Null, json!(true), json!(42), json!("bad"), json!([])] {
rejection(
&h,
Some(json!({"protocolVersion":LEGACY_REVISION,"_meta":meta})),
accept,
400,
-32020,
"protocol identity mismatch",
true,
)
.await;
}
}
}
#[allow(clippy::too_many_arguments)]
async fn rejection(
h: &Endpoint,
params: Option<Value>,
accept: &str,
status: u16,
code: i64,
message: &str,
admission_only: bool,
) {
let ops = h.sessions.snapshot();
let admission = h.counters.snapshot();
let sdk = h.counters.sdk_initialize_input();
let response = post(h, params.clone(), accept).await;
assert_eq!(response.status().as_u16(), status, "params={params:?}");
assert!(response.headers().get("MCP-Session-Id").is_none());
// Only HTTP 200 dispatch errors use SSE; HTTP 400 stays JSON regardless of Accept.
let sse = status == 200 && !admission_only && accept.starts_with("text/event-stream");
let wire = body(response, sse).await;
assert_eq!(wire["jsonrpc"], "2.0");
assert_eq!(
wire["id"],
if code == -32600 {
Value::Null
} else {
json!("initialize/Ю")
}
);
assert_eq!(wire["error"]["code"], code, "params={params:?}; {wire}");
assert_eq!(wire["error"]["message"], message);
assert!(wire.get("result").is_none());
// Initialize errors are constructed in the request scope, including terminal SSE errors.
assert_eq!(wire["error"]["data"]["request_id"], "initialize-input");
assert_eq!(wire["error"]["data"]["trace_id"], TRACE);
if code == -32020 {
assert_eq!(
wire["error"]["data"]["details"],
"request _meta must be an object"
);
}
assert_deltas(
"reject",
admission,
h.counters.snapshot(),
Snapshot::new(1, 0, usize::from(!admission_only), 0),
);
assert_session_ops(
"reject",
ops,
h.sessions.snapshot(),
SessionOps {
get: 0,
create: 0,
mark_initialized: 0,
},
);
if !message.starts_with("unsupported protocol version") {
assert_eq!(
h.counters.sdk_initialize_input(),
sdk,
"malformed input never reaches SDK consumption"
);
}
eprintln!(
"existing GREEN reject params={params:?}; accept={accept}; status={status}; code={code}"
);
}
#[tokio::test]
async fn rmcp_initialize_input_sdk_unsupported_revision_uses_same_allowlist() {
let h = endpoint().await;
let mut deltas = vec![];
for accept in ACCEPTS {
for version in ["2025-03-26", "2025-06-18", "2099-01-01", ""] {
let sdk = h.counters.sdk_initialize_input();
rejection(
&h,
Some(json!({"protocolVersion":version})),
accept,
400,
-32602,
&format!("unsupported protocol version {version}"),
false,
)
.await;
deltas.push(h.counters.sdk_initialize_input() - sdk);
}
}
assert_eq!(
deltas,
vec![1; 8],
"unsupported strings must reach the same SDK-backed negotiation, without minting sessions"
);
}
#[tokio::test]
async fn rmcp_initialize_input_observer_positive_control() {
let c = Arc::new(CounterSet::default());
let params: rmcp::model::InitializeRequestParams = serde_json::from_value(json!({
"protocolVersion":LEGACY_REVISION,"capabilities":{},"clientInfo":{"name":"control","version":"1"}
})).unwrap();
observe(c.clone(), async {
super::admission_enter();
super::sdk_initialize_input_consumed(&params);
assert_eq!(c.sdk_initialize_input(), 1);
assert_eq!(
c.sdk_initialize_result(),
0,
"input and output are independent"
);
})
.await;
assert_eq!(c.snapshot(), Snapshot::new(1, 0, 0, 0));
super::sdk_initialize_input_consumed(&params);
assert_eq!(c.sdk_initialize_input(), 1, "out-of-scope call is a no-op");
observe(Arc::new(CounterSet::default()), async {
super::sdk_initialize_input_consumed(&params);
})
.await;
assert_eq!(
c.sdk_initialize_input(),
1,
"another request scope is isolated"
);
}
@@ -0,0 +1,247 @@
//! Initialized HTTP transition against the existing PostgreSQL store, not an SDK session manager.
use super::*;
use crate::session::{PostgresTransportSessionStore, TransportSessionStore};
use crate::session::{SessionState, SessionStoreError};
use std::sync::atomic::{AtomicBool, Ordering};
use time::OffsetDateTime;
struct FaultStore {
inner: PostgresTransportSessionStore,
fail_get: AtomicBool,
fail_mark: AtomicBool,
}
#[async_trait::async_trait]
impl TransportSessionStore for FaultStore {
async fn create(
&self,
revision: &str,
workspace: &str,
agent: &str,
elicitation: bool,
now: OffsetDateTime,
expires: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError> {
self.inner
.create(revision, workspace, agent, elicitation, now, expires)
.await
}
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
if self.fail_get.load(Ordering::SeqCst) {
return Err(SessionStoreError {
details: "test read failure".into(),
});
}
self.inner.get(id).await
}
async fn mark_initialized(
&self,
id: &str,
now: OffsetDateTime,
) -> Result<bool, SessionStoreError> {
if self.fail_mark.load(Ordering::SeqCst) {
return Err(SessionStoreError {
details: "test mark failure".into(),
});
}
self.inner.mark_initialized(id, now).await
}
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
self.inner.delete(id).await
}
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.cleanup_expired(now).await
}
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.active_count(now).await
}
}
#[tokio::test]
async fn initialized_durable_transition_reconnect_and_store_failures() {
crank_test_support::postgres_schema_url_for_task("initialized_durable", "t_9c033310").await;
let registry = test_registry().await;
let pool = registry.pool().clone();
let store = Arc::new(FaultStore {
inner: PostgresTransportSessionStore::from_pool(pool.clone())
.await
.unwrap(),
fail_get: AtomicBool::new(false),
fail_mark: AtomicBool::new(false),
});
let h = Endpoint::started_with_store(Some(store.clone())).await;
let response = post(&h, None, "application/json", legacy_initialize(80)).await;
assert_eq!(response.status(), 200);
let id = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
let before = store.get(&id).await.unwrap().unwrap();
assert!(!before.initialized);
let response = post(
&h,
Some(&id),
"application/json",
initialized_notification(),
)
.await;
assert_eq!(response.status(), 202);
assert!(response.bytes().await.unwrap().is_empty());
assert_eq!(sdk(&h.counters), [1, 1]);
let restarted = PostgresTransportSessionStore::from_pool(pool.clone())
.await
.unwrap();
let after = restarted.get(&id).await.unwrap().unwrap();
assert!(after.initialized);
assert_eq!(after.id, before.id);
assert_eq!(after.workspace_slug, before.workspace_slug);
assert_eq!(after.agent_slug, before.agent_slug);
assert_eq!(after.protocol_version, before.protocol_version);
assert_eq!(after.created_at, before.created_at);
assert_eq!(after.expires_at, before.expires_at);
assert_eq!(after.supports_elicitation, before.supports_elicitation);
let response = post(
&h,
Some(&id),
"application/json",
json!({"jsonrpc":"2.0","id":81,"method":"ping"}),
)
.await;
assert_eq!(response.status(), 200);
assert!(body(response, false).await.get("error").is_none());
let pending = store
.create(
LEGACY_REVISION,
WORKSPACE_SLUG,
AGENT_SLUG,
false,
OffsetDateTime::now_utc(),
None,
)
.await
.unwrap();
store.fail_mark.store(true, Ordering::SeqCst);
let counts = sdk(&h.counters);
let response = post(
&h,
Some(&pending),
"application/json",
initialized_notification(),
)
.await;
assert_eq!(response.status(), 500);
assert!(response.bytes().await.unwrap().is_empty());
assert_eq!(sdk(&h.counters), [counts[0] + 1, counts[1] + 1]);
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
store.fail_mark.store(false, Ordering::SeqCst);
// Fail reads without touching registry/auth tables; admission must stop before the SDK.
store.fail_get.store(true, Ordering::SeqCst);
let counts = sdk(&h.counters);
let response = post(
&h,
Some(&pending),
"application/json",
initialized_notification(),
)
.await;
assert_eq!(response.status(), 500);
assert_eq!(sdk(&h.counters), counts);
store.fail_get.store(false, Ordering::SeqCst);
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
}
#[tokio::test]
async fn initialized_foreign_and_revision_guards_leave_state_untouched() {
let h = endpoint().await;
for (revision, workspace, agent) in [
(LEGACY_REVISION, "foreign-workspace", AGENT_SLUG),
(LEGACY_REVISION, WORKSPACE_SLUG, "foreign-agent"),
("2024-11-05", WORKSPACE_SLUG, AGENT_SLUG),
(MODERN_REVISION, WORKSPACE_SLUG, AGENT_SLUG),
] {
let id = h
.sessions
.create(
revision,
workspace,
agent,
false,
OffsetDateTime::now_utc(),
None,
)
.await
.unwrap();
let state = h.sessions.retained(&id).await.unwrap();
let ops = h.sessions.snapshot();
let counts = sdk(&h.counters);
let response = post(
&h,
Some(&id),
"application/json",
initialized_notification(),
)
.await;
assert_eq!(
response.status(),
if workspace != WORKSPACE_SLUG || agent != AGENT_SLUG {
404
} else {
400
}
);
assert_eq!(h.counters.sdk_initialized_consumed(), counts[1]);
if workspace == WORKSPACE_SLUG && agent == AGENT_SLUG {
assert_eq!(h.counters.sdk_initialized_decoded(), counts[0]);
}
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
assert_eq!(h.sessions.retained(&id).await.unwrap(), state);
}
let id = initialize(&h, "application/json").await;
let counts = sdk(&h.counters);
let ops = h.sessions.snapshot();
let response = h
.request(
LEGACY_REVISION,
Some(&id),
&h.key,
"application/json",
initialized_notification(),
)
.header("MCP-Session-Id", "conflicting-session")
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
assert_eq!(sdk(&h.counters), counts);
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
h.registry
.revoke_platform_api_key_for_agent(
&workspace_id(),
&agent_id(),
&crank_core::PlatformApiKeyId::new("pk_progress_other"),
&OffsetDateTime::now_utc(),
)
.await
.unwrap();
let counts = sdk(&h.counters);
let ops = h.sessions.snapshot();
let response = h
.request(
LEGACY_REVISION,
Some(&id),
&h.other_key,
"application/json",
initialized_notification(),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 401);
assert_eq!(sdk(&h.counters), counts);
assert_eq!(h.sessions.snapshot().create, ops.create);
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
}
@@ -0,0 +1,305 @@
//! #107 initialized: real HTTP wire control, independent SDK decode and consumption oracles.
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
use super::{CounterSet, Snapshot, observe, support::*};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
#[path = "rmcp_initialized_durable_tests.rs"]
mod durable;
async fn endpoint() -> Endpoint {
crank_test_support::postgres_schema_url_for_task("initialized_owner", "t_9c033310").await;
Endpoint::started().await
}
fn sdk(c: &CounterSet) -> [usize; 2] {
[c.sdk_initialized_decoded(), c.sdk_initialized_consumed()]
}
async fn post(
h: &Endpoint,
session: Option<&str>,
accept: &str,
payload: Value,
) -> reqwest::Response {
h.request(LEGACY_REVISION, session, &h.key, accept, payload)
.header("x-request-id", "initialized-atdd")
.header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
.send()
.await
.unwrap()
}
fn correlation(response: &reqwest::Response) {
assert_eq!(response.headers()["x-request-id"], "initialized-atdd");
assert_eq!(
response.headers()["x-trace-id"],
"11111111111111111111111111111111"
);
}
async fn body(response: reqwest::Response, sse: bool) -> Value {
correlation(&response);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with(if sse {
"text/event-stream"
} else {
"application/json"
})
);
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
.await
.unwrap()
.unwrap();
if sse {
let frames: Vec<Value> = raw
.lines()
.filter_map(|l| l.strip_prefix("data:"))
.map(|l| serde_json::from_str(l.trim()).unwrap())
.collect();
assert_eq!(frames.len(), 1, "one terminal SSE frame: {raw}");
frames.into_iter().next().unwrap()
} else {
serde_json::from_str(&raw).unwrap()
}
}
async fn initialize(h: &Endpoint, accept: &str) -> String {
let response = post(h, None, accept, legacy_initialize(71)).await;
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
let id = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
let wire = body(response, accept.starts_with("text/event-stream")).await;
assert_eq!(wire["id"], 71);
assert_eq!(wire["result"]["protocolVersion"], LEGACY_REVISION);
assert!(wire.get("error").is_none());
let state = h.sessions.retained(&id).await.expect("retained session");
assert!(!state.initialized);
assert_eq!(state.workspace_slug, WORKSPACE_SLUG);
assert_eq!(state.agent_slug, AGENT_SLUG);
id
}
async fn control() -> Vec<[usize; 2]> {
let h = endpoint().await;
let mut deltas = vec![];
for accept in ["application/json", "text/event-stream, application/json"] {
for params in [
None,
Some(json!({})),
Some(json!({"ignored":[null,true],
"protocolVersion":false,"capabilities":42,"_meta":{"future":[]}})),
] {
let id = initialize(&h, accept).await;
let untouched = initialize(&h, "application/json").await;
let before_state = h.sessions.retained(&id).await.unwrap();
let mut notification = json!({"jsonrpc":"2.0","method":"notifications/initialized",
"extension":{"future":[null,42]}});
if let Some(params) = params {
notification["params"] = params;
}
let before = sdk(&h.counters);
let ops = h.sessions.snapshot();
let admission = h.counters.snapshot();
let response = post(&h, Some(&id), accept, notification.clone()).await;
assert_eq!(response.status(), 202);
correlation(&response);
assert!(response.headers().get("MCP-Session-Id").is_none());
assert!(response.headers().get("content-type").is_none());
assert!(response.bytes().await.unwrap().is_empty());
assert_session_ops(
"initialized",
ops,
h.sessions.snapshot(),
SessionOps {
get: 2,
create: 0,
mark_initialized: 1,
},
);
assert_deltas(
"initialized",
admission,
h.counters.snapshot(),
Snapshot::new(1, 0, 1, 0),
);
let after = sdk(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
let state = h.sessions.retained(&id).await.unwrap();
assert!(state.initialized);
assert_eq!(state.id, before_state.id);
assert_eq!(state.workspace_slug, before_state.workspace_slug);
assert_eq!(state.agent_slug, before_state.agent_slug);
assert_eq!(state.protocol_version, before_state.protocol_version);
assert_eq!(state.created_at, before_state.created_at);
assert_eq!(state.expires_at, before_state.expires_at);
assert_eq!(
state.supports_elicitation,
before_state.supports_elicitation
);
assert!(state.updated_at >= before_state.updated_at);
assert!(!h.sessions.retained(&untouched).await.unwrap().initialized);
let response = post(
&h,
Some(&id),
accept,
json!({"jsonrpc":"2.0","id":"tools/Ю","method":"tools/list"}),
)
.await;
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
let wire = body(response, accept.starts_with("text/event-stream")).await;
assert_eq!(wire["id"], "tools/Ю");
assert!(wire.get("error").is_none());
assert_eq!(wire["result"]["tools"][0]["name"], TOOL_NAME);
eprintln!(
"existing GREEN initialize -> initialized -> tools/list accept={accept} notification={notification}; SDK delta={:?}",
deltas.last().unwrap()
);
}
}
deltas
}
#[tokio::test]
async fn initialized_wire_handshake_tolerance_and_scoped_state() {
control().await;
}
#[tokio::test]
async fn initialized_sdk_decoded_on_real_http_handshake() {
let deltas = control().await;
assert_eq!(
deltas.iter().map(|d| d[0]).collect::<Vec<_>>(),
vec![1; 6],
"real HTTP initialized must decode the SDK InitializedNotification"
);
}
#[tokio::test]
async fn initialized_sdk_variant_consumed_by_session_transition() {
let deltas = control().await;
assert_eq!(
deltas.iter().map(|d| d[1]).collect::<Vec<_>>(),
vec![1; 6],
"matched ClientNotification variant must drive the real scoped session mutation, not just decode"
);
}
#[tokio::test]
async fn initialized_admission_and_wrong_kind_never_mutate_or_consume() {
let h = endpoint().await;
let id = initialize(&h, "application/json").await;
let mut wrong_initialize = legacy_initialize(72);
wrong_initialize.as_object_mut().unwrap().remove("id");
let mut wrong_initialized = initialized_notification();
wrong_initialized["id"] = json!(73);
let mut cases = vec![
(wrong_initialize, 202, None),
(wrong_initialized, 200, Some(-32601)),
];
for params in [json!(null), json!(true), json!(42), json!("bad"), json!([])] {
cases.push((
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":params}),
400,
Some(-32600),
));
}
for meta in [
json!(null),
json!(false),
json!(42),
json!("bad"),
json!([]),
] {
cases.push((
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":meta}}),
400,
Some(-32020),
));
}
cases.push((
json!({"jsonrpc":"1.0","method":"notifications/initialized"}),
400,
Some(-32600),
));
for (payload, status, code) in cases {
let ops = h.sessions.snapshot();
let before = sdk(&h.counters);
let response = post(&h, Some(&id), "application/json", payload.clone()).await;
assert_eq!(response.status().as_u16(), status, "{payload}");
if let Some(code) = code {
let wire = body(response, false).await;
assert_eq!(wire["error"]["code"], code, "{payload}: {wire}");
assert!(wire.get("result").is_none());
} else {
assert!(response.bytes().await.unwrap().is_empty());
}
let after = h.sessions.snapshot();
assert_eq!(after.create, ops.create);
assert_eq!(after.mark_initialized, ops.mark_initialized);
assert!(!h.sessions.retained(&id).await.unwrap().initialized);
assert_eq!(
sdk(&h.counters),
before,
"rejected before SDK decode/consume: {payload}"
);
}
}
#[tokio::test]
async fn initialized_missing_unknown_sessions_and_modern_never_consume() {
let h = endpoint().await;
for (session, status) in [(None, 400), (Some("unknown-session"), 404)] {
let ops = h.sessions.snapshot();
let response = post(&h, session, "application/json", initialized_notification()).await;
assert_eq!(response.status().as_u16(), status);
assert!(response.bytes().await.unwrap().is_empty());
assert_eq!(h.sessions.snapshot().mark_initialized, ops.mark_initialized);
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
}
let ops = h.sessions.snapshot();
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":modern_meta()}}))
.send().await.unwrap();
assert_eq!(response.status(), 202);
assert!(response.bytes().await.unwrap().is_empty());
assert_eq!(
h.sessions.snapshot(),
ops,
"modern signal never accesses storage"
);
assert_eq!(h.counters.sdk_initialized_consumed(), 0);
}
#[tokio::test]
async fn initialized_observer_independent_positive_control() {
let a = Arc::new(CounterSet::default());
let b = Arc::new(CounterSet::default());
let notification: rmcp::model::InitializedNotification =
serde_json::from_value(json!({"method":"notifications/initialized"})).unwrap();
super::sdk_initialized_notification_decoded(&notification);
super::sdk_initialized_notification_consumed(&notification);
assert_eq!(sdk(&a), [0, 0]);
tokio::join!(
observe(a.clone(), async {
super::sdk_initialized_notification_decoded(&notification);
}),
observe(b.clone(), async {
super::sdk_initialized_notification_consumed(&notification);
})
);
assert_eq!(sdk(&a), [1, 0]);
assert_eq!(sdk(&b), [0, 1], "decode alone never proves consumption");
assert_eq!(a.snapshot(), Snapshot::new(0, 0, 0, 0));
assert_eq!(b.snapshot(), Snapshot::new(0, 0, 0, 0));
}
@@ -0,0 +1,270 @@
//! #107 negotiation results: existing HTTP wire GREEN, independent SDK execution oracle RED.
use super::{CounterSet, observe, support::*};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
fn sdk_counts(c: &CounterSet) -> [usize; 2] {
[c.sdk_initialize_result(), c.sdk_discover_result()]
}
fn capabilities() -> Value {
// Pin the reviewed advertisement, not a call to the builder under test or SDK defaults.
json!({"completions":{},"logging":{},"prompts":{"listChanged":true},
"resources":{"listChanged":true,"subscribe":false},"tools":{"listChanged":true}})
}
fn expected_result(revision: &str) -> Value {
let server = json!({"name":"crank-mcp-server","version":env!("CARGO_PKG_VERSION")});
if revision == LEGACY_REVISION {
json!({"protocolVersion":LEGACY_REVISION,"capabilities":capabilities(),"serverInfo":server})
} else {
json!({"resultType":"complete","supportedVersions":["2026-07-28","2025-11-25"],
"capabilities":capabilities(),"_meta":{"io.modelcontextprotocol/serverInfo":server},
"ttlMs":0,"cacheScope":"private"})
}
}
async fn wire(response: reqwest::Response, revision: &str, id: &Value, sse: bool) -> Value {
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
assert_eq!(response.headers()["x-request-id"], "negotiation-request");
assert_eq!(
response.headers()["x-trace-id"],
"11111111111111111111111111111111"
);
let content_type = response.headers()["content-type"].to_str().unwrap();
assert!(content_type.starts_with(if sse {
"text/event-stream"
} else {
"application/json"
}));
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
.await
.unwrap()
.unwrap();
let body: Value = if sse {
let frames: Vec<Value> = raw
.lines()
.filter_map(|line| line.strip_prefix("data:"))
.map(|data| serde_json::from_str(data.trim()).unwrap())
.collect();
assert_eq!(
frames.len(),
1,
"one terminal, no unsolicited notifications: {raw}"
);
frames.into_iter().next().unwrap()
} else {
serde_json::from_str(&raw).unwrap()
};
assert_eq!(
body,
json!({"jsonrpc":"2.0","id":id,"result":expected_result(revision)}),
"exact result/envelope fields and omissions (including title/icons/instructions/defaults)"
);
body
}
async fn control(revision: &str) -> Vec<[usize; 2]> {
crank_test_support::postgres_schema_url_for_task("negotiation_owner", "t_99aa603c").await;
let h = Endpoint::started().await;
let mut deltas = vec![];
// Accept order selects JSON or a single terminal SSE frame on the real transport.
for accept in ["application/json", "text/event-stream, application/json"] {
let id = json!("negotiation/Ю");
let payload = if revision == LEGACY_REVISION {
let mut initialize = legacy_initialize(1);
initialize["id"] = id.clone();
initialize
} else {
json!({"jsonrpc":"2.0","id":id,"method":"server/discover","params":{"_meta":modern_meta()}})
};
let before = sdk_counts(&h.counters);
let admission_before = h.counters.snapshot();
let response = h
.request(revision, None, &h.key, accept, payload)
.header("x-request-id", "negotiation-request")
.header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
.send()
.await
.unwrap();
let session = response
.headers()
.get("MCP-Session-Id")
.map(|v| v.to_str().unwrap().to_owned());
if revision == LEGACY_REVISION {
assert!(
!session
.as_deref()
.expect("initialize creates a session")
.is_empty()
);
} else {
assert_eq!(
session, None,
"stateless discovery never creates a session carrier"
);
}
wire(
response,
revision,
&id,
accept.starts_with("text/event-stream"),
)
.await;
assert_deltas(
"negotiation admission positive control",
admission_before,
h.counters.snapshot(),
if revision == LEGACY_REVISION {
super::Snapshot::new(1, 0, 1, 0)
} else {
super::Snapshot::new(1, 1, 0, 0)
},
);
let after = sdk_counts(&h.counters);
deltas.push([after[0] - before[0], after[1] - before[1]]);
if let Some(session) = session {
let response = h
.request(
revision,
Some(&session),
&h.key,
accept,
initialized_notification(),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 202);
assert!(response.bytes().await.unwrap().is_empty());
// Prove the minted session can authorize the next protected request.
let response = h
.request(
revision,
Some(&session),
&h.key,
"application/json",
json!({"jsonrpc":"2.0","id":2,"method":"ping"}),
)
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(
json_body(response).await,
json!({"jsonrpc":"2.0","id":2,"result":{"protocolVersion":LEGACY_REVISION}})
);
}
}
eprintln!("existing GREEN lifecycle negotiation wire {revision}; SDK deltas={deltas:?}");
deltas
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_wire_legacy() {
control(LEGACY_REVISION).await;
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_wire_modern() {
control(MODERN_REVISION).await;
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_sdk_legacy() {
assert_eq!(
control(LEGACY_REVISION).await,
vec![[1, 0]; 2],
"real HTTP initialize must serialize SDK InitializeResult (not admission/envelope only)"
);
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_sdk_modern() {
assert_eq!(
control(MODERN_REVISION).await,
vec![[0, 1]; 2],
"real HTTP discovery must serialize SDK DiscoverResult (not admission/envelope only)"
);
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_observer_positive_control() {
let c = Arc::new(CounterSet::default());
observe(c.clone(), async {
super::admission_enter();
super::sdk_initialize_result_serialized();
assert_eq!(
sdk_counts(&c),
[1, 0],
"initialize and discovery are separate markers"
);
super::sdk_discover_result_serialized();
})
.await;
assert_eq!(sdk_counts(&c), [1, 1]);
assert_eq!(c.snapshot(), super::Snapshot::new(1, 0, 0, 0));
super::sdk_initialize_result_serialized();
super::sdk_discover_result_serialized();
assert_eq!(sdk_counts(&c), [1, 1], "out-of-scope markers are no-ops");
}
#[tokio::test]
async fn rmcp_lifecycle_negotiation_wire_session_operations() {
crank_test_support::postgres_schema_url_for_task("negotiation_sessions_owner", "t_99aa603c")
.await;
let h = Harness::started().await;
// Existing counted-session fixture supplies independent get/create/initialized oracles.
run_valid_legacy_initialize(&h, 10, "legacy create exactly once").await;
let session = h.initialize_legacy_session().await;
run_valid_legacy_call(
&h,
&session,
11,
"negotiation@example.test",
"initialized session works",
)
.await;
for accept in ["application/json", "text/event-stream, application/json"] {
let before = h.session_ops();
let admission_before = h.snapshot();
let response = h
.post(
&[
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "server/discover"),
("Accept", accept),
("x-request-id", "negotiation-request"),
(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
),
],
&json!({"jsonrpc":"2.0","id":"discovery","method":"server/discover",
"params":{"_meta":modern_meta()}}),
)
.await;
assert!(response.headers().get("MCP-Session-Id").is_none());
wire(response, MODERN_REVISION, &json!("discovery"), false).await;
assert_deltas(
"modern discovery",
admission_before,
h.snapshot(),
super::Snapshot::new(1, 1, 0, 0),
);
assert_session_ops(
"stateless discovery",
before,
h.session_ops(),
SessionOps {
get: 0,
create: 0,
mark_initialized: 0,
},
);
}
}
@@ -0,0 +1,211 @@
//! #107 ping: existing wire GREEN is independent from the SDK execution oracle.
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
use super::{CounterSet, Snapshot, observe, support::*};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
async fn endpoint() -> Endpoint {
crank_test_support::postgres_schema_url_for_task("ping_owner", "t_83746dc7").await;
Endpoint::started().await
}
fn ping(revision: &str, extended: bool) -> Value {
let mut payload = json!({"jsonrpc":"2.0","id":"ping/Ю","method":"ping"});
if revision == MODERN_REVISION || extended {
payload["params"] = json!({"_meta":if revision == MODERN_REVISION {
modern_meta()
} else { json!({}) }});
}
if extended {
payload["params"]["ignored"] = json!([null, {"future":true}]);
payload["params"]["_meta"]["future"] = json!(42);
payload["extension"] = json!({"nested":[false]});
}
payload
}
async fn wire_body(response: reqwest::Response, sse: bool) -> Value {
assert_eq!(response.headers()["x-request-id"], "ping-atdd");
assert_eq!(
response.headers()["x-trace-id"],
"11111111111111111111111111111111"
);
assert!(
response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with(if sse {
"text/event-stream"
} else {
"application/json"
})
);
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
.await
.unwrap()
.unwrap();
if sse {
let frames: Vec<Value> = raw
.lines()
.filter_map(|line| line.strip_prefix("data:"))
.map(|line| serde_json::from_str(line.trim()).unwrap())
.collect();
assert_eq!(frames.len(), 1, "one terminal frame: {raw}");
frames.into_iter().next().unwrap()
} else {
serde_json::from_str(&raw).unwrap()
}
}
fn correlated(request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
request.header("x-request-id", "ping-atdd").header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
}
async fn success_control(revision: &str) -> Vec<(usize, usize)> {
let h = endpoint().await;
// The existing fixture performs real initialize -> initialized for legacy only.
let session = h.session(revision).await;
let mut sdk = vec![];
for (accept, extended) in [
("application/json", false),
("text/event-stream, application/json", true),
] {
let counters = h.counters.snapshot();
let ops = h.sessions.snapshot();
let before = (h.counters.sdk_ping_request(), h.counters.sdk_ping_result());
let response = correlated(h.request(
revision,
session.as_deref(),
&h.key,
accept,
ping(revision, extended),
))
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["MCP-Protocol-Version"], revision);
assert!(response.headers().get("MCP-Session-Id").is_none());
let wire = wire_body(response, accept.starts_with("text/event-stream")).await;
let result = if revision == MODERN_REVISION {
json!({"protocolVersion":revision,"resultType":"complete"})
} else {
json!({"protocolVersion":revision})
};
assert_eq!(wire, json!({"jsonrpc":"2.0","id":"ping/Ю","result":result}));
assert_deltas(
"ping",
counters,
h.counters.snapshot(),
Snapshot::new(
1,
usize::from(revision == MODERN_REVISION),
usize::from(revision == LEGACY_REVISION),
0,
),
);
assert_session_ops(
"ping",
ops,
h.sessions.snapshot(),
SessionOps {
get: 2 * usize::from(revision == LEGACY_REVISION),
create: 0,
mark_initialized: 0,
},
);
sdk.push((
h.counters.sdk_ping_request() - before.0,
h.counters.sdk_ping_result() - before.1,
));
eprintln!(
"existing GREEN ping revision={revision} accept={accept} extended={extended}; SDK delta={:?}",
sdk.last().unwrap()
);
}
sdk
}
#[tokio::test]
async fn ping_wire_json_sse_tolerance_and_session_contract() {
success_control(LEGACY_REVISION).await;
success_control(MODERN_REVISION).await;
}
#[tokio::test]
async fn ping_sdk_legacy_request_and_result() {
assert_eq!(
success_control(LEGACY_REVISION).await,
vec![(1, 1); 2],
"successful legacy HTTP ping must consume SDK request and serialize SDK result"
);
}
#[tokio::test]
async fn ping_sdk_modern_request_and_result() {
assert_eq!(
success_control(MODERN_REVISION).await,
vec![(1, 1); 2],
"successful stateless HTTP ping must consume SDK request and serialize SDK result"
);
}
#[tokio::test]
async fn ping_guards_never_enter_sdk() {
let h = endpoint().await;
for revision in [LEGACY_REVISION, MODERN_REVISION] {
let mut payload = ping(revision, true);
if revision == MODERN_REVISION {
payload["params"]["_meta"] = Value::Null;
}
let response = correlated(h.request(revision, None, &h.key, "application/json", payload))
.send()
.await
.unwrap();
assert_eq!(response.status(), 400);
if revision == LEGACY_REVISION {
assert!(response.headers().get("content-type").is_none());
assert!(response.bytes().await.unwrap().is_empty());
} else {
let wire = wire_body(response, false).await;
assert_eq!(wire["id"], "ping/Ю");
assert_eq!(wire["error"]["code"], -32020);
assert!(wire.get("result").is_none());
}
assert_eq!(
(h.counters.sdk_ping_request(), h.counters.sdk_ping_result()),
(0, 0)
);
eprintln!("existing GREEN pre-seam guard revision={revision}; SDK=(0,0)");
}
}
#[tokio::test]
async fn ping_observer_positive_control() {
let c = Arc::new(CounterSet::default());
let request: rmcp::model::PingRequest =
serde_json::from_value(json!({"method":"ping"})).unwrap();
observe(c.clone(), async {
super::sdk_ping_request_consumed(&request);
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 0));
super::sdk_ping_result_serialized();
assert_eq!((c.sdk_ping_request(), c.sdk_ping_result()), (1, 1));
})
.await;
super::sdk_ping_request_consumed(&request);
super::sdk_ping_result_serialized();
observe(Arc::new(CounterSet::default()), async {
super::sdk_ping_request_consumed(&request);
super::sdk_ping_result_serialized();
})
.await;
assert_eq!(
(c.sdk_ping_request(), c.sdk_ping_result()),
(1, 1),
"scope isolation and out-of-scope no-op"
);
assert_eq!(c.snapshot(), Snapshot::new(0, 0, 0, 0));
}
@@ -6,9 +6,10 @@ use crank_runtime::{
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::Semaphore;
pub(super) struct Endpoint {
pub(in crate::app::dispatch_observer) struct Endpoint {
pub registry: crank_registry::PostgresRegistry,
pub counters: Arc<CounterSet>,
pub sessions: Arc<CountedSessionStore>,
pub key: String,
pub other_key: String,
pub gate: Arc<Semaphore>,
@@ -25,6 +26,9 @@ impl Drop for Endpoint {
}
impl Endpoint {
pub async fn started() -> Self {
Self::started_with_store(None).await
}
pub async fn started_with_store(store: Option<crate::session::SharedSessionStore>) -> Self {
crank_test_support::postgres_schema_url_for_task("progress_owner", "t_d65dd129").await;
let registry = test_registry().await;
let gate = Arc::new(Semaphore::new(0));
@@ -90,6 +94,7 @@ impl Endpoint {
.await
.unwrap();
let counters = Arc::new(CounterSet::default());
let sessions = Arc::new(CountedSessionStore::default());
let app = crate::build_app(
registry.clone(),
Duration::ZERO,
@@ -101,7 +106,7 @@ impl Endpoint {
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
Arc::new(crate::session::InMemorySessionStore::default()),
store.unwrap_or_else(|| sessions.clone()),
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
);
let scope = counters.clone();
@@ -125,6 +130,7 @@ impl Endpoint {
Self {
registry,
counters,
sessions,
key,
other_key,
gate,
@@ -5,7 +5,7 @@ use futures_util::{StreamExt, stream};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
#[path = "rmcp_progress_cancel_http_support.rs"]
mod fixtures;
pub(super) mod fixtures;
use fixtures::Endpoint;
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
+8
View File
@@ -47,6 +47,14 @@ Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0
Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritten `jsonrpc_result`/`jsonrpc_error` в `jsonrpc.rs` сериализацией настоящих `JsonRpcResponse<Value>` и `JsonRpcError`/`ErrorData`. Уже подключённые consumers — общий `build_app` HTTP JSON и lifecycle SSE terminal обеих revisions; новые dispatch/transport пути не добавляются. Локальная projection+restore сразу возвращает исходные JSON id (включая null, u64 и точную floating-point форму) и i64 error code, которые SDK-типы не представляют полностью; произвольный result и omission error.data сохраняются. Прежний guard correlation не меняется: JSON protocol errors содержат correlation data, lifecycle SSE terminal errors по-прежнему её опускают. Runtime wire controls и отдельный SDK oracle проверяют success/protocol error, а affected regressions — admission, revoked credentials, tool isError и cancellation. Входная валидация, safe response id, auth, статусы/headers, очереди/сессии и transport остаются прежними; это не завершение #107, feature qualification или production deployment.
Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет handwritten ответы legacy `initialize` и modern `server/discover` на настоящие `InitializeResult`/`DiscoverResult` в `protocol/lifecycle_sdk.rs`. Уже подключённый потребитель — штатный `build_app` HTTP JSON/SSE. Версии и их порядок заданы прежним allowlist, capabilities поступают только из registry; server identity, omissions и discovery ttlMs=0/cacheScope=private сохранены. SDK `ServerCapabilities` не представляет дополнительные top-level имена registry: после typed serialization восстанавливаются только отсутствующие ключи, без замены SDK-known полей. HTTP ATDD отдельно проверяет прежний wire и SDK execution, legacy initialize→initialized→защищённый вызов и отсутствие session operations у modern discovery; affected regression сохраняет frozen advertisement, unsupported revision rejection, auth/revocation/Agent scope и legacy transport lifecycle. Следующий initialize-input-срез на базе rc.27 заменяет `app/request.rs::InitializeParams` декодированием настоящего `InitializeRequestParams` в `protocol/lifecycle_sdk.rs`: штатный `handle_initialize` использует SDK `protocol_version` в прежнем allowlist. Локальная projection передаёт только protocolVersion с инертными обязательными SDK capabilities/clientInfo; исходные ignored clientInfo/extensions не валидируются, а raw capabilities сохраняют прежний object-предикат elicitation. HTTP admission (включая запрет sequence params и malformed _meta) остаётся до SDK. Отдельный typed runtime oracle и JSON/SSE tolerance/session ATDD подтверждают использование результата SDK, отсутствие новых отказов и прежний initialize→initialized→защищённый вызов. Generic dispatch/ping, session storage/TTL/reconnect, admission/auth и transport не переносились. Существующий SSE error.data omission не исправляется; полный #107, feature qualification и production deployment не завершены.
Ping-срез #107 на базе rc.28/rmcp3.9.0 подключает обе штатные HTTP ветки к общему `protocol/lifecycle_sdk.rs::ping_result`: проекция уже допущенного метода декодируется в `PingRequest`, его SDK request variant выбирает `ServerResult::empty(())`, а сериализованный SDK результат поступает в прежний JSON/SSE terminal. Удалены два handwritten ping result builder; Crank добавляет прежний `protocolVersion` из legacy session либо modern identity, а modern result projection сохраняется. Игнорируемые params/extensions не получают новых SDK ограничений. Legacy initialized-session guard остаётся перед helper; modern ping не обращается к sessions. Runtime ATDD отдельно подтверждает SDK request/result execution и прежние wire/status/headers/id/correlation обеих revisions; affected regressions проверяют session/admission/method/revocation guards. Generic dispatch, session storage/TTL/reconnect, admission/auth и transport остаются прежними; полный #107, feature qualification и production deployment не завершены.
Initialized-срез #107 на базе rc.29/rmcp3.9.0 подключает штатный legacy HTTP handshake к `InitializedNotification` и `ClientNotification`: после registry/admission проекция метода декодируется SDK, а matched initialized variant после прежних session/scope guards разрешает существующий durable `mark_initialized`. Игнорируемые params/extensions, 202 с пустым телом, JSON/SSE и modern no-session поведение сохранены; SDK SessionManager не используется. Runtime-тесты отдельно наблюдают decoding и consumption, проверяют PostgreSQL reconnect и отказ store на чтении/записи. Это только lifecycle-срез, не завершение #107.
Envelope-dispatch-срез #107 на базе rc.30/rmcp3.9.0 подключает обе действующие HTTP ветки `app/dispatch.rs` и `app/legacy_dispatch.rs` к общему `protocol/dispatch_sdk.rs`: после прежних admission/auth guards минимальная проекция декодируется в настоящие `JsonRpcRequest<Value>`/`JsonRpcNotification<Value>`. SDK payload method выбирает прежний `registry::dispatch_decision`, SDK variant определяет request/notification routing вместо повторных raw-JSON predicates. Второй таблицы методов нет; registry остаётся policy gate revisions/capabilities/registered kind. Modern notification ACK по-прежнему предшествует request-only Mcp-Method/Mcp-Name checks и не обращается к sessions/domain. Params и ignored extensions/result/error остаются вне routing projection; SDK-incompatible числовые ID получают только внутренний surrogate, исходные ID/числовая форма остаются в raw message для wire/correlation/cancellation ownership. Для выбранного registry Ping handler typed projection использует canonical ping, сохраняя registered alias semantics. Runtime HTTP ATDD отдельно проверяет SDK decode/consumption и прежний JSON/SSE wire; affected registry/admission, durable initialized/reconnect, progress/cancel и auth guards проверяются без замены storage/transport. Это перенос только generic request/notification envelope routing: domain/generic handler execution, inbound response/error envelopes и их shape validation, session storage/TTL/reconnect, transport и feature qualification остаются вне среза. Полный #107 остаётся open; #108/4.7 и production switch не запускаются.
Проверяемый результат:
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.