MCP: execute legacy notifications through SDK handlers
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 40m6s
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
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 40m6s
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
This commit is contained in:
1 parent
986cd78b96
commit
fd76aaf676
10 files changed
+735
-52
No files matched your search
@@ -42,6 +42,8 @@ mod rmcp_http;
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
mod rmcp_negotiation;
|
||||
mod rmcp_notifications;
|
||||
#[cfg(test)]
|
||||
mod rmcp_progress_cancel;
|
||||
mod rmcp_prompts;
|
||||
mod rmcp_prompts_projection;
|
||||
|
||||
@@ -870,15 +870,9 @@ pub(super) async fn handle_initialized_notification(
|
||||
super::dispatch_observer::sdk_initialized_notification_consumed(&initialized);
|
||||
#[cfg(not(test))]
|
||||
let _ = initialized;
|
||||
match state
|
||||
.sessions
|
||||
.mark_initialized(&session_id, OffsetDateTime::now_utc())
|
||||
super::rmcp_notifications::initialized(state, session_id)
|
||||
.await
|
||||
{
|
||||
Ok(true) => StatusCode::ACCEPTED.into_response(),
|
||||
Ok(false) => StatusCode::NOT_FOUND.into_response(),
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
.into_response()
|
||||
}
|
||||
Ok(Some(_)) => StatusCode::NOT_FOUND.into_response(),
|
||||
Ok(None) => StatusCode::NOT_FOUND.into_response(),
|
||||
|
||||
@@ -98,6 +98,10 @@ pub(crate) struct CounterSet {
|
||||
sdk_dispatch_consumed: AtomicUsize,
|
||||
sdk_initialized_decoded: AtomicUsize,
|
||||
sdk_initialized_consumed: AtomicUsize,
|
||||
sdk_initialized_handler_completed: AtomicUsize,
|
||||
sdk_initialized_handler_consumed: AtomicUsize,
|
||||
sdk_cancelled_handler_completed: AtomicUsize,
|
||||
sdk_cancelled_handler_consumed: AtomicUsize,
|
||||
sdk_initialize_input: AtomicUsize,
|
||||
|
||||
sdk_initialize_handler_completed: AtomicUsize,
|
||||
@@ -185,6 +189,20 @@ impl CounterSet {
|
||||
self.sdk_initialized_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_completed(&self) -> usize {
|
||||
self.sdk_initialized_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_initialized_handler_consumed(&self) -> usize {
|
||||
self.sdk_initialized_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_cancelled_handler_completed(&self) -> usize {
|
||||
self.sdk_cancelled_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_cancelled_handler_consumed(&self) -> usize {
|
||||
self.sdk_cancelled_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialize_input(&self) -> usize {
|
||||
self.sdk_initialize_input.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -644,9 +662,29 @@ pub(crate) fn sdk_initialized_notification_consumed(
|
||||
increment(|counters| &counters.sdk_initialized_consumed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_completed() {
|
||||
increment(|c| &c.sdk_initialized_handler_completed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_initialized_handler_consumed() {
|
||||
increment(|c| &c.sdk_initialized_handler_consumed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_cancelled_handler_completed() {
|
||||
increment(|c| &c.sdk_cancelled_handler_completed);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_cancelled_handler_consumed() {
|
||||
increment(|c| &c.sdk_cancelled_handler_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_initialized_runtime_tests.rs"]
|
||||
mod rmcp_initialized_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_notification_handler_runtime_tests.rs"]
|
||||
mod rmcp_notification_handler_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);
|
||||
|
||||
@@ -802,25 +802,19 @@ async fn handle_cancelled_notification(
|
||||
message: &Value,
|
||||
credential: &VerifiedMachineCredential,
|
||||
) -> Response {
|
||||
let request_id = super::rmcp_progress_cancel::decode_cancelled_request_id(¶ms(message));
|
||||
let Some((typed, raw_number)) = super::rmcp_notifications::cancelled_params(¶ms(message))
|
||||
else {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
};
|
||||
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned_by_session {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id,
|
||||
owner: in_flight_owner(credential),
|
||||
},
|
||||
&request_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
super::rmcp_notifications::cancelled(
|
||||
Arc::clone(state),
|
||||
path.clone(),
|
||||
credential.clone(),
|
||||
session_id,
|
||||
typed,
|
||||
raw_number,
|
||||
)
|
||||
.await;
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Request-owned SDK execution for legacy notifications/initialized and notifications/cancelled.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use rmcp::{RoleServer, ServerHandler, model::*, service::NotificationContext};
|
||||
use serde_json::{Map, Value};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::auth::VerifiedMachineCredential;
|
||||
|
||||
struct OutcomeHandler {
|
||||
operation: Operation,
|
||||
outcome: Mutex<Option<StatusCode>>,
|
||||
}
|
||||
|
||||
enum Operation {
|
||||
Initialized {
|
||||
state: Arc<AppState>,
|
||||
session_id: String,
|
||||
},
|
||||
Cancelled {
|
||||
state: Arc<AppState>,
|
||||
path: AgentRoutePath,
|
||||
credential: VerifiedMachineCredential,
|
||||
session_id: Option<String>,
|
||||
request_id: Option<Value>,
|
||||
},
|
||||
}
|
||||
|
||||
impl OutcomeHandler {
|
||||
fn publish(&self, status: StatusCode) {
|
||||
if let Ok(mut outcome) = self.outcome.lock() {
|
||||
*outcome = Some(status);
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&self) -> Option<StatusCode> {
|
||||
self.outcome.lock().ok()?.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandler for OutcomeHandler {
|
||||
async fn on_initialized(&self, _context: NotificationContext<RoleServer>) {
|
||||
if let Operation::Initialized { state, session_id } = &self.operation {
|
||||
let status = match state
|
||||
.sessions
|
||||
.mark_initialized(session_id, time::OffsetDateTime::now_utc())
|
||||
.await
|
||||
{
|
||||
Ok(true) => StatusCode::ACCEPTED,
|
||||
Ok(false) => StatusCode::NOT_FOUND,
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
self.publish(status);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_initialized_handler_completed();
|
||||
}
|
||||
}
|
||||
|
||||
async fn on_cancelled(
|
||||
&self,
|
||||
params: CancelledNotificationParam,
|
||||
_context: NotificationContext<RoleServer>,
|
||||
) {
|
||||
if let Operation::Cancelled {
|
||||
state,
|
||||
path,
|
||||
credential,
|
||||
session_id,
|
||||
request_id,
|
||||
} = &self.operation
|
||||
{
|
||||
let target = params.request_id.map(|id| {
|
||||
let typed = id.into_json_value();
|
||||
match (request_id, typed) {
|
||||
(Some(Value::Number(original)), Value::String(projected))
|
||||
if original.to_string() == projected =>
|
||||
{
|
||||
Value::Number(original.clone())
|
||||
}
|
||||
(_, typed) => typed,
|
||||
}
|
||||
});
|
||||
if let (Some(target), Some(session_id)) = (target, session_id.as_ref()) {
|
||||
let owned = match state.sessions.get(session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id: session_id.clone(),
|
||||
owner: credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map_or_else(String::new, |id| id.as_str().to_owned()),
|
||||
},
|
||||
&target,
|
||||
);
|
||||
}
|
||||
}
|
||||
self.publish(StatusCode::ACCEPTED);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_handler_completed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Capture(Mutex<Option<oneshot::Sender<NotificationContext<RoleServer>>>>);
|
||||
|
||||
impl ServerHandler for Capture {
|
||||
async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
|
||||
if let Ok(mut sender) = self.0.lock()
|
||||
&& let Some(sender) = sender.take()
|
||||
{
|
||||
let _ = sender.send(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn notification_context() -> Result<NotificationContext<RoleServer>, ()> {
|
||||
let message: ClientJsonRpcMessage = serde_json::from_value(serde_json::json!({
|
||||
"jsonrpc":"2.0", "method":"notifications/initialized"
|
||||
}))
|
||||
.map_err(|_| ())?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(message);
|
||||
let (sender, captured) = oneshot::channel();
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-internal", "1"),
|
||||
);
|
||||
let mut running =
|
||||
rmcp::service::serve_directly(Capture(Mutex::new(Some(sender))), transport, Some(info));
|
||||
let context = captured.await;
|
||||
let closed = running.close().await.is_ok();
|
||||
drop(receiver);
|
||||
if !closed {
|
||||
return Err(());
|
||||
}
|
||||
context.map_err(|_| ())
|
||||
}
|
||||
|
||||
pub(super) async fn initialized(state: Arc<AppState>, session_id: String) -> StatusCode {
|
||||
let handler = OutcomeHandler {
|
||||
operation: Operation::Initialized { state, session_id },
|
||||
outcome: Mutex::new(None),
|
||||
};
|
||||
initialized_with(&handler, &handler, notification_context()).await
|
||||
}
|
||||
|
||||
async fn initialized_with(
|
||||
sdk: &impl ServerHandler,
|
||||
outcome: &OutcomeHandler,
|
||||
context: impl std::future::Future<Output = Result<NotificationContext<RoleServer>, ()>>,
|
||||
) -> StatusCode {
|
||||
let Ok(context) = context.await else {
|
||||
return StatusCode::INTERNAL_SERVER_ERROR;
|
||||
};
|
||||
ServerHandler::on_initialized(sdk, context).await;
|
||||
let status = outcome.take();
|
||||
#[cfg(test)]
|
||||
if status.is_some() {
|
||||
super::dispatch_observer::sdk_initialized_handler_consumed();
|
||||
}
|
||||
status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
// Retain the SDK's typed interpretation and the exact original number used by its safe projection.
|
||||
pub(super) fn cancelled_params(
|
||||
value: &Value,
|
||||
) -> Option<(CancelledNotificationParam, Option<Value>)> {
|
||||
let original = value.get("requestId");
|
||||
let mut projected = Map::new();
|
||||
if let Some(id) = original {
|
||||
let safe = match id {
|
||||
Value::Number(number) if number.as_i64().is_none() => Value::String(number.to_string()),
|
||||
_ => id.clone(),
|
||||
};
|
||||
projected.insert("requestId".to_owned(), safe);
|
||||
}
|
||||
let typed = serde_json::from_value(Value::Object(projected)).ok()?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_params_decoded();
|
||||
let raw_number = original.filter(|id| id.is_number()).cloned();
|
||||
Some((typed, raw_number))
|
||||
}
|
||||
|
||||
pub(super) async fn cancelled(
|
||||
state: Arc<AppState>,
|
||||
path: AgentRoutePath,
|
||||
credential: VerifiedMachineCredential,
|
||||
session_id: Option<String>,
|
||||
params: CancelledNotificationParam,
|
||||
raw_number: Option<Value>,
|
||||
) {
|
||||
let request_id = raw_number;
|
||||
let handler = OutcomeHandler {
|
||||
operation: Operation::Cancelled {
|
||||
state,
|
||||
path,
|
||||
credential,
|
||||
session_id,
|
||||
request_id,
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
};
|
||||
cancelled_with(&handler, &handler, params, notification_context()).await;
|
||||
}
|
||||
|
||||
async fn cancelled_with(
|
||||
sdk: &impl ServerHandler,
|
||||
outcome: &OutcomeHandler,
|
||||
params: CancelledNotificationParam,
|
||||
context: impl std::future::Future<Output = Result<NotificationContext<RoleServer>, ()>>,
|
||||
) {
|
||||
let Ok(context) = context.await else {
|
||||
return;
|
||||
};
|
||||
// Cancellation is intentionally opaque: no outcome or bootstrap details reach the client.
|
||||
ServerHandler::on_cancelled(sdk, params, context).await;
|
||||
let status = outcome.take();
|
||||
if status.is_none() {
|
||||
tracing::warn!(name: "mcp.cancelled_handler.missing_outcome", "SDK cancellation handler did not publish an outcome");
|
||||
}
|
||||
#[cfg(test)]
|
||||
if status.is_some() {
|
||||
super::dispatch_observer::sdk_cancelled_handler_consumed();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_notification_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,31 +1,11 @@
|
||||
//! Lossless projection of legacy cancellation targets through the pinned SDK.
|
||||
|
||||
use rmcp::model::CancelledNotificationParam;
|
||||
use serde_json::{Map, Value};
|
||||
//! Test compatibility entry for the production notification decoder.
|
||||
use serde_json::Value;
|
||||
|
||||
pub(super) fn decode_cancelled_request_id(params: &Value) -> Option<Value> {
|
||||
let mut projection = Map::new();
|
||||
let original_id = params.get("requestId");
|
||||
if let Some(id) = original_id {
|
||||
// SDK IDs use i64; the temporary string never reaches the in-flight lookup.
|
||||
let projected = match id {
|
||||
Value::Number(number) if number.as_i64().is_none() => Value::String(number.to_string()),
|
||||
_ => id.clone(),
|
||||
};
|
||||
projection.insert("requestId".to_owned(), projected);
|
||||
}
|
||||
// Only requestId names a target; reason, _meta and extensions retain their ignore semantics.
|
||||
let decoded =
|
||||
serde_json::from_value::<CancelledNotificationParam>(Value::Object(projection)).ok()?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_cancelled_params_decoded();
|
||||
let id = decoded.request_id?;
|
||||
Some(match original_id {
|
||||
Some(Value::Number(number)) => Value::Number(number.clone()),
|
||||
_ => id.into_json_value(),
|
||||
})
|
||||
let (typed, raw_number) = super::rmcp_notifications::cancelled_params(params)?;
|
||||
let id = typed.request_id?;
|
||||
Some(raw_number.unwrap_or_else(|| id.into_json_value()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_progress_cancel_tests.rs"]
|
||||
mod tests;
|
||||
@@ -9,6 +9,7 @@ struct FaultStore {
|
||||
inner: PostgresTransportSessionStore,
|
||||
fail_get: AtomicBool,
|
||||
fail_mark: AtomicBool,
|
||||
delete_on_mark: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -44,6 +45,9 @@ impl TransportSessionStore for FaultStore {
|
||||
details: "test mark failure".into(),
|
||||
});
|
||||
}
|
||||
if self.delete_on_mark.load(Ordering::SeqCst) {
|
||||
self.inner.delete(id).await?;
|
||||
}
|
||||
self.inner.mark_initialized(id, now).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
@@ -68,6 +72,7 @@ async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
.unwrap(),
|
||||
fail_get: AtomicBool::new(false),
|
||||
fail_mark: AtomicBool::new(false),
|
||||
delete_on_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;
|
||||
@@ -150,6 +155,26 @@ async fn initialized_durable_transition_reconnect_and_store_failures() {
|
||||
assert_eq!(sdk(&h.counters), counts);
|
||||
store.fail_get.store(false, Ordering::SeqCst);
|
||||
assert!(!restarted.get(&pending).await.unwrap().unwrap().initialized);
|
||||
|
||||
// Session can disappear after admission/scoped reads but before the durable UPDATE.
|
||||
store.delete_on_mark.store(true, Ordering::SeqCst);
|
||||
let completed = h.counters.sdk_initialized_handler_completed();
|
||||
let consumed = h.counters.sdk_initialized_handler_consumed();
|
||||
let response = post(
|
||||
&h,
|
||||
Some(&pending),
|
||||
"application/json",
|
||||
initialized_notification(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 404);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_completed(),
|
||||
completed + 1
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_consumed(), consumed + 1);
|
||||
assert!(restarted.get(&pending).await.unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! #107 real HTTP contract for awaited legacy SDK notification handlers.
|
||||
use super::rmcp_progress_cancel_runtime_tests::fixtures::Endpoint;
|
||||
use super::support::*;
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Duration;
|
||||
|
||||
async fn legacy_session(h: &Endpoint) -> String {
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
None,
|
||||
&h.key,
|
||||
"application/json",
|
||||
legacy_initialize(801),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let session = response.headers()["MCP-Session-Id"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body: Value = json_body(response).await;
|
||||
assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION);
|
||||
session
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn initialized_handler_executes_and_is_consumed_by_real_http_caller() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = legacy_session(&h).await;
|
||||
let response = h
|
||||
.request(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
&h.key,
|
||||
"application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), 202, "legacy HTTP wire positive control");
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert!(h.sessions.retained(&session).await.unwrap().initialized);
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_completed(),
|
||||
1,
|
||||
"real awaited on_initialized must complete its durable operation"
|
||||
);
|
||||
assert_eq!(
|
||||
h.counters.sdk_initialized_handler_consumed(),
|
||||
1,
|
||||
"HTTP caller must consume the outcome of that same SDK handler"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_handler_executes_and_is_consumed_for_owned_active_call() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
let call = h.call(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
json!(802),
|
||||
Some(json!("cancel")),
|
||||
"text/event-stream",
|
||||
);
|
||||
let active = tokio::spawn(async move { call.send().await.unwrap().text().await.unwrap() });
|
||||
h.wait_started(1).await;
|
||||
h.cancel(&h.key, &session, json!({"requestId":802})).await;
|
||||
tokio::time::timeout(Duration::from_secs(2), active)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
h.counters.sdk_cancelled_handler_completed(),
|
||||
1,
|
||||
"real awaited on_cancelled must cancel the owned call"
|
||||
);
|
||||
assert_eq!(
|
||||
h.counters.sdk_cancelled_handler_consumed(),
|
||||
1,
|
||||
"HTTP caller must consume the outcome of that same SDK handler"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_notifications_remain_ack_only_without_legacy_handlers() {
|
||||
crank_test_support::postgres_schema_url_for_task("notification_handler", "t_2a52960d").await;
|
||||
let h = Endpoint::started().await;
|
||||
let before = 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());
|
||||
let response = h.request(MODERN_REVISION, None, &h.key, "application/json",
|
||||
json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":802,"_meta":modern_meta()}}))
|
||||
.send().await.unwrap();
|
||||
assert_eq!(response.status(), 202);
|
||||
assert!(response.bytes().await.unwrap().is_empty());
|
||||
assert_session_ops(
|
||||
"modern notification ACK",
|
||||
before,
|
||||
h.sessions.snapshot(),
|
||||
SessionOps {
|
||||
get: 0,
|
||||
create: 0,
|
||||
mark_initialized: 0,
|
||||
},
|
||||
);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_completed(), 0);
|
||||
assert_eq!(h.counters.sdk_initialized_handler_consumed(), 0);
|
||||
assert_eq!(h.counters.sdk_cancelled_handler_completed(), 0);
|
||||
assert_eq!(h.counters.sdk_cancelled_handler_consumed(), 0);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//! Direct controls of the production awaited notification boundary.
|
||||
use super::*;
|
||||
use crate::session::{
|
||||
InMemorySessionStore, SessionState, SessionStoreError, TransportSessionStore,
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Store {
|
||||
inner: InMemorySessionStore,
|
||||
marks: AtomicUsize,
|
||||
reads: AtomicUsize,
|
||||
entered: AtomicBool,
|
||||
dropped: AtomicBool,
|
||||
pending: AtomicBool,
|
||||
fail_get: AtomicBool,
|
||||
gate: tokio::sync::Notify,
|
||||
}
|
||||
struct Witness<'a>(&'a AtomicBool);
|
||||
impl Drop for Witness<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, SeqCst);
|
||||
}
|
||||
}
|
||||
impl Store {
|
||||
async fn wait(&self) {
|
||||
if self.pending.load(SeqCst) {
|
||||
let _witness = Witness(&self.dropped);
|
||||
self.entered.store(true, SeqCst);
|
||||
self.gate.notified().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl TransportSessionStore for Store {
|
||||
async fn create(
|
||||
&self,
|
||||
v: &str,
|
||||
w: &str,
|
||||
a: &str,
|
||||
e: bool,
|
||||
n: OffsetDateTime,
|
||||
x: Option<OffsetDateTime>,
|
||||
) -> Result<String, SessionStoreError> {
|
||||
self.inner.create(v, w, a, e, n, x).await
|
||||
}
|
||||
async fn get(&self, id: &str) -> Result<Option<SessionState>, SessionStoreError> {
|
||||
self.wait().await;
|
||||
self.reads.fetch_add(1, SeqCst);
|
||||
if self.fail_get.load(SeqCst) {
|
||||
return Err(SessionStoreError {
|
||||
details: "test read refusal".into(),
|
||||
});
|
||||
}
|
||||
self.inner.get(id).await
|
||||
}
|
||||
async fn mark_initialized(
|
||||
&self,
|
||||
id: &str,
|
||||
n: OffsetDateTime,
|
||||
) -> Result<bool, SessionStoreError> {
|
||||
self.wait().await;
|
||||
self.marks.fetch_add(1, SeqCst);
|
||||
self.inner.mark_initialized(id, n).await
|
||||
}
|
||||
async fn delete(&self, id: &str) -> Result<bool, SessionStoreError> {
|
||||
self.inner.delete(id).await
|
||||
}
|
||||
async fn cleanup_expired(&self, n: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.cleanup_expired(n).await
|
||||
}
|
||||
async fn active_count(&self, n: OffsetDateTime) -> Result<u64, SessionStoreError> {
|
||||
self.inner.active_count(n).await
|
||||
}
|
||||
}
|
||||
async fn fixture() -> (Arc<AppState>, Arc<Store>, String) {
|
||||
let mut state = (*super::super::rmcp_tools_tests::test_state().await).clone();
|
||||
let store = Arc::new(Store::default());
|
||||
let id = store
|
||||
.create(
|
||||
"2025-11-25",
|
||||
"w",
|
||||
"a",
|
||||
false,
|
||||
OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
state.sessions = store.clone();
|
||||
(Arc::new(state), store, id)
|
||||
}
|
||||
fn initialized_handler(state: Arc<AppState>, id: &str) -> OutcomeHandler {
|
||||
OutcomeHandler {
|
||||
operation: Operation::Initialized {
|
||||
state,
|
||||
session_id: id.to_owned(),
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
fn cancelled_handler(state: Arc<AppState>, id: &str, raw: Option<Value>) -> OutcomeHandler {
|
||||
OutcomeHandler {
|
||||
operation: Operation::Cancelled {
|
||||
state,
|
||||
path: AgentRoutePath {
|
||||
workspace_slug: "w".into(),
|
||||
agent_slug: "a".into(),
|
||||
},
|
||||
credential: VerifiedMachineCredential {
|
||||
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
|
||||
max_security_level: crank_core::OperationSecurityLevel::Standard,
|
||||
scopes: vec![],
|
||||
platform_api_key_id: None,
|
||||
},
|
||||
session_id: Some(id.to_owned()),
|
||||
request_id: raw,
|
||||
},
|
||||
outcome: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
struct Noop;
|
||||
impl ServerHandler for Noop {}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_noop_and_bootstrap_failure_have_no_effect() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let init = initialized_handler(state.clone(), &id);
|
||||
assert_eq!(
|
||||
initialized_with(&Noop, &init, notification_context()).await,
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
initialized_with(&init, &init, async { Err(()) }).await,
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
);
|
||||
let cancel = cancelled_handler(state.clone(), &id, None);
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(1))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":1})).unwrap();
|
||||
cancelled_with(&Noop, &cancel, params.clone(), notification_context()).await;
|
||||
cancelled_with(&cancel, &cancel, params, async { Err(()) }).await;
|
||||
assert!(cancel.take().is_none());
|
||||
assert_eq!(store.marks.load(SeqCst), 0);
|
||||
assert_eq!(store.reads.load(SeqCst), 0);
|
||||
assert!(!store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
// Positive control: exactly one durable operation, and the caller drains its outcome.
|
||||
assert_eq!(
|
||||
initialized_with(&init, &init, notification_context()).await,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
assert_eq!(store.marks.load(SeqCst), 1);
|
||||
assert!(init.take().is_none());
|
||||
assert!(store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
}
|
||||
|
||||
struct Mutate(Arc<OutcomeHandler>, NumberOrString);
|
||||
impl ServerHandler for Mutate {
|
||||
async fn on_cancelled(
|
||||
&self,
|
||||
mut p: CancelledNotificationParam,
|
||||
ctx: NotificationContext<RoleServer>,
|
||||
) {
|
||||
assert!(ctx.peer.is_transport_closed());
|
||||
p.request_id = Some(self.1.clone());
|
||||
ServerHandler::on_cancelled(self.0.as_ref(), p, ctx).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_typed_target_mutation_and_raw_number_separation() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
for raw in [
|
||||
serde_json::json!(18446744073709551615_u64),
|
||||
serde_json::json!(1.25),
|
||||
] {
|
||||
let numeric = state.in_flight.register(&scope, &raw).unwrap();
|
||||
let text = state
|
||||
.in_flight
|
||||
.register(&scope, &Value::String(raw.to_string()))
|
||||
.unwrap();
|
||||
let changed = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(42))
|
||||
.unwrap();
|
||||
let (params, original) = cancelled_params(&serde_json::json!({"requestId":raw})).unwrap();
|
||||
let h = Arc::new(cancelled_handler(state.clone(), &id, original));
|
||||
let mutation = Mutate(h.clone(), NumberOrString::Number(42));
|
||||
cancelled_with(
|
||||
&mutation,
|
||||
h.as_ref(),
|
||||
params.clone(),
|
||||
notification_context(),
|
||||
)
|
||||
.await;
|
||||
assert!(futures_util::poll!(Box::pin(changed.cancel_signal().cancelled())).is_ready());
|
||||
assert!(futures_util::poll!(Box::pin(numeric.cancel_signal().cancelled())).is_pending());
|
||||
assert!(futures_util::poll!(Box::pin(text.cancel_signal().cancelled())).is_pending());
|
||||
assert!(h.take().is_none());
|
||||
cancelled_with(h.as_ref(), h.as_ref(), params, notification_context()).await;
|
||||
assert!(futures_util::poll!(Box::pin(numeric.cancel_signal().cancelled())).is_ready());
|
||||
assert!(futures_util::poll!(Box::pin(text.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
assert_eq!(
|
||||
store.reads.load(SeqCst),
|
||||
4,
|
||||
"one lookup per real callback, no bootstrap effects"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_store_read_refusal_does_not_cancel() {
|
||||
let (state, store, id) = fixture().await;
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(7))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":7})).unwrap();
|
||||
let h = cancelled_handler(state, &id, None);
|
||||
store.fail_get.store(true, SeqCst);
|
||||
ServerHandler::on_cancelled(&h, params, notification_context().await.unwrap()).await;
|
||||
assert_eq!(h.take(), Some(StatusCode::ACCEPTED));
|
||||
assert_eq!(store.reads.load(SeqCst), 1);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_handler_pending_store_drop_stops_initialized_and_cancelled() {
|
||||
let (state, store, id) = fixture().await;
|
||||
for cancel in [false, true] {
|
||||
store.pending.store(true, SeqCst);
|
||||
store.entered.store(false, SeqCst);
|
||||
store.dropped.store(false, SeqCst);
|
||||
let h = if cancel {
|
||||
cancelled_handler(state.clone(), &id, None)
|
||||
} else {
|
||||
initialized_handler(state.clone(), &id)
|
||||
};
|
||||
let scope = super::super::lifecycle::InFlightScope {
|
||||
session_id: id.clone(),
|
||||
owner: String::new(),
|
||||
};
|
||||
let entry = state
|
||||
.in_flight
|
||||
.register(&scope, &serde_json::json!(7))
|
||||
.unwrap();
|
||||
let (params, _) = cancelled_params(&serde_json::json!({"requestId":7})).unwrap();
|
||||
let mut future = Box::pin(async {
|
||||
if cancel {
|
||||
cancelled_with(&h, &h, params, notification_context()).await;
|
||||
} else {
|
||||
initialized_with(&h, &h, notification_context()).await;
|
||||
}
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
tokio::select! {
|
||||
_ = &mut future => panic!("pending operation completed"),
|
||||
_ = async { while !store.entered.load(SeqCst) { tokio::task::yield_now().await; } } => {}
|
||||
}
|
||||
}).await.unwrap();
|
||||
assert!(!store.dropped.load(SeqCst));
|
||||
drop(future);
|
||||
assert!(
|
||||
store.dropped.load(SeqCst),
|
||||
"the actual store future belongs to this await"
|
||||
);
|
||||
store.gate.notify_waiters();
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(store.marks.load(SeqCst), 0);
|
||||
assert_eq!(store.reads.load(SeqCst), 0);
|
||||
assert!(h.take().is_none());
|
||||
assert!(!store.inner.get(&id).await.unwrap().unwrap().initialized);
|
||||
assert!(futures_util::poll!(Box::pin(entry.cancel_signal().cancelled())).is_pending());
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ Negotiation-handler-срез #107 поверх rc.36/rmcp3.9.0 заменяет
|
||||
|
||||
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.
|
||||
|
||||
Notification handler-срез #107 на базе rc.37/rmcp3.9.0 заменяет DTO-only execution legacy `notifications/initialized` и `notifications/cancelled` прямым await настоящих `ServerHandler::on_initialized/on_cancelled` в `app/rmcp_notifications.rs`. Ближайшие подключённые consumers — `dispatch::handle_initialized_notification` и `legacy_dispatch::handle_cancelled_notification` штатного `build_app` HTTP. Durable mark и scoped lookup/cancel выполняются внутри overrides; caller забирает request-local outcome после await, сохраняя empty202/400/404/500 и непрозрачный cancellation ACK. Инертный capture-bootstrap получает настоящий SDK NotificationContext и закрывается до рабочего handler; closed Peer callbacks не поддерживает. No-op/missing outcome, typed-target mutation, numeric/string separation, bootstrap refusal и pending store drop controls дополняют HTTP completed/consumed ATDD; PostgreSQL reconnect/read/write refusal и исчезновение session между get/mark сохраняют прежние guards. Drop прекращает polling request-owned операции, но не обещает rollback уже отправленного SQL или отзыв выполненной отмены. Modern notifications остаются ACK-only без sessions/domain; storage/TTL/reconnect, capabilities, progress/logging/signals/subscriptions и transport не заменены SDK defaults. Старый cancellation decoder оставлен только как test entry к новому production decoder. #107 остаётся open/partial; full/load/external-client qualification, bootstrap performance, #108/4.7 и production не входят в срез.
|
||||
|
||||
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 не запускаются.
|
||||
|
||||
Inbound-response-срез #107 на базе rc.31/rmcp3.9.0 подключает no-method ветку общего envelope guard к `protocol/response_sdk.rs`: реальные `JsonRpcResponse<Value>`/`JsonRpcError` определяют response classification и ранний HTTP202 ACK штатного `build_app` POST обеих revisions. Сохранены object-only result без обязательного resultType, exclusivity result/error, optional error id, произвольные data/params/extensions и любые JSON number id/code; только SDK-несовместимые числа получают внутренние surrogates после проверки исходного wire-предиката, raw message не меняется. Заменён handwritten response classifier/error-object parser. Обнаруженный ATDD обход credentials ранним ACK устранён свежей read-авторизацией no-method сообщений до SDK decode; порядок method-bearing запросов не меняется. Origin/Accept/ambiguous carrier checks предшествуют decode/ACK, ACK остаётся до era/session resolution без session/domain вызовов. HTTP wire и SDK decoded/consumed oracles проверяются отдельно. Domain/generic handler execution, session storage/TTL/reconnect, transport и feature qualification остаются вне среза; полный #107 остаётся open, #108/4.7/production не запускаются.
|
||||
|
||||
Reference in new issue
Block a user