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

This commit is contained in:
bsodfather committed 2026-11-14 00:00:27 +00:00
1 parent 986cd78b96
commit fd76aaf676
10 files changed
+735 -52

No files matched your search

@@ -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(&params(message));
let Some((typed, raw_number)) = super::rmcp_notifications::cancelled_params(&params(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;