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
12 changed files with 1273 additions and 36 deletions

No files matched your search

+28 -9
View File
@@ -12,10 +12,7 @@ use super::rmcp_dispatch::{
};
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,
crate::protocol::ping_result(message, version),
crate::protocol::ping_result(&json!({"method": "ping"}), version),
),
),
response_mode,
@@ -851,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 {
@@ -858,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())
@@ -75,12 +75,28 @@ pub(crate) struct CounterSet {
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)
}
@@ -431,6 +447,36 @@ pub(crate) fn sdk_ping_result_serialized() {
#[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),
crate::protocol::ping_result(message, &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(
@@ -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()
);
}
}
}
@@ -45,6 +45,16 @@ fn restore_registry_extensions(result: &mut Value, advertised: Value) {
}
}
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!({
@@ -26,6 +26,7 @@ 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;
@@ -33,6 +34,8 @@ 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,
@@ -42,7 +45,7 @@ pub(crate) use completion::{
handle_completion_command,
};
pub(crate) use lifecycle_sdk::{
discover_result, initialize_params, initialize_result, ping_result,
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,
@@ -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
}
@@ -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));
}
@@ -26,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));
@@ -103,7 +106,7 @@ impl Endpoint {
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
sessions.clone(),
store.unwrap_or_else(|| sessions.clone()),
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
);
let scope = counters.clone();
+4
View File
@@ -51,6 +51,10 @@ Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет
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.