//! 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>, } enum Operation { Initialized { state: Arc, session_id: String, }, Cancelled { state: Arc, path: AgentRoutePath, credential: VerifiedMachineCredential, session_id: Option, request_id: Option, }, } impl OutcomeHandler { fn publish(&self, status: StatusCode) { if let Ok(mut outcome) = self.outcome.lock() { *outcome = Some(status); } } fn take(&self) -> Option { self.outcome.lock().ok()?.take() } } impl ServerHandler for OutcomeHandler { async fn on_initialized(&self, _context: NotificationContext) { 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, ) { 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>>>); impl ServerHandler for Capture { async fn on_initialized(&self, context: NotificationContext) { if let Ok(mut sender) = self.0.lock() && let Some(sender) = sender.take() { let _ = sender.send(context); } } } async fn notification_context() -> Result, ()> { let message: ClientJsonRpcMessage = serde_json::from_value(serde_json::json!({ "jsonrpc":"2.0", "method":"notifications/initialized" })) .map_err(|_| ())?; let (transport, receiver) = rmcp::transport::OneshotTransport::::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, 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, ()>>, ) -> 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)> { 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, path: AgentRoutePath, credential: VerifiedMachineCredential, session_id: Option, params: CancelledNotificationParam, raw_number: Option, ) { 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, ()>>, ) { 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;