Compare commits
8
Commits
v0.4.0-rc.37
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ce3c2bb97 | ||
|
|
48436538f1 | ||
|
|
8f494679b8 | ||
|
|
0755e6e8e8 | ||
|
|
d01bdf019c | ||
|
|
22637861c3 | ||
|
|
7aab666aaa | ||
|
|
fd76aaf676 |
No files matched your search
@@ -41,14 +41,20 @@ mod rmcp_http;
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_http_tests.rs"]
|
||||
mod rmcp_http_tests;
|
||||
mod rmcp_logging;
|
||||
mod rmcp_negotiation;
|
||||
mod rmcp_notifications;
|
||||
#[cfg(test)]
|
||||
mod rmcp_progress_cancel;
|
||||
mod rmcp_progress_peer;
|
||||
mod rmcp_prompts;
|
||||
mod rmcp_prompts_projection;
|
||||
mod rmcp_resources;
|
||||
mod rmcp_resources_projection;
|
||||
#[cfg(test)]
|
||||
mod rmcp_session_tests;
|
||||
mod rmcp_subscriptions;
|
||||
mod rmcp_subscriptions_output;
|
||||
#[cfg(test)]
|
||||
mod rmcp_tools;
|
||||
mod rmcp_tools_projection;
|
||||
|
||||
@@ -691,8 +691,8 @@ pub(super) async fn handle_modern_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let accepted = match filter.notifications.accepted() {
|
||||
crate::protocol::FilterOutcome::Accepted(accepted) => accepted,
|
||||
match filter.notifications.accepted() {
|
||||
crate::protocol::FilterOutcome::Accepted(_) => {}
|
||||
crate::protocol::FilterOutcome::Invalid(detail) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
@@ -719,18 +719,19 @@ pub(super) async fn handle_modern_request(
|
||||
else {
|
||||
return StatusCode::TOO_MANY_REQUESTS.into_response();
|
||||
};
|
||||
let acknowledged = crate::protocol::acknowledged_frame(&subscription_id, accepted);
|
||||
let receiver = crate::protocol::spawn_signal_watch(
|
||||
let (acknowledged, receiver) = match super::rmcp_subscriptions::start(
|
||||
Arc::clone(state),
|
||||
crate::protocol::Watch {
|
||||
workspace_slug: path.workspace_slug.clone(),
|
||||
agent_slug: path.agent_slug.clone(),
|
||||
signals: accepted,
|
||||
wire: crate::protocol::Wire::Modern(subscription_id),
|
||||
legacy_stream: None,
|
||||
deadline: None,
|
||||
},
|
||||
);
|
||||
path.workspace_slug.clone(),
|
||||
path.agent_slug.clone(),
|
||||
subscription_id,
|
||||
filter.notifications.into_sdk(),
|
||||
super::rmcp_subscriptions::project_meta(message),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(stream) => stream,
|
||||
Err(error) => return sdk_error_response(message, response_mode, version, error),
|
||||
};
|
||||
let stream = crate::protocol::frames_stream(vec![acknowledged], receiver, permit);
|
||||
|
||||
sse_response(StatusCode::OK, stream, None, Some(version))
|
||||
@@ -870,15 +871,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(),
|
||||
|
||||
@@ -82,11 +82,18 @@ pub(crate) struct CounterSet {
|
||||
sdk_logging_dispatch: AtomicUsize,
|
||||
sdk_logging_level: AtomicUsize,
|
||||
sdk_logging_notification: AtomicUsize,
|
||||
sdk_logging_handler_completed: AtomicUsize,
|
||||
sdk_logging_handler_consumed: AtomicUsize,
|
||||
sdk_progress_notification: AtomicUsize,
|
||||
sdk_cancelled_params: AtomicUsize,
|
||||
sdk_subscriptions_listen: AtomicUsize,
|
||||
sdk_subscriptions_acknowledged: AtomicUsize,
|
||||
sdk_signal_notification: AtomicUsize,
|
||||
sdk_subscription_listen_entered: AtomicUsize,
|
||||
sdk_subscription_handler_completed: AtomicUsize,
|
||||
sdk_subscription_handler_consumed: AtomicUsize,
|
||||
sdk_subscription_notification_consumed: AtomicUsize,
|
||||
sdk_subscription_owner_completed: AtomicUsize,
|
||||
sdk_jsonrpc_response: AtomicUsize,
|
||||
sdk_jsonrpc_error: AtomicUsize,
|
||||
|
||||
@@ -98,6 +105,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 +196,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)
|
||||
}
|
||||
@@ -219,6 +244,25 @@ impl CounterSet {
|
||||
pub(crate) fn sdk_subscriptions_acknowledged(&self) -> usize {
|
||||
self.sdk_subscriptions_acknowledged.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_subscription_listen_entered(&self) -> usize {
|
||||
self.sdk_subscription_listen_entered.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscription_handler_completed(&self) -> usize {
|
||||
self.sdk_subscription_handler_completed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscription_handler_consumed(&self) -> usize {
|
||||
self.sdk_subscription_handler_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscription_notification_consumed(&self) -> usize {
|
||||
self.sdk_subscription_notification_consumed
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_subscription_owner_completed(&self) -> usize {
|
||||
self.sdk_subscription_owner_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sdk_signal_notification(&self) -> usize {
|
||||
self.sdk_signal_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -242,6 +286,14 @@ impl CounterSet {
|
||||
self.sdk_logging_notification.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_handler_completed(&self) -> usize {
|
||||
self.sdk_logging_handler_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_logging_handler_consumed(&self) -> usize {
|
||||
self.sdk_logging_handler_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
|
||||
self.sdk_completion_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
@@ -545,9 +597,23 @@ pub(crate) fn sdk_logging_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_logging_notification);
|
||||
}
|
||||
|
||||
/// Mark after the real logging handler has completed its awaited operation and built its result.
|
||||
pub(crate) fn sdk_logging_handler_completed() {
|
||||
increment(|counters| &counters.sdk_logging_handler_completed);
|
||||
}
|
||||
|
||||
/// Mark only after the caller consumes the actual SDK handler Result.
|
||||
pub(crate) fn sdk_logging_handler_consumed() {
|
||||
increment(|counters| &counters.sdk_logging_handler_consumed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_logging_runtime_tests.rs"]
|
||||
mod rmcp_logging_runtime_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_logging_handler_runtime_tests.rs"]
|
||||
mod rmcp_logging_handler_runtime_tests;
|
||||
|
||||
/// Mark only after successfully serializing real SDK ProgressNotificationParam params.
|
||||
pub(crate) fn sdk_progress_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_progress_notification);
|
||||
@@ -573,6 +639,28 @@ pub(crate) fn sdk_subscriptions_acknowledged_serialized() {
|
||||
increment(|counters| &counters.sdk_subscriptions_acknowledged);
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_subscription_listen_entered() {
|
||||
increment(|c| &c.sdk_subscription_listen_entered);
|
||||
}
|
||||
pub(crate) fn sdk_subscription_handler_completed() {
|
||||
increment(|c| &c.sdk_subscription_handler_completed);
|
||||
}
|
||||
pub(crate) fn sdk_subscription_handler_consumed() {
|
||||
increment(|c| &c.sdk_subscription_handler_consumed);
|
||||
}
|
||||
pub(crate) fn sdk_subscription_notification_consumed() {
|
||||
increment(|c| &c.sdk_subscription_notification_consumed);
|
||||
}
|
||||
pub(crate) fn sdk_subscription_owner_completed() {
|
||||
increment(|c| &c.sdk_subscription_owner_completed);
|
||||
}
|
||||
|
||||
#[path = "../rmcp_signals_test_support.rs"]
|
||||
mod signals_test_support;
|
||||
|
||||
#[path = "../rmcp_subscription_handler_runtime_tests.rs"]
|
||||
mod rmcp_subscription_handler_runtime_tests;
|
||||
|
||||
pub(crate) fn sdk_signal_notification_serialized() {
|
||||
increment(|counters| &counters.sdk_signal_notification);
|
||||
}
|
||||
@@ -644,9 +732,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);
|
||||
|
||||
@@ -31,11 +31,11 @@ use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
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,
|
||||
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, handle_logging_command,
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, INVALID_LEVEL,
|
||||
Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome,
|
||||
RequestIdentity, ResourceReadCommand, ResourcesCommand, ResourcesListCommand,
|
||||
ResourcesOutcome, ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand,
|
||||
ToolsListCommand,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -727,30 +727,23 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||
LoggingOutcome::Applied(level) => {
|
||||
crate::protocol::set_active_level(Some(level));
|
||||
crate::protocol::note(
|
||||
crate::protocol::LogLevel::Notice,
|
||||
EVENT_LEVEL_APPLIED,
|
||||
"applied",
|
||||
);
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), json!({})),
|
||||
let request = match command.validate() {
|
||||
Ok(request) => request,
|
||||
Err(detail) => {
|
||||
return super::dispatch::sdk_error_response(
|
||||
message,
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
&session.protocol_version,
|
||||
rmcp::ErrorData::invalid_params(detail, None),
|
||||
);
|
||||
}
|
||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
}
|
||||
};
|
||||
super::rmcp_logging::response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
super::rmcp_logging::set_level(&state, &session.id, request).await,
|
||||
)
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
@@ -802,25 +795,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()
|
||||
}
|
||||
@@ -34,8 +34,7 @@ use axum::{
|
||||
};
|
||||
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
||||
use futures_util::stream;
|
||||
use rmcp::model::{NumberOrString, ProgressNotificationParam};
|
||||
use serde_json::{Number, Value, json};
|
||||
use serde_json::{Number, Value};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
@@ -83,15 +82,23 @@ impl ProgressToken {
|
||||
}
|
||||
}
|
||||
|
||||
fn sdk_token(&self) -> NumberOrString {
|
||||
#[cfg(test)]
|
||||
pub(super) fn sdk_token(&self) -> rmcp::model::NumberOrString {
|
||||
match self {
|
||||
Self::Text(text) => NumberOrString::String(text.clone().into()),
|
||||
Self::Text(text) => rmcp::model::NumberOrString::String(text.clone().into()),
|
||||
Self::Number(number) => number.as_i64().map_or_else(
|
||||
|| NumberOrString::String(number.to_string().into()),
|
||||
NumberOrString::Number,
|
||||
|| rmcp::model::NumberOrString::String(number.to_string().into()),
|
||||
rmcp::model::NumberOrString::Number,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn raw(&self) -> Value {
|
||||
match self {
|
||||
Self::Text(text) => Value::String(text.clone()),
|
||||
Self::Number(number) => Value::Number(number.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The progress token of one request parameters object, already validated and bounded. The adapters
|
||||
@@ -133,28 +140,18 @@ pub(crate) struct ProgressEvent {
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
|
||||
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
|
||||
pub(super) fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
||||
let sdk_params = ProgressNotificationParam::new(
|
||||
rmcp::model::ProgressToken(token.sdk_token()),
|
||||
event.progress as f64,
|
||||
)
|
||||
.with_message(event.message);
|
||||
let mut params = serde_json::to_value(sdk_params)
|
||||
.expect("finite progress and string/number token are serializable SDK params");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_progress_notification_serialized();
|
||||
// SDK uses i64 tokens and f64 progress; restore the original JSON numbers before wire delivery.
|
||||
if let ProgressToken::Number(number) = token {
|
||||
params["progressToken"] = Value::Number(number.clone());
|
||||
#[cfg(test)]
|
||||
impl ProgressEvent {
|
||||
pub(super) fn sdk_params(
|
||||
&self,
|
||||
token: &ProgressToken,
|
||||
) -> rmcp::model::ProgressNotificationParam {
|
||||
rmcp::model::ProgressNotificationParam::new(
|
||||
rmcp::model::ProgressToken(token.sdk_token()),
|
||||
self.progress as f64,
|
||||
)
|
||||
.with_message(self.message)
|
||||
}
|
||||
params["progress"] = Value::from(event.progress);
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/progress",
|
||||
"params": params,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -421,7 +418,8 @@ pub(crate) async fn run_tool_call(
|
||||
call,
|
||||
events: progress_events,
|
||||
cancel: lifecycle.cancel.clone(),
|
||||
token,
|
||||
peer: Some(super::rmcp_progress_peer::ProgressPeer::start(token.raw())),
|
||||
outcome: None,
|
||||
message,
|
||||
protocol_version: protocol_version.clone(),
|
||||
pending: VecDeque::new(),
|
||||
@@ -474,7 +472,8 @@ struct CallStream {
|
||||
call: Pin<Box<dyn Future<Output = super::rmcp_tools_runtime::Outcome> + Send>>,
|
||||
events: mpsc::Receiver<ProgressEvent>,
|
||||
cancel: CancelSignal,
|
||||
token: ProgressToken,
|
||||
peer: Option<super::rmcp_progress_peer::ProgressPeer>,
|
||||
outcome: Option<super::rmcp_tools_runtime::Outcome>,
|
||||
message: Value,
|
||||
protocol_version: String,
|
||||
pending: VecDeque<Event>,
|
||||
@@ -511,55 +510,101 @@ async fn next_event_in_scope(
|
||||
return None;
|
||||
}
|
||||
|
||||
let step = {
|
||||
let CallStream {
|
||||
call,
|
||||
events,
|
||||
cancel,
|
||||
..
|
||||
} = &mut call;
|
||||
tokio::select! {
|
||||
biased;
|
||||
Some(event) = events.recv() => Step::Progress(event),
|
||||
outcome = call => Step::Outcome(outcome),
|
||||
_ = cancel.cancelled() => Step::Cancelled,
|
||||
}
|
||||
};
|
||||
loop {
|
||||
let step = if let Some(outcome) = call.outcome.take() {
|
||||
Step::Outcome(outcome)
|
||||
} else {
|
||||
let CallStream {
|
||||
call,
|
||||
events,
|
||||
cancel,
|
||||
..
|
||||
} = &mut call;
|
||||
tokio::select! {
|
||||
biased;
|
||||
Some(event) = events.recv() => Step::Progress(event),
|
||||
outcome = call => Step::Outcome(outcome),
|
||||
_ = cancel.cancelled() => Step::Cancelled,
|
||||
}
|
||||
};
|
||||
|
||||
match step {
|
||||
Step::Progress(event) => {
|
||||
let frame = progress_frame(&call.token, &event);
|
||||
Some((Ok(Event::default().data(frame.to_string())), call))
|
||||
}
|
||||
Step::Outcome(outcome) => {
|
||||
call.finished = true;
|
||||
let payload = match sdk_tools_payload(&call.message, &call.protocol_version, outcome) {
|
||||
ToolCommandPayload::Ok(payload) => payload,
|
||||
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
||||
};
|
||||
// The same projection point the single response uses, so a streamed answer delivers the
|
||||
// same closed `notifications/message` (Story 3.18) before its terminal frame.
|
||||
crate::transport::note_logging_outcome(&payload);
|
||||
for notification in crate::protocol::take_notifications() {
|
||||
match step {
|
||||
Step::Progress(event) => {
|
||||
let Some(peer) = &mut call.peer else { continue };
|
||||
// One send in flight; keep driving the original domain future/deadline, never a task.
|
||||
let delivery = {
|
||||
let notify = peer.notify(event.progress, event.message);
|
||||
tokio::pin!(notify);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut notify => break Some(result),
|
||||
outcome = &mut call.call, if call.outcome.is_none() => {
|
||||
let expired = is_deadline(&outcome);
|
||||
call.outcome = Some(outcome);
|
||||
if expired { break None; }
|
||||
}
|
||||
_ = call.cancel.cancelled() => return None,
|
||||
}
|
||||
}
|
||||
};
|
||||
match delivery {
|
||||
Some(Ok(frame)) => {
|
||||
return Some((Ok(Event::default().data(frame.to_string())), call));
|
||||
}
|
||||
// Progress is optional: no retry, handwritten fallback or replay of the Tool.
|
||||
Some(Err(_)) | None => {
|
||||
if let Some(peer) = call.peer.take() {
|
||||
peer.finish().await;
|
||||
}
|
||||
call.events.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Step::Outcome(outcome) => {
|
||||
call.finished = true;
|
||||
if let Some(peer) = call.peer.take() {
|
||||
peer.finish().await;
|
||||
}
|
||||
let payload =
|
||||
match sdk_tools_payload(&call.message, &call.protocol_version, outcome) {
|
||||
ToolCommandPayload::Ok(payload) => payload,
|
||||
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
||||
};
|
||||
// The same projection point the single response uses, so a streamed answer delivers the
|
||||
// same closed `notifications/message` (Story 3.18) before its terminal frame.
|
||||
crate::transport::note_logging_outcome(&payload);
|
||||
for notification in crate::protocol::take_notifications() {
|
||||
call.pending
|
||||
.push_back(Event::default().data(notification.to_string()));
|
||||
}
|
||||
call.pending
|
||||
.push_back(Event::default().data(notification.to_string()));
|
||||
.push_back(Event::default().data(payload.to_string()));
|
||||
return Some((Ok(call.pending.pop_front().expect("queued frame")), call));
|
||||
}
|
||||
Step::Cancelled => {
|
||||
call.finished = true;
|
||||
call.pending.clear();
|
||||
return None;
|
||||
}
|
||||
call.pending
|
||||
.push_back(Event::default().data(payload.to_string()));
|
||||
Some((Ok(call.pending.pop_front().expect("queued frame")), call))
|
||||
}
|
||||
Step::Cancelled => {
|
||||
call.finished = true;
|
||||
call.pending.clear();
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_deadline(outcome: &super::rmcp_tools_runtime::Outcome) -> bool {
|
||||
matches!(outcome, super::rmcp_tools_runtime::Outcome::Call(result)
|
||||
if result.structured_content.as_ref().is_some_and(|value|
|
||||
value["error"]["code"] == "upstream_timeout"))
|
||||
}
|
||||
|
||||
fn jsonrpc_internal_error(message: &Value) -> Value {
|
||||
crate::jsonrpc::jsonrpc_error(request_id(message), -32603, "internal server error")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_progress_stream_tests.rs"]
|
||||
mod stream_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lifecycle_tests.rs"]
|
||||
mod tests;
|
||||
@@ -2,13 +2,14 @@
|
||||
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn token(value: Value) -> Option<ProgressToken> {
|
||||
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
||||
for wire_token in [
|
||||
"\"token\"",
|
||||
"-7",
|
||||
@@ -19,13 +20,9 @@ fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
||||
] {
|
||||
let value: Value = serde_json::from_str(wire_token).unwrap();
|
||||
for progress in [2, 9_007_199_254_740_993, u64::MAX] {
|
||||
let frame = progress_frame(
|
||||
&token(value.clone()).unwrap(),
|
||||
&ProgressEvent {
|
||||
progress,
|
||||
message: "execution_dispatched",
|
||||
},
|
||||
);
|
||||
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(value.clone());
|
||||
let frame = peer.notify(progress, "execution_dispatched").await.unwrap();
|
||||
peer.finish().await;
|
||||
assert_eq!(frame["params"]["progressToken"].to_string(), wire_token);
|
||||
assert_eq!(
|
||||
frame["params"]["progress"].to_string(),
|
||||
@@ -123,14 +120,15 @@ async fn without_a_token_no_progress_is_produced_at_all() {
|
||||
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
|
||||
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
|
||||
/// `total` absent because this server never invents one.
|
||||
#[test]
|
||||
fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||
#[tokio::test]
|
||||
async fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||
let event = ProgressEvent {
|
||||
progress: 2,
|
||||
message: Phase::Authorized.message(),
|
||||
};
|
||||
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!("tok-2"));
|
||||
assert_eq!(
|
||||
progress_frame(&ProgressToken::Text("tok-2".to_owned()), &event),
|
||||
peer.notify(event.progress, event.message).await.unwrap(),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/progress",
|
||||
@@ -141,10 +139,13 @@ fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||
}
|
||||
})
|
||||
);
|
||||
peer.finish().await;
|
||||
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!(7));
|
||||
assert_eq!(
|
||||
progress_frame(&ProgressToken::Number(7.into()), &event)["params"]["progressToken"],
|
||||
peer.notify(event.progress, event.message).await.unwrap()["params"]["progressToken"],
|
||||
json!(7)
|
||||
);
|
||||
peer.finish().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Request-owned SDK implementation of the legacy `logging/setLevel` handler.
|
||||
// The pinned legacy revision still requires this deprecated SDK method.
|
||||
#![allow(deprecated)]
|
||||
use super::AppState;
|
||||
use crate::protocol::{self, LogLevel};
|
||||
use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct LoggingHandler {
|
||||
store: Arc<protocol::LogLevelStore>,
|
||||
session_id: String,
|
||||
}
|
||||
|
||||
impl ServerHandler for LoggingHandler {
|
||||
async fn set_level(
|
||||
&self,
|
||||
request: SetLevelRequestParams,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
#[allow(deprecated)]
|
||||
let level: LogLevel = request.level.into();
|
||||
self.store.set(&self.session_id, level);
|
||||
protocol::set_active_level(Some(level));
|
||||
protocol::note(LogLevel::Notice, protocol::EVENT_LEVEL_APPLIED, "applied");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_completed();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_context() -> Result<RequestContext<RoleServer>, ErrorData> {
|
||||
let ping: ClientJsonRpcMessage = serde_json::from_value(serde_json::json!({
|
||||
"jsonrpc":"2.0", "id":1, "method":"ping"
|
||||
}))
|
||||
.map_err(|_| ErrorData::internal_error("logging handler unavailable", None))?;
|
||||
let (transport, receiver) = rmcp::transport::OneshotTransport::<RoleServer>::new(ping);
|
||||
let info = InitializeRequestParams::new(
|
||||
ClientCapabilities::default(),
|
||||
Implementation::new("crank-logging-context", "1"),
|
||||
);
|
||||
#[derive(Clone)]
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
let mut running = rmcp::service::serve_directly(Bootstrap, transport, Some(info));
|
||||
let peer = running.peer().clone();
|
||||
running
|
||||
.close()
|
||||
.await
|
||||
.map_err(|_| ErrorData::internal_error("logging handler unavailable", None))?;
|
||||
drop(receiver);
|
||||
Ok(RequestContext::new(RequestId::Number(1), peer))
|
||||
}
|
||||
|
||||
pub(super) async fn set_level(
|
||||
state: &Arc<AppState>,
|
||||
session_id: &str,
|
||||
request: SetLevelRequestParams,
|
||||
) -> Result<(), ErrorData> {
|
||||
let handler = LoggingHandler {
|
||||
store: Arc::clone(&state.logging_levels),
|
||||
session_id: session_id.to_owned(),
|
||||
};
|
||||
let context = request_context().await?;
|
||||
invoke(&handler, request, context).await
|
||||
}
|
||||
|
||||
async fn invoke(
|
||||
handler: &impl ServerHandler,
|
||||
request: SetLevelRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
ServerHandler::set_level(handler, request, context).await
|
||||
}
|
||||
|
||||
pub(super) fn response(
|
||||
message: &serde_json::Value,
|
||||
mode: crate::transport::ResponseMode,
|
||||
revision: &str,
|
||||
result: Result<(), ErrorData>,
|
||||
) -> axum::response::Response {
|
||||
match result {
|
||||
Ok(()) => {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_consumed();
|
||||
crate::transport::transport_response(
|
||||
axum::http::StatusCode::OK,
|
||||
crate::jsonrpc::jsonrpc_result(
|
||||
crate::jsonrpc::request_id(message),
|
||||
serde_json::json!({}),
|
||||
),
|
||||
mode,
|
||||
None,
|
||||
Some(revision),
|
||||
)
|
||||
}
|
||||
Err(error) => {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_logging_handler_consumed();
|
||||
super::dispatch::sdk_error_response(message, mode, revision, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_logging_handler_tests.rs"]
|
||||
mod tests;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Request-owned outbound SDK peer for progress notifications.
|
||||
use std::{
|
||||
io,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use futures_util::{sink, stream};
|
||||
use rmcp::{
|
||||
RoleServer, ServerHandler,
|
||||
model::{
|
||||
ClientJsonRpcMessage, ProgressNotificationParam, ServerJsonRpcMessage, ServerNotification,
|
||||
},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rmcp_progress_peer_controls.rs"]
|
||||
pub(crate) mod controls;
|
||||
|
||||
const PROGRESS_TOKEN: &str = "progressToken";
|
||||
// The SDK traces outbound params; client tokens must stay outside its pump.
|
||||
const SDK_PROGRESS_TOKEN: &str = "crank-internal-progress";
|
||||
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
|
||||
struct SinkState {
|
||||
sender: mpsc::Sender<Value>,
|
||||
#[cfg(test)]
|
||||
control: Option<controls::Controls>,
|
||||
}
|
||||
|
||||
pub(super) struct ProgressPeer {
|
||||
token: Value,
|
||||
receiver: mpsc::Receiver<Value>,
|
||||
shutdown: Option<oneshot::Sender<()>>,
|
||||
owner: Option<tokio::task::JoinHandle<()>>,
|
||||
peer: watch::Receiver<Option<rmcp::service::Peer<RoleServer>>>,
|
||||
#[cfg(test)]
|
||||
controls: Option<controls::Controls>,
|
||||
progress_sidecar: Arc<Mutex<Option<u64>>>,
|
||||
}
|
||||
|
||||
impl ProgressPeer {
|
||||
pub(super) fn start(token: Value) -> Self {
|
||||
#[cfg(test)]
|
||||
let controls = controls::Controls::current();
|
||||
let (sender, receiver) = mpsc::channel(1);
|
||||
let owner_sender = sender.clone();
|
||||
let (shutdown, shutdown_rx) = oneshot::channel();
|
||||
let (peer_tx, peer) = watch::channel(None);
|
||||
let progress_sidecar = Arc::new(Mutex::new(None::<u64>));
|
||||
let sink_sidecar = progress_sidecar.clone();
|
||||
let raw_token = token.clone();
|
||||
let output = sink::unfold(
|
||||
SinkState {
|
||||
sender: sender.clone(),
|
||||
#[cfg(test)]
|
||||
control: controls.clone(),
|
||||
},
|
||||
move |state, message| {
|
||||
let progress_sidecar = sink_sidecar.clone();
|
||||
let raw_token = raw_token.clone();
|
||||
async move {
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &state.control {
|
||||
control.entered();
|
||||
if control.should_fail_send() {
|
||||
return Err(io::Error::other("controlled progress send failure"));
|
||||
}
|
||||
}
|
||||
let ServerJsonRpcMessage::Notification(notification) = &message else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unexpected SDK progress output",
|
||||
));
|
||||
};
|
||||
let ServerNotification::ProgressNotification(_) = ¬ification.notification
|
||||
else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unexpected SDK progress notification",
|
||||
));
|
||||
};
|
||||
let mut actual = serde_json::to_value(&message).map_err(io::Error::other)?;
|
||||
if actual["params"][PROGRESS_TOKEN] != SDK_PROGRESS_TOKEN {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"unexpected SDK progress token",
|
||||
));
|
||||
}
|
||||
let progress = progress_sidecar
|
||||
.lock()
|
||||
.expect("progress sidecar lock")
|
||||
.take()
|
||||
.ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "missing progress sidecar")
|
||||
})?;
|
||||
actual["params"]["progress"] = Value::from(progress);
|
||||
actual["params"][PROGRESS_TOKEN] = raw_token;
|
||||
#[cfg(test)]
|
||||
if state
|
||||
.control
|
||||
.as_ref()
|
||||
.is_some_and(controls::Controls::should_mutate_message)
|
||||
{
|
||||
actual["params"]["message"] = Value::from("controlled output mutation");
|
||||
}
|
||||
state.sender.try_send(actual).map_err(|error| match error {
|
||||
mpsc::error::TrySendError::Full(_) => {
|
||||
io::Error::new(io::ErrorKind::WouldBlock, "progress output full")
|
||||
}
|
||||
mpsc::error::TrySendError::Closed(_) => {
|
||||
io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed")
|
||||
}
|
||||
})?;
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &state.control {
|
||||
control.queued();
|
||||
control.wait_gate().await;
|
||||
}
|
||||
Ok::<_, io::Error>(state)
|
||||
}
|
||||
},
|
||||
);
|
||||
#[cfg(test)]
|
||||
let owner_controls = controls.clone();
|
||||
let owner = tokio::spawn(async move {
|
||||
let running = rmcp::service::serve_directly(
|
||||
Bootstrap,
|
||||
(Box::pin(output), stream::pending::<ClientJsonRpcMessage>()),
|
||||
None,
|
||||
);
|
||||
let peer = running.peer().clone();
|
||||
let _ = peer_tx.send(Some(peer));
|
||||
let stop = running.cancellation_token();
|
||||
let pump = running.waiting();
|
||||
tokio::pin!(pump);
|
||||
let mut pump_done = false;
|
||||
tokio::select! {
|
||||
_ = owner_sender.closed() => {},
|
||||
_ = shutdown_rx => {},
|
||||
_ = &mut pump => { pump_done = true; },
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &owner_controls {
|
||||
control.release_sink();
|
||||
}
|
||||
stop.cancel();
|
||||
if !pump_done {
|
||||
let _ = pump.await;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(control) = owner_controls {
|
||||
control.completed();
|
||||
}
|
||||
});
|
||||
Self {
|
||||
token,
|
||||
receiver,
|
||||
shutdown: Some(shutdown),
|
||||
owner: Some(owner),
|
||||
peer,
|
||||
#[cfg(test)]
|
||||
controls,
|
||||
progress_sidecar,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn notify(
|
||||
&mut self,
|
||||
progress: u64,
|
||||
message: &'static str,
|
||||
) -> Result<Value, io::Error> {
|
||||
if !matches!(self.token, Value::String(_) | Value::Number(_)) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid progress token",
|
||||
));
|
||||
}
|
||||
let sdk_token = rmcp::model::ProgressToken(rmcp::model::NumberOrString::String(
|
||||
SDK_PROGRESS_TOKEN.into(),
|
||||
));
|
||||
let params =
|
||||
ProgressNotificationParam::new(sdk_token, progress as f64).with_message(message);
|
||||
*self.progress_sidecar.lock().expect("progress sidecar lock") = Some(progress);
|
||||
let mut peer = self.peer.clone();
|
||||
while peer.borrow().is_none() {
|
||||
peer.changed().await.map_err(io::Error::other)?;
|
||||
}
|
||||
let peer = peer.borrow().as_ref().expect("peer initialized").clone();
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &self.controls {
|
||||
control.sent();
|
||||
}
|
||||
let send = peer.notify_progress(params);
|
||||
tokio::pin!(send);
|
||||
let mut output = None;
|
||||
let send_result = loop {
|
||||
tokio::select! {
|
||||
result = &mut send => break result,
|
||||
received = self.receiver.recv(), if output.is_none() => {
|
||||
output = Some(received.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed"))?);
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &self.controls { control.received(); }
|
||||
}
|
||||
}
|
||||
};
|
||||
send_result.map_err(io::Error::other)?;
|
||||
let actual = match output {
|
||||
Some(output) => output,
|
||||
None => self.receiver.recv().await.ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed")
|
||||
})?,
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(control) = &self.controls {
|
||||
control.consumed();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_progress_notification_serialized();
|
||||
Ok(actual)
|
||||
}
|
||||
|
||||
pub(super) async fn finish(mut self) {
|
||||
self.close();
|
||||
if let Some(owner) = self.owner.take() {
|
||||
let _ = owner.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.receiver.close();
|
||||
if let Some(shutdown) = self.shutdown.take() {
|
||||
let _ = shutdown.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ProgressPeer {
|
||||
fn drop(&mut self) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_progress_peer_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Request-local test controls for the actual SDK progress peer.
|
||||
#![cfg(test)]
|
||||
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
tokio::task_local! {
|
||||
static CURRENT: Controls;
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Controls(Arc<State>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
actual_send: AtomicUsize,
|
||||
sink_entered: AtomicUsize,
|
||||
output_consumed: AtomicUsize,
|
||||
output_received: AtomicUsize,
|
||||
output_queued: AtomicUsize,
|
||||
owner_completed: AtomicUsize,
|
||||
fail_send: AtomicBool,
|
||||
mutate_message: AtomicBool,
|
||||
gate: std::sync::OnceLock<Arc<Semaphore>>,
|
||||
}
|
||||
|
||||
impl Controls {
|
||||
/// Installs controls only for this request future; `ProgressPeer::start` captures them.
|
||||
pub(crate) async fn scope<F: std::future::Future>(controls: Controls, future: F) -> F::Output {
|
||||
CURRENT.scope(controls, future).await
|
||||
}
|
||||
|
||||
pub(crate) fn actual_send(&self) -> usize {
|
||||
self.0.actual_send.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn sink_entered(&self) -> usize {
|
||||
self.0.sink_entered.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn output_consumed(&self) -> usize {
|
||||
self.0.output_consumed.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn output_queued(&self) -> usize {
|
||||
self.0.output_queued.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn output_received(&self) -> usize {
|
||||
self.0.output_received.load(Ordering::SeqCst)
|
||||
}
|
||||
pub(crate) fn owner_completed(&self) -> usize {
|
||||
self.0.owner_completed.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_send(&self) {
|
||||
self.0.fail_send.store(true, Ordering::SeqCst);
|
||||
}
|
||||
pub(crate) fn mutate_output_message(&self) {
|
||||
self.0.mutate_message.store(true, Ordering::SeqCst);
|
||||
}
|
||||
pub(crate) fn hold_sink(&self) {
|
||||
let _ = self.gate();
|
||||
}
|
||||
pub(crate) fn release_sink(&self) {
|
||||
self.gate().close();
|
||||
}
|
||||
|
||||
pub(super) fn current() -> Option<Self> {
|
||||
CURRENT.try_with(Clone::clone).ok()
|
||||
}
|
||||
pub(super) fn sent(&self) {
|
||||
self.0.actual_send.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn entered(&self) {
|
||||
self.0.sink_entered.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn consumed(&self) {
|
||||
self.0.output_consumed.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn queued(&self) {
|
||||
self.0.output_queued.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn received(&self) {
|
||||
self.0.output_received.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn completed(&self) {
|
||||
self.0.owner_completed.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
pub(super) fn should_fail_send(&self) -> bool {
|
||||
self.0.fail_send.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
pub(super) fn should_mutate_message(&self) -> bool {
|
||||
self.0.mutate_message.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
pub(super) async fn wait_gate(&self) {
|
||||
if let Some(gate) = self.0.gate.get() {
|
||||
let _ = gate.acquire().await;
|
||||
}
|
||||
}
|
||||
fn gate(&self) -> &Arc<Semaphore> {
|
||||
self.0.gate.get_or_init(|| Arc::new(Semaphore::new(0)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//! Request-stream ownership controls without an external service or a second domain task.
|
||||
use super::super::rmcp_progress_peer::{ProgressPeer, controls::Controls};
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
struct DomainLease(Arc<AtomicBool>);
|
||||
impl Drop for DomainLease {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_call(
|
||||
controls: &Controls,
|
||||
deadline: bool,
|
||||
) -> (
|
||||
CallStream,
|
||||
Arc<AtomicBool>,
|
||||
Arc<InFlightCalls>,
|
||||
InFlightScope,
|
||||
) {
|
||||
controls.hold_sink();
|
||||
let dropped = Arc::new(AtomicBool::new(false));
|
||||
let lease = DomainLease(dropped.clone());
|
||||
let registry = Arc::new(InFlightCalls::new(1));
|
||||
let scope = InFlightScope {
|
||||
session_id: "owned".into(),
|
||||
owner: "key".into(),
|
||||
};
|
||||
let entry = registry.register(&scope, &serde_json::json!(1)).unwrap();
|
||||
let (lifecycle, events) = ToolCallLifecycle::new(Some(ProgressToken::Text("owned".into())));
|
||||
let domain = async move {
|
||||
let _lease = lease;
|
||||
lifecycle.advance(Phase::Resolved);
|
||||
if deadline {
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
let mut result = rmcp::model::CallToolResult::error(vec![]);
|
||||
result.structured_content =
|
||||
Some(serde_json::json!({"error":{"code":"upstream_timeout"}}));
|
||||
super::super::rmcp_tools_runtime::Outcome::Call(result)
|
||||
} else {
|
||||
std::future::pending().await
|
||||
}
|
||||
};
|
||||
let call = CallStream {
|
||||
call: Box::pin(domain),
|
||||
events: events.unwrap(),
|
||||
cancel: entry.cancel_signal(),
|
||||
peer: Some(ProgressPeer::start(serde_json::json!("owned"))),
|
||||
outcome: None,
|
||||
message: serde_json::json!({"jsonrpc":"2.0","id":1}),
|
||||
protocol_version: crate::jsonrpc::LEGACY_PROTOCOL_VERSION.into(),
|
||||
pending: VecDeque::new(),
|
||||
finished: false,
|
||||
logging: crate::protocol::carry_scope(),
|
||||
_in_flight: Some(entry),
|
||||
};
|
||||
(call, dropped, registry, scope)
|
||||
}
|
||||
|
||||
async fn joined(controls: &Controls) {
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
while controls.owner_completed() != 1 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("request owner must join SDK pump");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_unpolled_stream_drop_releases_owner_domain_and_registration() {
|
||||
let controls = Controls::default();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||
drop(call);
|
||||
joined(&controls).await;
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert_eq!(controls.actual_send(), 0);
|
||||
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_pending_send_cancel_stops_domain_and_joins_pump() {
|
||||
let controls = Controls::default();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||
let next = next_event(call);
|
||||
tokio::pin!(next);
|
||||
tokio::select! {
|
||||
_ = &mut next => panic!("held send cannot produce a frame"),
|
||||
_ = async { while controls.sink_entered() == 0 { tokio::task::yield_now().await; } } => {}
|
||||
}
|
||||
assert!(registry.cancel(&scope, &serde_json::json!(1)));
|
||||
assert!(tokio::time::timeout(Duration::from_secs(2), &mut next).await.unwrap().is_none());
|
||||
joined(&controls).await;
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert_eq!(controls.output_consumed(), 0);
|
||||
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||
}).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_pending_send_body_drop_stops_domain_and_joins_pump() {
|
||||
let controls = Controls::default();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||
let mut next = Box::pin(next_event(call));
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
tokio::select! {
|
||||
_ = &mut next => panic!("held send cannot produce a frame"),
|
||||
_ = async { while controls.sink_entered() == 0 { tokio::task::yield_now().await; } } => {}
|
||||
}
|
||||
}).await.unwrap();
|
||||
drop(next);
|
||||
joined(&controls).await;
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
assert_eq!(controls.output_consumed(), 0);
|
||||
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||
}).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_failure_after_first_frame_preserves_terminal_without_fallback() {
|
||||
let controls = Controls::default();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let (call, _, _, _) = stream_call(&controls, false);
|
||||
controls.release_sink();
|
||||
let (_, mut call) = next_event(call).await.expect("first actual SDK progress");
|
||||
assert_eq!(controls.output_consumed(), 1);
|
||||
controls.fail_next_send();
|
||||
let (sender, events) = mpsc::channel(PROGRESS_CAPACITY);
|
||||
sender
|
||||
.try_send(ProgressEvent {
|
||||
progress: 2,
|
||||
message: "execution_dispatched",
|
||||
})
|
||||
.unwrap();
|
||||
call.events = events;
|
||||
call.call = Box::pin(async {
|
||||
super::super::rmcp_tools_runtime::Outcome::Call(rmcp::model::CallToolResult::success(
|
||||
vec![],
|
||||
))
|
||||
});
|
||||
let (_, call) = next_event(call)
|
||||
.await
|
||||
.expect("original terminal after send error");
|
||||
assert!(
|
||||
call.finished,
|
||||
"no fallback progress in place of failed SDK send"
|
||||
);
|
||||
assert!(call.peer.is_none());
|
||||
assert_eq!(controls.actual_send(), 2);
|
||||
assert_eq!(controls.output_consumed(), 1);
|
||||
assert_eq!(controls.owner_completed(), 1);
|
||||
assert!(next_event(call).await.is_none(), "terminal stays last");
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_pending_send_keeps_original_domain_deadline() {
|
||||
let controls = Controls::default();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let (call, dropped, registry, scope) = stream_call(&controls, true);
|
||||
let (_, call) = tokio::time::timeout(Duration::from_secs(2), next_event(call))
|
||||
.await
|
||||
.expect("domain deadline must not wait for held send")
|
||||
.unwrap();
|
||||
assert!(call.finished);
|
||||
assert!(call.peer.is_none());
|
||||
assert_eq!(controls.sink_entered(), 1);
|
||||
assert_eq!(controls.output_consumed(), 0);
|
||||
joined(&controls).await;
|
||||
assert!(dropped.load(Ordering::SeqCst));
|
||||
drop(call);
|
||||
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Request-owned SDK subscription execution; the existing SSE receiver owns cancellation.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use futures_util::{sink, stream};
|
||||
use rmcp::{
|
||||
ErrorData, RoleServer, ServerHandler, Service,
|
||||
model::*,
|
||||
service::{RequestContext, SubscriptionContext},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::protocol::signals::{self, CatalogFingerprint, ReadError, Reader, Watch};
|
||||
|
||||
type PreparedWatch = (Watch, Reader, Result<CatalogFingerprint, ReadError>);
|
||||
|
||||
struct Listener {
|
||||
capabilities: ServerCapabilities,
|
||||
watch: Mutex<Option<PreparedWatch>>,
|
||||
}
|
||||
|
||||
impl ServerHandler for Listener {
|
||||
fn supported_protocol_versions(&self) -> std::borrow::Cow<'static, [ProtocolVersion]> {
|
||||
std::borrow::Cow::Owned(
|
||||
crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS
|
||||
.iter()
|
||||
.map(|revision| {
|
||||
serde_json::from_value(Value::String((*revision).to_owned()))
|
||||
.expect("registered revisions match SDK versions")
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
let mut info = ServerConfig::default();
|
||||
info.capabilities = self.capabilities.clone();
|
||||
info
|
||||
}
|
||||
|
||||
fn accepted_subscription_filter(&self, _: &SubscriptionFilter) -> Option<SubscriptionFilter> {
|
||||
Some(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"toolsListChanged": true, "resourcesListChanged": true, "promptsListChanged": true
|
||||
}))
|
||||
.expect("closed subscription candidate matches SDK"),
|
||||
)
|
||||
}
|
||||
|
||||
async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_subscription_listen_entered();
|
||||
let (mut watch, read, baseline) = self
|
||||
.watch
|
||||
.lock()
|
||||
.expect("request-local watch lock")
|
||||
.take()
|
||||
.ok_or_else(unavailable)?;
|
||||
let accepted = context.accepted();
|
||||
watch.signals = signals::Signals {
|
||||
tools: accepted.tools_list_changed == Some(true),
|
||||
resources: accepted.resources_list_changed == Some(true),
|
||||
prompts: accepted.prompts_list_changed == Some(true),
|
||||
};
|
||||
let result = signals::run_delivery(
|
||||
watch,
|
||||
signals::Delivery::Subscription(context.sink().clone()),
|
||||
read,
|
||||
baseline,
|
||||
)
|
||||
.await;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_subscription_handler_completed();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn project_meta(message: &Value) -> RequestMetaObject {
|
||||
use crate::jsonrpc::{
|
||||
META_CLIENT_CAPABILITIES_KEY, META_CLIENT_INFO_KEY, META_PROTOCOL_VERSION_KEY,
|
||||
};
|
||||
let raw = &message["params"]["_meta"];
|
||||
// Subscription delivery uses no client features; do not revalidate ignored capability extensions.
|
||||
let mut meta = serde_json::json!({
|
||||
META_PROTOCOL_VERSION_KEY: raw[META_PROTOCOL_VERSION_KEY],
|
||||
META_CLIENT_CAPABILITIES_KEY: {},
|
||||
});
|
||||
if let Some(info) = raw.get(META_CLIENT_INFO_KEY) {
|
||||
meta[META_CLIENT_INFO_KEY] =
|
||||
serde_json::json!({"name": info["name"], "version": info["version"]});
|
||||
}
|
||||
serde_json::from_value(meta).expect("admitted identity projection matches SDK metadata")
|
||||
}
|
||||
|
||||
fn unavailable() -> ErrorData {
|
||||
ErrorData::internal_error("subscription handler unavailable", None)
|
||||
}
|
||||
|
||||
pub(super) async fn start(
|
||||
state: Arc<super::AppState>,
|
||||
workspace_slug: String,
|
||||
agent_slug: String,
|
||||
original_id: Value,
|
||||
requested: SubscriptionFilter,
|
||||
meta: RequestMetaObject,
|
||||
) -> Result<(String, mpsc::Receiver<String>), ErrorData> {
|
||||
let watch = Watch {
|
||||
workspace_slug,
|
||||
agent_slug,
|
||||
signals: signals::Signals::ALL,
|
||||
wire: signals::Wire::Legacy,
|
||||
legacy_stream: None,
|
||||
deadline: None,
|
||||
};
|
||||
let mut read = signals::reader(state, &watch);
|
||||
// Keep the single baseline across ACK setup, including Retry/Gone semantics.
|
||||
let baseline = read().await;
|
||||
let capabilities = serde_json::from_value(crate::protocol::advertised_server_capabilities(
|
||||
crate::jsonrpc::MODERN_PROTOCOL_VERSION,
|
||||
))
|
||||
.expect("registered capabilities match SDK shapes");
|
||||
start_with(
|
||||
Listener {
|
||||
capabilities,
|
||||
watch: Mutex::new(Some((watch, read, baseline))),
|
||||
},
|
||||
requested,
|
||||
meta,
|
||||
original_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn start_with(
|
||||
handler: impl ServerHandler,
|
||||
requested: SubscriptionFilter,
|
||||
meta: RequestMetaObject,
|
||||
original_id: Value,
|
||||
) -> Result<(String, mpsc::Receiver<String>), ErrorData> {
|
||||
let (sender, mut receiver) = mpsc::channel(signals::SIGNAL_QUEUE_CAPACITY);
|
||||
let owner = own(handler, requested, meta, original_id, sender);
|
||||
#[cfg(test)]
|
||||
let observer = super::dispatch_observer::installed_observer();
|
||||
#[cfg(test)]
|
||||
let owner = async move {
|
||||
match observer {
|
||||
Some(observer) => super::dispatch_observer::observe(observer, owner).await,
|
||||
None => owner.await,
|
||||
}
|
||||
};
|
||||
let mut task = tokio::spawn(owner);
|
||||
// Dropping this future also drops receiver: the owner closes and joins the SDK pump.
|
||||
tokio::select! {
|
||||
biased;
|
||||
frame = receiver.recv() => match frame {
|
||||
Some(ack) => Ok((ack, receiver)),
|
||||
None => { task.await.map_err(|_| unavailable())??; Err(unavailable()) }
|
||||
},
|
||||
result = &mut task => {
|
||||
result.map_err(|_| unavailable())??;
|
||||
receiver.try_recv().map(|ack| (ack, receiver)).map_err(|_| unavailable())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_subscription_handler_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
async fn own(
|
||||
handler: impl ServerHandler,
|
||||
requested: SubscriptionFilter,
|
||||
meta: RequestMetaObject,
|
||||
original_id: Value,
|
||||
sender: mpsc::Sender<String>,
|
||||
) -> Result<(), ErrorData> {
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
let output_sender = sender.clone();
|
||||
#[cfg(test)]
|
||||
let observer = super::dispatch_observer::installed_observer();
|
||||
let output = sink::unfold(output_sender, move |sender, message| {
|
||||
let id = original_id.clone();
|
||||
#[cfg(test)]
|
||||
let observer = observer.clone();
|
||||
async move {
|
||||
let send = async { super::rmcp_subscriptions_output::send(&sender, &id, message) };
|
||||
#[cfg(test)]
|
||||
let send = async {
|
||||
match observer {
|
||||
Some(observer) => super::dispatch_observer::observe(observer, send).await,
|
||||
None => send.await,
|
||||
}
|
||||
};
|
||||
send.await?;
|
||||
Ok::<_, std::io::Error>(sender)
|
||||
}
|
||||
});
|
||||
let running = rmcp::service::serve_directly(
|
||||
Bootstrap,
|
||||
(Box::pin(output), stream::pending::<ClientJsonRpcMessage>()),
|
||||
None,
|
||||
);
|
||||
let mut context =
|
||||
RequestContext::<RoleServer>::new(RequestId::Number(1), running.peer().clone());
|
||||
context.meta = meta;
|
||||
let ct = context.ct.clone();
|
||||
let stop = running.cancellation_token();
|
||||
let pump = running.waiting();
|
||||
tokio::pin!(pump);
|
||||
let mut pump_done = false;
|
||||
let result = {
|
||||
let request = ClientRequest::SubscriptionsListenRequest(SubscriptionsListenRequest::new(
|
||||
SubscriptionsListenRequestParams::new(requested),
|
||||
));
|
||||
let operation = Service::handle_request(&handler, request, context);
|
||||
tokio::pin!(operation);
|
||||
tokio::select! {
|
||||
result = &mut operation => {
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_subscription_handler_consumed();
|
||||
match result {
|
||||
Ok(ServerResult::SubscriptionsListenResult(_)) => Ok(()),
|
||||
Ok(_) => Err(unavailable()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
},
|
||||
_ = sender.closed() => Ok(()),
|
||||
_ = &mut pump => { pump_done = true; Err(unavailable()) },
|
||||
}
|
||||
};
|
||||
ct.cancel();
|
||||
stop.cancel();
|
||||
if !pump_done {
|
||||
pump.await.map_err(|_| unavailable())?;
|
||||
}
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_subscription_owner_completed();
|
||||
if result.is_err() {
|
||||
tracing::warn!(name: "mcp.subscription.ended", "subscription handler ended with an error");
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
use std::io;
|
||||
|
||||
use rmcp::model::{ServerJsonRpcMessage, ServerNotification};
|
||||
use serde_json::Value;
|
||||
|
||||
const SUBSCRIPTION_ID: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
const ACK: &str = "notifications/subscriptions/acknowledged";
|
||||
const RESOURCES: &str = "notifications/resources/list_changed";
|
||||
const PROMPTS: &str = "notifications/prompts/list_changed";
|
||||
const TOOLS: &str = "notifications/tools/list_changed";
|
||||
|
||||
pub(super) fn send(
|
||||
sender: &tokio::sync::mpsc::Sender<String>,
|
||||
original_id: &Value,
|
||||
message: ServerJsonRpcMessage,
|
||||
) -> Result<(), io::Error> {
|
||||
let ServerJsonRpcMessage::Notification(notification) = message else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"subscription output accepts notifications only",
|
||||
));
|
||||
};
|
||||
|
||||
let (method, is_ack) = match ¬ification.notification {
|
||||
ServerNotification::SubscriptionsAcknowledgedNotification(_) => (ACK, true),
|
||||
ServerNotification::ResourceListChangedNotification(_) => (RESOURCES, false),
|
||||
ServerNotification::PromptListChangedNotification(_) => (PROMPTS, false),
|
||||
ServerNotification::ToolListChangedNotification(_) => (TOOLS, false),
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"unsupported subscription notification",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut encoded = serde_json::to_value(ServerJsonRpcMessage::Notification(notification))
|
||||
.map_err(io::Error::other)?;
|
||||
if encoded["method"] != method {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"subscription notification method does not match its SDK variant",
|
||||
));
|
||||
}
|
||||
encoded["params"]["_meta"][SUBSCRIPTION_ID] = original_id.clone();
|
||||
let frame = serde_json::to_string(&encoded).map_err(io::Error::other)?;
|
||||
#[cfg(test)]
|
||||
if is_ack {
|
||||
crate::app::dispatch_observer::sdk_subscriptions_acknowledged_serialized();
|
||||
} else {
|
||||
crate::app::dispatch_observer::sdk_signal_notification_serialized();
|
||||
}
|
||||
|
||||
if is_ack {
|
||||
sender.try_send(frame).map_err(|error| match error {
|
||||
tokio::sync::mpsc::error::TrySendError::Full(_) => {
|
||||
io::Error::new(io::ErrorKind::WouldBlock, "subscription ACK queue is full")
|
||||
}
|
||||
tokio::sync::mpsc::error::TrySendError::Closed(_) => {
|
||||
io::Error::new(io::ErrorKind::BrokenPipe, "subscription output is closed")
|
||||
}
|
||||
})?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match sender.try_send(frame) {
|
||||
Ok(()) | Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => Ok(()),
|
||||
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"subscription output is closed",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sdk_controls {
|
||||
use super::*;
|
||||
use futures_util::{sink, stream};
|
||||
use rmcp::{
|
||||
ErrorData, RoleServer, ServerHandler, Service,
|
||||
model::{ClientJsonRpcMessage, RequestId, RequestMetaObject, SubscriptionFilter},
|
||||
service::{RequestContext, SubscriptionContext},
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
struct Bootstrap;
|
||||
impl ServerHandler for Bootstrap {}
|
||||
|
||||
struct Listener {
|
||||
entered: Arc<AtomicUsize>,
|
||||
count: usize,
|
||||
fail: bool,
|
||||
}
|
||||
impl ServerHandler for Listener {
|
||||
fn get_info(&self) -> rmcp::model::ServerConfig {
|
||||
let mut info = rmcp::model::ServerConfig::default();
|
||||
info.capabilities =
|
||||
serde_json::from_value(json!({"tools":{"listChanged":true}})).unwrap();
|
||||
info
|
||||
}
|
||||
fn accepted_subscription_filter(
|
||||
&self,
|
||||
_: &SubscriptionFilter,
|
||||
) -> Option<SubscriptionFilter> {
|
||||
Some(
|
||||
serde_json::from_value(json!({"toolsListChanged":true,"promptsListChanged":true}))
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
|
||||
self.entered.fetch_add(1, Ordering::SeqCst);
|
||||
assert_eq!(
|
||||
serde_json::to_value(context.accepted()).unwrap(),
|
||||
json!({"toolsListChanged":true})
|
||||
);
|
||||
assert!(context.sink().notify_prompt_list_changed().await.is_err());
|
||||
if self.fail {
|
||||
return Err(ErrorData::internal_error("listener rejected", None));
|
||||
}
|
||||
for _ in 0..self.count {
|
||||
context.sink().notify_tool_list_changed().await.unwrap();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn exercise(original_id: Value, count: usize, fail: bool, closed: bool) {
|
||||
let (sender, mut receiver) = mpsc::channel(4);
|
||||
let entered = Arc::new(AtomicUsize::new(0));
|
||||
let handler = Listener {
|
||||
entered: entered.clone(),
|
||||
count,
|
||||
fail,
|
||||
};
|
||||
let output_id = original_id.clone();
|
||||
let output = sink::unfold(sender, move |sender, message| {
|
||||
let id = output_id.clone();
|
||||
async move {
|
||||
send(&sender, &id, message)?;
|
||||
Ok::<_, io::Error>(sender)
|
||||
}
|
||||
});
|
||||
let mut running = rmcp::service::serve_directly(
|
||||
Bootstrap,
|
||||
(Box::pin(output), stream::pending::<ClientJsonRpcMessage>()),
|
||||
None,
|
||||
);
|
||||
let mut context =
|
||||
RequestContext::<RoleServer>::new(RequestId::Number(1), running.peer().clone());
|
||||
context.meta = RequestMetaObject::with_client_context(
|
||||
rmcp::model::ProtocolVersion::V_2026_07_28,
|
||||
rmcp::model::Implementation::new("output-test", "1"),
|
||||
rmcp::model::ClientCapabilities::default(),
|
||||
);
|
||||
let request = serde_json::from_value(json!({"method":"subscriptions/listen", "params":{"notifications":{"toolsListChanged":true,"promptsListChanged":true,"resourcesListChanged":true,"resourceSubscriptions":["crank://excluded"]}}})).unwrap();
|
||||
|
||||
if closed {
|
||||
drop(receiver);
|
||||
let result = Service::handle_request(&handler, request, context).await;
|
||||
assert!(result.is_err());
|
||||
assert_eq!(
|
||||
entered.load(Ordering::SeqCst),
|
||||
0,
|
||||
"ACK send failure must prevent listen"
|
||||
);
|
||||
} else {
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(3),
|
||||
Service::handle_request(&handler, request, context),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(entered.load(Ordering::SeqCst), 1);
|
||||
let mut frames = Vec::new();
|
||||
while let Ok(frame) = receiver.try_recv() {
|
||||
frames.push(serde_json::from_str::<Value>(&frame).unwrap());
|
||||
}
|
||||
assert_eq!(frames[0]["method"], ACK);
|
||||
assert_eq!(
|
||||
frames[0]["params"]["notifications"],
|
||||
json!({"toolsListChanged":true})
|
||||
);
|
||||
assert_eq!(frames[0]["params"]["_meta"][SUBSCRIPTION_ID], original_id);
|
||||
assert_eq!(
|
||||
frames[0]["params"]["_meta"][SUBSCRIPTION_ID].to_string(),
|
||||
original_id.to_string()
|
||||
);
|
||||
assert_eq!(frames.len(), (count + 1).min(4));
|
||||
for frame in &frames[1..] {
|
||||
assert_eq!(frame["method"], TOOLS);
|
||||
assert_eq!(
|
||||
frame["params"]["_meta"][SUBSCRIPTION_ID].to_string(),
|
||||
original_id.to_string()
|
||||
);
|
||||
}
|
||||
if fail {
|
||||
assert_eq!(result.unwrap_err().message, "listener rejected");
|
||||
} else {
|
||||
assert!(matches!(
|
||||
result.unwrap(),
|
||||
rmcp::model::ServerResult::SubscriptionsListenResult(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
let peer = running.peer().clone();
|
||||
running.close().await.unwrap();
|
||||
assert!(peer.is_transport_closed());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_sdk_ack_notifications_filters_ids_outcomes_and_bounded_delivery() {
|
||||
for encoded in ["18446744073709551615", "1.234567890123456789e+25"] {
|
||||
exercise(serde_json::from_str(encoded).unwrap(), 1, false, false).await;
|
||||
}
|
||||
exercise(json!("burst"), 10, false, false).await;
|
||||
exercise(json!("no-op"), 0, false, false).await;
|
||||
exercise(json!("error"), 0, true, false).await;
|
||||
exercise(json!("closed"), 1, false, true).await;
|
||||
}
|
||||
}
|
||||
@@ -196,8 +196,7 @@ impl ServerHandler for RmcpTools {
|
||||
event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => {
|
||||
if let Some(event) = event {
|
||||
if let Some(token) = &token {
|
||||
let params = serde_json::from_value(super::lifecycle::progress_frame(token, &event)["params"].clone()).map_err(|_| McpError::internal_error("invalid progress event", None))?;
|
||||
let _ = context.peer.notify_progress(params).await;
|
||||
let _ = context.peer.notify_progress(event.sdk_params(token)).await;
|
||||
}
|
||||
} else { events = None; }
|
||||
}
|
||||
|
||||
@@ -186,7 +186,8 @@ impl SetLevelCommand {
|
||||
}
|
||||
}
|
||||
|
||||
/// A neutral outcome of the shared `logging/setLevel` service.
|
||||
/// Compatibility outcome for the original protocol unit tests; runtime uses the SDK handler.
|
||||
#[cfg(test)]
|
||||
pub(crate) enum LoggingOutcome {
|
||||
/// The level of this client context was accepted.
|
||||
Applied(LogLevel),
|
||||
@@ -394,6 +395,7 @@ impl LogLevelStore {
|
||||
///
|
||||
/// The command has already been parsed from the wire form, so this function only validates and
|
||||
/// records; it never reads the registry, the catalog or any stored value.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn handle_logging_command(
|
||||
store: &LogLevelStore,
|
||||
session_id: &str,
|
||||
|
||||
@@ -33,7 +33,7 @@ mod prompts;
|
||||
mod registry;
|
||||
mod resources;
|
||||
mod response_sdk;
|
||||
mod signals;
|
||||
pub(crate) mod signals;
|
||||
|
||||
pub(crate) use dispatch_sdk::decode_dispatch_envelope;
|
||||
|
||||
@@ -48,9 +48,8 @@ pub(crate) use completion::{
|
||||
pub(crate) use lifecycle_sdk::{initialize_params, initialized_notification};
|
||||
pub(crate) use logging::{
|
||||
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
|
||||
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
|
||||
in_carried_scope, modern_request_level, note, scoped as logging_scope, set_active_level,
|
||||
set_sse_acceptable, take_notifications,
|
||||
LogLevel, LogLevelStore, SetLevelCommand, carry_scope, in_carried_scope, modern_request_level,
|
||||
note, scoped as logging_scope, set_active_level, set_sse_acceptable, take_notifications,
|
||||
};
|
||||
pub(crate) use prompts::{
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, handle_prompts_command,
|
||||
@@ -61,7 +60,7 @@ pub(crate) use resources::{
|
||||
};
|
||||
pub(crate) use signals::{
|
||||
FilterOutcome, INVALID_LISTEN_FILTER, ListenParams, Signals, StreamRegistry, Watch, Wire,
|
||||
acknowledged_frame, frames_stream, spawn as spawn_signal_watch, subscription_id,
|
||||
frames_stream, spawn as spawn_signal_watch, subscription_id,
|
||||
};
|
||||
|
||||
/// Resolved era of an incoming POST request.
|
||||
|
||||
@@ -176,12 +176,18 @@ impl<'de> Deserialize<'de> for ListenParams {
|
||||
/// The bounded input contract of a `subscriptions/listen` filter.
|
||||
pub(crate) enum FilterOutcome {
|
||||
/// The list-change subset this server honours for the stream.
|
||||
// Compatibility projection retained for the existing filter controls; SDK owns runtime acceptance.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
Accepted(Signals),
|
||||
/// One safe detail: no URI, name or value the client sent is echoed back.
|
||||
Invalid(&'static str),
|
||||
}
|
||||
|
||||
impl ListenFilter {
|
||||
pub(crate) fn into_sdk(self) -> SubscriptionFilter {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Validate the bounded inputs and keep only the honoured types.
|
||||
///
|
||||
/// `resourceSubscriptions` is not implemented in the current scope, which is what the
|
||||
@@ -269,6 +275,7 @@ pub(crate) enum Wire {
|
||||
/// `2025-11-25`: a bare server notification without parameters.
|
||||
Legacy,
|
||||
/// `2026-07-28`: every message carries the subscription id of its `subscriptions/listen` request.
|
||||
#[cfg(test)]
|
||||
Modern(Value),
|
||||
}
|
||||
|
||||
@@ -285,6 +292,7 @@ impl Wire {
|
||||
}
|
||||
let subscription_id = match self {
|
||||
Wire::Legacy => None,
|
||||
#[cfg(test)]
|
||||
Wire::Modern(subscription_id) => Some(subscription_id),
|
||||
};
|
||||
frames.push(sdk::signal_frame(method, subscription_id));
|
||||
@@ -294,6 +302,7 @@ impl Wire {
|
||||
}
|
||||
|
||||
/// The first modern frame: the accepted subset, before any list-change notification of the stream.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||
sdk::acknowledged_frame(subscription_id, accepted)
|
||||
}
|
||||
@@ -382,13 +391,17 @@ pub(crate) type Reader = Box<dyn FnMut() -> ReadFuture + Send>;
|
||||
///
|
||||
/// The first read is the baseline taken **before** the acknowledgment is written; it is never reset
|
||||
/// afterwards, so a publication between the baseline and the acknowledgment is still delivered.
|
||||
pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String> {
|
||||
pub(crate) fn reader(state: Arc<AppState>, watch: &Watch) -> Reader {
|
||||
let scope = (watch.workspace_slug.clone(), watch.agent_slug.clone());
|
||||
let reader: Reader = Box::new(move || {
|
||||
Box::new(move || {
|
||||
let state = Arc::clone(&state);
|
||||
let scope = scope.clone();
|
||||
Box::pin(async move { read(&state, &scope).await })
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String> {
|
||||
let reader = reader(state, &watch);
|
||||
let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||
#[cfg(not(test))]
|
||||
tokio::spawn(run(watch, sender, reader));
|
||||
@@ -408,10 +421,57 @@ pub(crate) fn spawn(state: Arc<AppState>, watch: Watch) -> mpsc::Receiver<String
|
||||
receiver
|
||||
}
|
||||
|
||||
pub(crate) enum Delivery {
|
||||
Frames(mpsc::Sender<String>),
|
||||
Subscription(rmcp::service::SubscriptionSink),
|
||||
}
|
||||
|
||||
impl Delivery {
|
||||
async fn send(&self, wire: &Wire, signals: Signals) -> Result<(), rmcp::ErrorData> {
|
||||
match self {
|
||||
Self::Frames(sender) => {
|
||||
for frame in wire.signal_frames(signals) {
|
||||
let _ = sender.try_send(frame);
|
||||
}
|
||||
}
|
||||
Self::Subscription(sink) => {
|
||||
if signals.resources {
|
||||
sink.notify_resource_list_changed()
|
||||
.await
|
||||
.map_err(send_error)?;
|
||||
}
|
||||
if signals.prompts {
|
||||
sink.notify_prompt_list_changed()
|
||||
.await
|
||||
.map_err(send_error)?;
|
||||
}
|
||||
if signals.tools {
|
||||
sink.notify_tool_list_changed().await.map_err(send_error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn send_error(_: rmcp::service::SubscriptionSendError) -> rmcp::ErrorData {
|
||||
rmcp::ErrorData::internal_error("subscription output unavailable", None)
|
||||
}
|
||||
|
||||
async fn run(watch: Watch, sender: mpsc::Sender<String>, mut read: Reader) {
|
||||
let mut baseline = match read().await {
|
||||
let initial = read().await;
|
||||
let _ = run_delivery(watch, Delivery::Frames(sender), read, initial).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn run_delivery(
|
||||
watch: Watch,
|
||||
delivery: Delivery,
|
||||
mut read: Reader,
|
||||
initial: Result<CatalogFingerprint, ReadError>,
|
||||
) -> Result<(), rmcp::ErrorData> {
|
||||
let mut baseline = match initial {
|
||||
Ok(fingerprint) => Some(fingerprint),
|
||||
Err(ReadError::Gone) => return,
|
||||
Err(ReadError::Gone) => return Ok(()),
|
||||
Err(ReadError::Retry) => {
|
||||
observe_failure();
|
||||
None
|
||||
@@ -419,36 +479,33 @@ async fn run(watch: Watch, sender: mpsc::Sender<String>, mut read: Reader) {
|
||||
};
|
||||
|
||||
loop {
|
||||
if !still_owned(&watch) || sender.is_closed() {
|
||||
return;
|
||||
if !still_owned(&watch)
|
||||
|| matches!(&delivery, Delivery::Frames(sender) if sender.is_closed())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if watch
|
||||
.deadline
|
||||
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
{
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
tokio::time::sleep(POLL_INTERVAL).await;
|
||||
if !still_owned(&watch) {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match read().await {
|
||||
Ok(fingerprint) => {
|
||||
if let Some(previous) = baseline.as_ref() {
|
||||
let changes = fingerprint.changes_since(previous).intersect(watch.signals);
|
||||
for frame in watch.wire.signal_frames(changes) {
|
||||
// A slow reader coalesces: the newest frame is dropped instead of blocking
|
||||
// the producer or growing a queue, and the client recovers through the
|
||||
// authoritative list methods.
|
||||
let _ = sender.try_send(frame);
|
||||
}
|
||||
delivery.send(&watch.wire, changes).await?;
|
||||
}
|
||||
baseline = Some(fingerprint);
|
||||
}
|
||||
// The Agent is no longer published: fail closed by ending the stream instead of serving a
|
||||
// catalog nobody may read any more.
|
||||
Err(ReadError::Gone) => return,
|
||||
Err(ReadError::Gone) => return Ok(()),
|
||||
// The committed catalog is untouched: the failure is observable and this tick is skipped.
|
||||
Err(_) => observe_failure(),
|
||||
}
|
||||
@@ -499,15 +556,39 @@ pub(crate) fn frames_stream<G: Send + 'static>(
|
||||
guard: G,
|
||||
) -> impl stream::Stream<Item = Result<Event, std::convert::Infallible>> {
|
||||
let pending: VecDeque<String> = first.into();
|
||||
#[cfg(test)]
|
||||
let observer = crate::app::dispatch_observer::installed_observer();
|
||||
stream::unfold(
|
||||
(pending, receiver, guard),
|
||||
|(mut pending, mut receiver, guard)| async move {
|
||||
loop {
|
||||
if let Some(frame) = pending.pop_front() {
|
||||
return Some((Ok(Event::default().data(frame)), (pending, receiver, guard)));
|
||||
move |(mut pending, mut receiver, guard)| {
|
||||
#[cfg(test)]
|
||||
let observer = observer.clone();
|
||||
async move {
|
||||
loop {
|
||||
if let Some(frame) = pending.pop_front() {
|
||||
#[cfg(test)]
|
||||
if let Ok(value) = serde_json::from_str::<Value>(&frame)
|
||||
&& value["params"]["_meta"].get(SUBSCRIPTION_ID_KEY).is_some()
|
||||
&& matches!(
|
||||
value["method"].as_str(),
|
||||
Some(
|
||||
RESOURCE_LIST_CHANGED | PROMPT_LIST_CHANGED | TOOL_LIST_CHANGED
|
||||
)
|
||||
)
|
||||
&& let Some(observer) = observer.as_ref()
|
||||
{
|
||||
crate::app::dispatch_observer::observe(Arc::clone(observer), async {
|
||||
crate::app::dispatch_observer::sdk_subscription_notification_consumed();
|
||||
}).await;
|
||||
}
|
||||
return Some((
|
||||
Ok(Event::default().data(frame)),
|
||||
(pending, receiver, guard),
|
||||
));
|
||||
}
|
||||
let frame = receiver.recv().await?;
|
||||
pending.push_back(frame);
|
||||
}
|
||||
let frame = receiver.recv().await?;
|
||||
pending.push_back(frame);
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -2,12 +2,18 @@
|
||||
|
||||
use rmcp::model::{
|
||||
JsonRpcNotification, JsonRpcVersion2_0, NotificationMetaObject, PromptListChangedNotification,
|
||||
ResourceListChangedNotification, SubscriptionFilter, SubscriptionsAcknowledgedNotification,
|
||||
SubscriptionsAcknowledgedNotificationParams, ToolListChangedNotification,
|
||||
ResourceListChangedNotification, ToolListChangedNotification,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use rmcp::model::{
|
||||
SubscriptionFilter, SubscriptionsAcknowledgedNotification,
|
||||
SubscriptionsAcknowledgedNotificationParams,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::{PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, Signals, TOOL_LIST_CHANGED};
|
||||
#[cfg(test)]
|
||||
use super::Signals;
|
||||
use super::{PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, TOOL_LIST_CHANGED};
|
||||
|
||||
fn subscription_meta(subscription_id: &Value) -> NotificationMetaObject {
|
||||
let mut meta = Map::new();
|
||||
@@ -60,6 +66,7 @@ pub(super) fn signal_frame(method: &str, subscription_id: Option<&Value>) -> Str
|
||||
frame
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String {
|
||||
let mut notifications = SubscriptionFilter::new();
|
||||
notifications.resources_list_changed = accepted.resources.then_some(true);
|
||||
|
||||
@@ -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,12 @@
|
||||
//! Handler-specific acceptance oracle, distinct from existing wire-level GREEN controls.
|
||||
use super::rmcp_logging_runtime_tests;
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_logging_http_completes_and_consumes_the_sdk_handler() {
|
||||
// Existing real build_app HTTP control proves the JSON/SSE contract independently.
|
||||
assert_eq!(
|
||||
rmcp_logging_runtime_tests::control("2025-11-25").await,
|
||||
[1, 1, 1, 1, 1],
|
||||
"legacy wire succeeded but the awaited SDK handler was not completed/consumed"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
#![allow(deprecated)]
|
||||
use super::*;
|
||||
use crate::protocol::SetLevelCommand;
|
||||
use serde_json::json;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn request(level: &str) -> SetLevelRequestParams {
|
||||
serde_json::from_value(json!({"level": level})).expect("valid SDK logging level")
|
||||
}
|
||||
fn handler(store: &Arc<protocol::LogLevelStore>) -> LoggingHandler {
|
||||
LoggingHandler {
|
||||
store: store.clone(),
|
||||
session_id: "current".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn typed_sdk_level_is_the_applied_level_and_execution_is_single() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
store.set("other", LogLevel::Debug);
|
||||
let counters = Arc::new(super::super::dispatch_observer::CounterSet::default());
|
||||
let events = super::super::dispatch_observer::observe(
|
||||
counters.clone(),
|
||||
protocol::logging_scope(async {
|
||||
// Mutate the typed value after validation: no raw command may override it later.
|
||||
let mut typed = SetLevelCommand {
|
||||
level: "critical".into(),
|
||||
}
|
||||
.validate()
|
||||
.unwrap();
|
||||
typed.level = LoggingLevel::Info;
|
||||
let result = invoke(&handler(&store), typed, request_context().await.unwrap()).await;
|
||||
assert!(result.is_ok());
|
||||
protocol::set_sse_acceptable();
|
||||
let events = protocol::take_notifications();
|
||||
let response = response(
|
||||
&json!({"id":91}),
|
||||
crate::transport::ResponseMode::Json,
|
||||
crate::jsonrpc::LEGACY_PROTOCOL_VERSION,
|
||||
result,
|
||||
);
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(store.get("current"), Some(LogLevel::Info));
|
||||
assert_eq!(store.get("other"), Some(LogLevel::Debug));
|
||||
events
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(counters.sdk_logging_handler_completed(), 1);
|
||||
assert_eq!(counters.sdk_logging_handler_consumed(), 1);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert_eq!(
|
||||
events[0]["params"]["data"],
|
||||
json!({
|
||||
"event": protocol::EVENT_LEVEL_APPLIED, "outcome": "applied"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
struct Controlled {
|
||||
inner: LoggingHandler,
|
||||
entered: AtomicUsize,
|
||||
error: Option<ErrorData>,
|
||||
pending: bool,
|
||||
}
|
||||
impl ServerHandler for Controlled {
|
||||
async fn set_level(
|
||||
&self,
|
||||
request: SetLevelRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<(), ErrorData> {
|
||||
self.entered.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(error) = &self.error {
|
||||
return Err(error.clone());
|
||||
}
|
||||
if self.pending {
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
ServerHandler::set_level(&self.inner, request, context).await
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_trait_error_controls_the_http_response_without_store_effect() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
let error = ErrorData::invalid_params("controlled handler error", None);
|
||||
let controlled = Controlled {
|
||||
inner: handler(&store),
|
||||
entered: AtomicUsize::new(0),
|
||||
error: Some(error),
|
||||
pending: false,
|
||||
};
|
||||
for mode in [
|
||||
crate::transport::ResponseMode::Json,
|
||||
crate::transport::ResponseMode::Sse,
|
||||
] {
|
||||
let result = invoke(
|
||||
&controlled,
|
||||
request("notice"),
|
||||
request_context().await.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let reply = response(
|
||||
&json!({"id":"controlled"}),
|
||||
mode,
|
||||
crate::jsonrpc::LEGACY_PROTOCOL_VERSION,
|
||||
result,
|
||||
);
|
||||
assert_eq!(reply.status(), 200);
|
||||
let bytes = axum::body::to_bytes(reply.into_body(), 4096).await.unwrap();
|
||||
let raw = std::str::from_utf8(&bytes).unwrap();
|
||||
let raw = raw
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data:"))
|
||||
.unwrap_or(raw);
|
||||
let body: serde_json::Value = serde_json::from_str(raw).unwrap();
|
||||
assert_eq!(body["id"], "controlled");
|
||||
assert_eq!(body["error"]["code"], -32602);
|
||||
assert_eq!(body["error"]["message"], "controlled handler error");
|
||||
assert!(body.get("result").is_none());
|
||||
}
|
||||
assert_eq!(controlled.entered.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(store.get("current"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_pending_await_before_store_effect_does_not_detach_work() {
|
||||
let store = Arc::new(protocol::LogLevelStore::new());
|
||||
let controlled = Controlled {
|
||||
inner: handler(&store),
|
||||
entered: AtomicUsize::new(0),
|
||||
error: None,
|
||||
pending: true,
|
||||
};
|
||||
let context = request_context().await.unwrap();
|
||||
let mut future = Box::pin(invoke(&controlled, request("alert"), context));
|
||||
assert!(futures_util::poll!(future.as_mut()).is_pending());
|
||||
assert_eq!(controlled.entered.load(Ordering::SeqCst), 1);
|
||||
drop(future);
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(store.get("current"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_command_maps_to_safe_invalid_params_error_data() {
|
||||
let error = SetLevelCommand {
|
||||
level: "not-a-level".to_owned(),
|
||||
}
|
||||
.validate()
|
||||
.unwrap_err();
|
||||
assert_eq!(error, protocol::INVALID_LEVEL);
|
||||
let sdk_error = ErrorData::invalid_params(error, None);
|
||||
assert_eq!(sdk_error.code.0, -32602);
|
||||
assert_eq!(sdk_error.message, protocol::INVALID_LEVEL);
|
||||
}
|
||||
@@ -78,7 +78,7 @@ fn opted(level: Value) -> Value {
|
||||
meta[LEVEL] = level;
|
||||
json!({"_meta":meta})
|
||||
}
|
||||
async fn control(revision: &str) -> [usize; 3] {
|
||||
pub(super) async fn control(revision: &str) -> [usize; 5] {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
@@ -131,6 +131,11 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
assert_eq!(h.counters.sdk_logging_notification(), 0);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
handlers(&h.counters),
|
||||
[0, 0],
|
||||
"rejected input must not invoke the handler"
|
||||
);
|
||||
let before = counts(&h.counters);
|
||||
let (method, params, expected) = if revision == LEGACY_REVISION {
|
||||
(
|
||||
@@ -155,7 +160,7 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
assert_eq!(events, vec![expected]);
|
||||
assert!(raw.len() < 4096);
|
||||
let after = counts(&h.counters);
|
||||
let delta = std::array::from_fn(|i| after[i] - before[i]);
|
||||
let delta: [usize; 3] = std::array::from_fn(|i| after[i] - before[i]);
|
||||
// Legacy severity persists, modern opt-in does not leak into the next request.
|
||||
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
|
||||
assert!(body["result"]["tools"].is_array());
|
||||
@@ -169,6 +174,7 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
.await
|
||||
.unwrap();
|
||||
let before = counts(&h.counters);
|
||||
let before_handlers = handlers(&h.counters);
|
||||
let era = h.counters.snapshot();
|
||||
let response = h
|
||||
.post(
|
||||
@@ -186,13 +192,20 @@ async fn control(revision: &str) -> [usize; 3] {
|
||||
let raw = response.text().await.unwrap();
|
||||
assert!(!raw.contains("notifications/message"));
|
||||
assert_eq!(counts(&h.counters), before);
|
||||
assert_eq!(handlers(&h.counters), before_handlers);
|
||||
let after = h.counters.snapshot();
|
||||
assert_eq!(after.era_modern, era.era_modern);
|
||||
assert_eq!(after.era_legacy, era.era_legacy);
|
||||
eprintln!(
|
||||
"existing GREEN logging HTTP {revision}: safe SSE, result, opt-in/invalid/era/auth controls passed; SDK positive delta={delta:?}"
|
||||
);
|
||||
delta
|
||||
[
|
||||
delta[0],
|
||||
delta[1],
|
||||
delta[2],
|
||||
h.counters.sdk_logging_handler_completed(),
|
||||
h.counters.sdk_logging_handler_consumed(),
|
||||
]
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_wire_legacy() {
|
||||
@@ -206,7 +219,7 @@ async fn rmcp_logging_wire_modern() {
|
||||
async fn rmcp_logging_sdk_legacy() {
|
||||
assert_eq!(
|
||||
control(LEGACY_REVISION).await,
|
||||
[1, 1, 1],
|
||||
[1, 1, 1, 1, 1],
|
||||
"missing SDK legacy request/level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
@@ -214,7 +227,7 @@ async fn rmcp_logging_sdk_legacy() {
|
||||
async fn rmcp_logging_sdk_modern() {
|
||||
assert_eq!(
|
||||
control(MODERN_REVISION).await,
|
||||
[0, 1, 1],
|
||||
[0, 1, 1, 0, 0],
|
||||
"missing SDK modern level/notification after successful HTTP wire assertions"
|
||||
);
|
||||
}
|
||||
@@ -256,3 +269,140 @@ async fn rmcp_logging_observer_scope_control() {
|
||||
assert_eq!(counts(&a), [1, 1, 1]);
|
||||
assert_eq!(counts(&b), [0, 0, 1]);
|
||||
}
|
||||
|
||||
fn handlers(c: &CounterSet) -> [usize; 2] {
|
||||
[
|
||||
c.sdk_logging_handler_completed(),
|
||||
c.sdk_logging_handler_consumed(),
|
||||
]
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_all_levels_json_sse_and_ignored_extensions() {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(LEGACY_REVISION).await.unwrap();
|
||||
for accept in ["application/json", "text/event-stream, application/json"] {
|
||||
for level in [
|
||||
"debug",
|
||||
"info",
|
||||
"notice",
|
||||
"warning",
|
||||
"error",
|
||||
"critical",
|
||||
"alert",
|
||||
"emergency",
|
||||
] {
|
||||
let before = handlers(&h.counters);
|
||||
let response = h.post_with_accept(LEGACY_REVISION, Some(&session), "logging/setLevel",
|
||||
json!({"level":level,"extension":{"CANARY":"ignored"},"_meta":{"extension":true}}), accept).await;
|
||||
assert_eq!(response.headers()["MCP-Protocol-Version"], LEGACY_REVISION);
|
||||
assert_eq!(
|
||||
response.headers()["x-request-id"],
|
||||
"logging-handler-control"
|
||||
);
|
||||
let (body, events, raw) = reply(response).await;
|
||||
assert_eq!(body["result"], json!({}));
|
||||
assert!(!raw.contains("CANARY"));
|
||||
if accept == "application/json" || !["debug", "info", "notice"].contains(&level) {
|
||||
assert!(events.is_empty());
|
||||
} else {
|
||||
let mut expected = vec![notification(
|
||||
"notice",
|
||||
"mcp.logging.level_applied",
|
||||
"applied",
|
||||
)];
|
||||
if ["debug", "info"].contains(&level) {
|
||||
expected.push(notification("info", "mcp.request.served", "ok"));
|
||||
}
|
||||
assert_eq!(events, expected);
|
||||
}
|
||||
assert_eq!(handlers(&h.counters), before.map(|n| n + 1));
|
||||
}
|
||||
}
|
||||
let before = handlers(&h.counters);
|
||||
let response = h
|
||||
.post(
|
||||
LEGACY_REVISION,
|
||||
Some(&session),
|
||||
"logging/setLevel",
|
||||
json!({"level":"info","_meta":7}),
|
||||
)
|
||||
.await;
|
||||
assert!(response.status().is_client_error());
|
||||
assert!(!response.text().await.unwrap().contains("CANARY"));
|
||||
assert_eq!(handlers(&h.counters), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_logging_session_guards_do_not_enter_the_handler() {
|
||||
use crate::session::TransportSessionStore;
|
||||
let h = Endpoint::started().await;
|
||||
let uninitialized = h
|
||||
.sessions
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
AGENT_SLUG,
|
||||
false,
|
||||
time::OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign = h
|
||||
.sessions
|
||||
.create(
|
||||
LEGACY_REVISION,
|
||||
WORKSPACE_SLUG,
|
||||
"another-agent",
|
||||
false,
|
||||
time::OffsetDateTime::now_utc(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
h.sessions
|
||||
.mark_initialized(&foreign, time::OffsetDateTime::now_utc())
|
||||
.await
|
||||
.unwrap();
|
||||
for session in [
|
||||
None,
|
||||
Some("unknown"),
|
||||
Some(uninitialized.as_str()),
|
||||
Some(foreign.as_str()),
|
||||
] {
|
||||
let response = h
|
||||
.post(
|
||||
LEGACY_REVISION,
|
||||
session,
|
||||
"logging/setLevel",
|
||||
json!({"level":"debug"}),
|
||||
)
|
||||
.await;
|
||||
let status = response.status();
|
||||
let raw = response.text().await.unwrap();
|
||||
if session == Some(uninitialized.as_str()) {
|
||||
assert_eq!(status, 200);
|
||||
let body: Value = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(body["error"]["code"], -32002);
|
||||
} else {
|
||||
assert_eq!(status.as_u16(), if session.is_none() { 400 } else { 404 });
|
||||
}
|
||||
assert!(!raw.contains("mcp.logging.level_applied"));
|
||||
assert_eq!(handlers(&h.counters), [0, 0]);
|
||||
assert_eq!(h.counters.sdk_logging_dispatch(), 0);
|
||||
}
|
||||
let session = h.session(LEGACY_REVISION).await;
|
||||
let (body, _, _) = reply(
|
||||
h.post(
|
||||
LEGACY_REVISION,
|
||||
session.as_deref(),
|
||||
"logging/setLevel",
|
||||
json!({"level":"notice"}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["result"], json!({}));
|
||||
assert_eq!(handlers(&h.counters), [1, 1]);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crank_runtime::{
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub sessions: Arc<crate::session::InMemorySessionStore>,
|
||||
key: String,
|
||||
url: String,
|
||||
server: tokio::task::JoinHandle<()>,
|
||||
@@ -18,7 +19,7 @@ impl Drop for Endpoint {
|
||||
}
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
crank_test_support::postgres_schema_url_for_task("logging_owner", "t_c28c3800").await;
|
||||
crank_test_support::postgres_schema_url_for_task("logging_handler", "t_dbf2bdff").await;
|
||||
let registry = test_registry().await;
|
||||
let operation = test_operation("http://127.0.0.1:9");
|
||||
registry
|
||||
@@ -38,6 +39,7 @@ impl Endpoint {
|
||||
publish_agent(®istry, &operation).await;
|
||||
let key = create_api_key(®istry).await;
|
||||
let counters = Arc::new(CounterSet::default());
|
||||
let sessions = Arc::new(crate::session::InMemorySessionStore::default());
|
||||
let app = crate::build_app(
|
||||
registry.clone(),
|
||||
Duration::ZERO,
|
||||
@@ -49,7 +51,7 @@ impl Endpoint {
|
||||
.build(),
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
sessions.clone(),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
@@ -73,22 +75,41 @@ impl Endpoint {
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
sessions,
|
||||
key,
|
||||
url,
|
||||
server,
|
||||
}
|
||||
}
|
||||
pub async fn post(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> reqwest::Response {
|
||||
self.post_with_accept(
|
||||
revision,
|
||||
session,
|
||||
method,
|
||||
params,
|
||||
"text/event-stream, application/json",
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub async fn post_with_accept(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
method: &str,
|
||||
mut params: Value,
|
||||
accept: &str,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(&self.url)
|
||||
.bearer_auth(&self.key)
|
||||
.header("Accept", "text/event-stream, application/json")
|
||||
.header("Accept", accept)
|
||||
.header("x-request-id", "logging-handler-control")
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use tokio::sync::Semaphore;
|
||||
pub(in crate::app::dispatch_observer) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
pub counters: Arc<CounterSet>,
|
||||
pub peer_controls: crate::app::rmcp_progress_peer::controls::Controls,
|
||||
pub sessions: Arc<CountedSessionStore>,
|
||||
pub key: String,
|
||||
pub other_key: String,
|
||||
@@ -110,11 +111,18 @@ impl Endpoint {
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let scope = counters.clone();
|
||||
let peer_controls = crate::app::rmcp_progress_peer::controls::Controls::default();
|
||||
let peer_scope = peer_controls.clone();
|
||||
let app = app.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let c = scope.clone();
|
||||
let control = peer_scope.clone();
|
||||
async move {
|
||||
let response = observe(c.clone(), next.run(request)).await;
|
||||
let response = crate::app::rmcp_progress_peer::controls::Controls::scope(
|
||||
control,
|
||||
observe(c.clone(), next.run(request)),
|
||||
)
|
||||
.await;
|
||||
observe_body(response, c)
|
||||
}
|
||||
},
|
||||
@@ -130,6 +138,7 @@ impl Endpoint {
|
||||
Self {
|
||||
registry,
|
||||
counters,
|
||||
peer_controls,
|
||||
sessions,
|
||||
key,
|
||||
other_key,
|
||||
|
||||
@@ -8,6 +8,9 @@ use std::{sync::Arc, time::Duration};
|
||||
pub(super) mod fixtures;
|
||||
use fixtures::Endpoint;
|
||||
|
||||
#[path = "rmcp_progress_peer_runtime_tests.rs"]
|
||||
mod peer_runtime;
|
||||
|
||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||
let (parts, body) = response.into_parts();
|
||||
let body = stream::unfold(
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Actual SDK send/output controls through the ordinary HTTP/SSE consumer.
|
||||
use super::*;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
async fn peer_output_control(revision: &str) {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let controls = &h.peer_controls;
|
||||
controls.mutate_output_message();
|
||||
h.gate.add_permits(1);
|
||||
let reply = frames(
|
||||
h.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(61),
|
||||
Some(json!(1.0)),
|
||||
"text/event-stream",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(reply.len(), 4);
|
||||
assert_eq!(
|
||||
reply[0]["params"]["message"], "controlled output mutation",
|
||||
"SSE must consume actual SDK output, not a parallel handwritten frame"
|
||||
);
|
||||
assert_eq!(reply[0]["params"]["progressToken"].to_string(), "1.0");
|
||||
terminal(&reply, revision, json!(61));
|
||||
assert_eq!(controls.actual_send(), 3);
|
||||
assert_eq!(controls.sink_entered(), 3);
|
||||
assert_eq!(controls.output_consumed(), 3);
|
||||
assert_eq!(controls.owner_completed(), 1);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 1);
|
||||
|
||||
controls.fail_next_send();
|
||||
h.gate.add_permits(1);
|
||||
let reply = frames(
|
||||
h.call(
|
||||
revision,
|
||||
session.as_deref(),
|
||||
json!(62),
|
||||
Some(json!("failed-send")),
|
||||
"text/event-stream",
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
reply.len(),
|
||||
1,
|
||||
"failed SDK send disables progress without fallback"
|
||||
);
|
||||
terminal(&reply, revision, json!(62));
|
||||
assert_eq!(controls.actual_send(), 4, "no SDK retry/restart");
|
||||
assert_eq!(controls.sink_entered(), 4);
|
||||
assert_eq!(
|
||||
controls.output_consumed(),
|
||||
3,
|
||||
"failed output cannot count as delivered"
|
||||
);
|
||||
assert_eq!(controls.owner_completed(), 2);
|
||||
assert_eq!(h.started.load(Ordering::SeqCst), 2, "same Tool, no replay");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_runtime_legacy() {
|
||||
peer_output_control(LEGACY_REVISION).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_progress_peer_runtime_modern() {
|
||||
peer_output_control(MODERN_REVISION).await;
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
use super::ProgressPeer;
|
||||
use super::controls::Controls;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
io::Write,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct LogCapture(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl Write for LogCapture {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture {
|
||||
type Writer = Self;
|
||||
fn make_writer(&'a self) -> Self {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdk_trace_keeps_raw_string_and_numeric_tokens_private_without_disabling_logs() {
|
||||
let capture = LogCapture::default();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_max_level(tracing::Level::TRACE)
|
||||
.without_time()
|
||||
.with_ansi(false)
|
||||
.with_writer(capture.clone())
|
||||
.finish();
|
||||
let dispatch = tracing::Dispatch::new(subscriber);
|
||||
let _guard = tracing::dispatcher::set_default(&dispatch);
|
||||
// All spawned pump tasks run under this thread's TRACE capture, not just the caller.
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
for raw in [
|
||||
"\"private-progress-canary-716283941\"",
|
||||
"-716283941",
|
||||
"1.572839416",
|
||||
"1.0",
|
||||
"-0.0",
|
||||
"18446744073709551615",
|
||||
"7.182736451928374651e+27",
|
||||
] {
|
||||
let token: Value = serde_json::from_str(raw).unwrap();
|
||||
let mut peer = ProgressPeer::start(token.clone());
|
||||
let output = peer.notify(u64::MAX, "running").await.unwrap();
|
||||
assert_eq!(
|
||||
output["params"]["progressToken"].to_string(),
|
||||
token.to_string()
|
||||
);
|
||||
assert_eq!(output["params"]["progress"], json!(u64::MAX));
|
||||
peer.finish().await;
|
||||
}
|
||||
tracing::info!("application-log-still-enabled");
|
||||
});
|
||||
let logs = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(logs.contains("application-log-still-enabled"));
|
||||
let notifications: Vec<_> = logs
|
||||
.lines()
|
||||
.filter(|line| line.contains("ProxyMessage(Notification"))
|
||||
.collect();
|
||||
assert_eq!(notifications.len(), 7, "actual SDK TRACE must be captured");
|
||||
assert!(
|
||||
notifications
|
||||
.iter()
|
||||
.all(|line| line.contains("ProgressToken(String(\"crank-internal-progress\"))"))
|
||||
);
|
||||
for raw in [
|
||||
"private-progress-canary-716283941",
|
||||
"-716283941",
|
||||
"1.572839416",
|
||||
"18446744073709551615",
|
||||
"7.182736451928374651",
|
||||
] {
|
||||
assert!(!logs.contains(raw), "raw token leaked into SDK TRACE");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn emits_real_sdk_progress_notification_with_exact_raw_numbers() {
|
||||
let token: Value = serde_json::from_str("1.0").unwrap();
|
||||
let mut peer = ProgressPeer::start(token);
|
||||
let output = peer.notify(9_007_199_254_740_993, "running").await.unwrap();
|
||||
assert_eq!(output["method"], "notifications/progress");
|
||||
assert_eq!(output["params"]["progressToken"].to_string(), "1.0");
|
||||
assert_eq!(
|
||||
output["params"]["progress"],
|
||||
json!(9_007_199_254_740_993u64)
|
||||
);
|
||||
assert_eq!(output["params"]["message"], "running");
|
||||
peer.finish().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_output_send_failure_instead_of_claiming_delivery() {
|
||||
let mut peer = ProgressPeer::start(json!(4));
|
||||
peer.receiver.close();
|
||||
assert!(peer.notify(2, "running").await.is_err());
|
||||
peer.finish().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_controls_observe_mutated_actual_sdk_output_and_owner_shutdown() {
|
||||
let controls = Controls::default();
|
||||
controls.mutate_output_message();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let mut peer = ProgressPeer::start(json!(4));
|
||||
let output = peer.notify(2, "running").await.unwrap();
|
||||
assert_eq!(output["params"]["message"], "controlled output mutation");
|
||||
peer.finish().await;
|
||||
})
|
||||
.await;
|
||||
assert_eq!(controls.actual_send(), 1);
|
||||
assert_eq!(controls.sink_entered(), 1);
|
||||
assert_eq!(controls.output_consumed(), 1);
|
||||
assert_eq!(controls.owner_completed(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_sdk_send_does_not_claim_output() {
|
||||
let controls = Controls::default();
|
||||
controls.fail_next_send();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let mut peer = ProgressPeer::start(json!(4));
|
||||
assert!(peer.notify(2, "running").await.is_err());
|
||||
peer.finish().await;
|
||||
})
|
||||
.await;
|
||||
assert_eq!(controls.actual_send(), 1);
|
||||
assert_eq!(controls.sink_entered(), 1);
|
||||
assert_eq!(controls.output_consumed(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sink_gate_holds_responder_after_output_and_cleans_up_on_release() {
|
||||
let controls = Controls::default();
|
||||
controls.hold_sink();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let mut peer = ProgressPeer::start(json!(4));
|
||||
{
|
||||
let send = peer.notify(2, "running");
|
||||
tokio::pin!(send);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while controls.output_received() == 0 {
|
||||
tokio::select! {
|
||||
result = &mut send => panic!("send completed before gate release: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
}
|
||||
}).await.expect("SDK output received while responder is gated");
|
||||
assert_eq!(controls.output_consumed(), 0);
|
||||
controls.release_sink();
|
||||
assert!(send.await.is_ok());
|
||||
}
|
||||
peer.finish().await;
|
||||
})
|
||||
.await;
|
||||
assert_eq!(controls.owner_completed(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_pending_gated_send_releases_and_joins_owner() {
|
||||
let controls = Controls::default();
|
||||
controls.hold_sink();
|
||||
Controls::scope(controls.clone(), async {
|
||||
let mut peer = ProgressPeer::start(json!(4));
|
||||
{
|
||||
let send = peer.notify(2, "running");
|
||||
tokio::pin!(send);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||
while controls.output_queued() == 0 {
|
||||
tokio::select! {
|
||||
result = &mut send => panic!("send completed before drop: {result:?}"),
|
||||
_ = tokio::task::yield_now() => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("SDK output queued before pending send drop");
|
||||
}
|
||||
peer.finish().await;
|
||||
})
|
||||
.await;
|
||||
assert_eq!(controls.owner_completed(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_numeric_tokens_and_counts_survive_sdk_projection() {
|
||||
for token in ["-7", "1.5", "-0", "18446744073709551615"] {
|
||||
let token: Value = serde_json::from_str(token).unwrap();
|
||||
let mut peer = ProgressPeer::start(token.clone());
|
||||
let output = peer.notify(u64::MAX, "running").await.unwrap();
|
||||
assert_eq!(output["params"]["progressToken"], token);
|
||||
assert_eq!(output["params"]["progress"], json!(u64::MAX));
|
||||
peer.finish().await;
|
||||
}
|
||||
let token: Value = serde_json::from_str("1.0").unwrap();
|
||||
let mut peer = ProgressPeer::start(token.clone());
|
||||
let output = peer.notify(9_007_199_254_740_993, "running").await.unwrap();
|
||||
assert_eq!(output["params"]["progressToken"], token);
|
||||
assert_eq!(
|
||||
output["params"]["progress"],
|
||||
json!(9_007_199_254_740_993u64)
|
||||
);
|
||||
peer.finish().await;
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
//! #107: HTTP wire controls are independent of the SDK execution oracle.
|
||||
//! A real committed Tool removal exercises the watcher; existing mcp_signals::scenarios covers
|
||||
//! Resource/Prompt publications, isolation, coalescing, reconnect and authoritative recovery.
|
||||
use super::signals_test_support::{self as fixtures, Endpoint, terminal};
|
||||
use super::{CounterSet, support::*};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
#[path = "rmcp_signals_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, terminal};
|
||||
use std::time::Duration;
|
||||
|
||||
const SUB_ID: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
const ACK: &str = "notifications/subscriptions/acknowledged";
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Small real catalog fixture; broader Resource/Prompt mutations stay in mcp_signals::scenarios.
|
||||
use super::*;
|
||||
use super::{CounterSet, support::*};
|
||||
use crank_core::{AgentStatus, AgentVersion, ToolSelectionPolicy};
|
||||
use crank_registry::{CreateAgentDraftVersionRequest, PublishAgentRequest, PublishRequest};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
pub(super) struct Endpoint {
|
||||
pub registry: crank_registry::PostgresRegistry,
|
||||
@@ -21,7 +23,7 @@ impl Drop for Endpoint {
|
||||
impl Endpoint {
|
||||
pub async fn started() -> Self {
|
||||
// First caller labels the shared, exit-cleaned disposable PostgreSQL with this owner.
|
||||
crank_test_support::postgres_schema_url_for_task("signals_owner", "t_7d5f77a6").await;
|
||||
crank_test_support::postgres_schema_url_for_task("signals_owner", "t_35c2ce53").await;
|
||||
let registry = test_registry().await;
|
||||
// This fixture only lists/removes a Tool; no upstream execution is needed.
|
||||
let operation = test_operation("http://127.0.0.1:9");
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! #107 subscription handler acceptance: real HTTP wire first, then SDK runtime oracle.
|
||||
use super::CounterSet;
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::signals_test_support::Endpoint;
|
||||
|
||||
const SUB_ID: &str = "io.modelcontextprotocol/subscriptionId";
|
||||
const ACK: &str = "notifications/subscriptions/acknowledged";
|
||||
const TOOLS: &str = "notifications/tools/list_changed";
|
||||
|
||||
fn snapshot(c: &CounterSet) -> [usize; 5] {
|
||||
[
|
||||
c.sdk_subscription_listen_entered(),
|
||||
c.sdk_subscription_handler_completed(),
|
||||
c.sdk_subscription_handler_consumed(),
|
||||
c.sdk_subscription_notification_consumed(),
|
||||
c.sdk_subscription_owner_completed(),
|
||||
]
|
||||
}
|
||||
|
||||
async fn http_control(id: Value) -> ([usize; 5], [usize; 3]) {
|
||||
let h = Endpoint::started().await;
|
||||
let started = snapshot(&h.counters);
|
||||
let sdk_wire_before = [
|
||||
h.counters.sdk_subscriptions_listen(),
|
||||
h.counters.sdk_subscriptions_acknowledged(),
|
||||
h.counters.sdk_signal_notification(),
|
||||
];
|
||||
let mut stream = h.listen(id.clone(), json!({"toolsListChanged":true})).await;
|
||||
let first = stream.frame().await;
|
||||
assert_eq!(first["method"], ACK, "HTTP SSE ACK must be first");
|
||||
assert_eq!(first["params"]["_meta"][SUB_ID], id, "exact JSON ACK id");
|
||||
assert_eq!(first["params"]["_meta"][SUB_ID].to_string(), id.to_string());
|
||||
assert_eq!(
|
||||
first["params"]["notifications"],
|
||||
json!({"toolsListChanged":true})
|
||||
);
|
||||
stream.silent().await;
|
||||
|
||||
h.draft_without_tools().await;
|
||||
h.publish_without_tools().await;
|
||||
let notification = stream.frame().await;
|
||||
assert_eq!(notification["method"], TOOLS);
|
||||
assert_eq!(
|
||||
notification["params"]["_meta"][SUB_ID], id,
|
||||
"exact JSON notification id"
|
||||
);
|
||||
assert_eq!(
|
||||
notification["params"]["_meta"][SUB_ID].to_string(),
|
||||
id.to_string()
|
||||
);
|
||||
stream.silent().await;
|
||||
|
||||
let wire = [
|
||||
h.counters.sdk_subscriptions_listen() - sdk_wire_before[0],
|
||||
h.counters.sdk_subscriptions_acknowledged() - sdk_wire_before[1],
|
||||
h.counters.sdk_signal_notification() - sdk_wire_before[2],
|
||||
];
|
||||
drop(stream);
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
while h.counters.sdk_subscription_owner_completed() == started[4] {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("HTTP close must join SDK owner/pump");
|
||||
let runtime = std::array::from_fn(|i| snapshot(&h.counters)[i] - started[i]);
|
||||
(runtime, wire)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn modern_http_wire_control_and_sdk_handler_runtime() {
|
||||
for id in [
|
||||
json!(u64::MAX),
|
||||
serde_json::from_str("0.12345678901234567890123456789").unwrap(),
|
||||
] {
|
||||
let (runtime, wire) = http_control(id).await;
|
||||
assert_eq!(
|
||||
wire,
|
||||
[1, 1, 1],
|
||||
"SDK decode/ACK/notification consumed through HTTP"
|
||||
);
|
||||
assert_eq!(
|
||||
runtime,
|
||||
[1, 0, 0, 1, 1],
|
||||
"cancelled listen must not be reported as completed; owner/pump must finish"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
use super::*;
|
||||
use crate::app::dispatch_observer::{self as observer, CounterSet};
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
|
||||
fn meta() -> RequestMetaObject {
|
||||
project_meta(&json!({"params":{"_meta":{
|
||||
"io.modelcontextprotocol/protocolVersion":"2026-07-28",
|
||||
"io.modelcontextprotocol/clientCapabilities":{},
|
||||
}}}))
|
||||
}
|
||||
fn filter(value: Value) -> SubscriptionFilter {
|
||||
serde_json::from_value(value).unwrap()
|
||||
}
|
||||
async fn finished(c: &CounterSet) {
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
while c.sdk_subscription_owner_completed() != 1 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("owner must join SDK bridge");
|
||||
}
|
||||
|
||||
struct Controlled {
|
||||
fail: bool,
|
||||
tools: bool,
|
||||
calls: Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
impl ServerHandler for Controlled {
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
let mut info = ServerConfig::default();
|
||||
info.capabilities = serde_json::from_value(
|
||||
json!({"tools":{"listChanged":self.tools}, "resources":{"listChanged":true}}),
|
||||
)
|
||||
.unwrap();
|
||||
info
|
||||
}
|
||||
fn accepted_subscription_filter(&self, _: &SubscriptionFilter) -> Option<SubscriptionFilter> {
|
||||
Some(filter(
|
||||
json!({"toolsListChanged":true, "resourcesListChanged":true, "promptsListChanged":true}),
|
||||
))
|
||||
}
|
||||
async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
|
||||
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
assert!(context.sink().notify_prompt_list_changed().await.is_err());
|
||||
if self.fail {
|
||||
return Err(ErrorData::internal_error("controlled refusal", None));
|
||||
}
|
||||
if self.tools {
|
||||
context.sink().notify_tool_list_changed().await.unwrap();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn actual_owner_consumes_typed_success_error_and_capability_subset_without_final_wire() {
|
||||
for (fail, tools) in [(false, true), (false, false), (true, false)] {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observer::observe(c.clone(), async {
|
||||
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let handler = Controlled {
|
||||
fail,
|
||||
tools,
|
||||
calls: calls.clone(),
|
||||
};
|
||||
let (sender, mut receiver) = mpsc::channel(4);
|
||||
let operation = own(
|
||||
handler,
|
||||
filter(json!({"toolsListChanged":true,"promptsListChanged":true})),
|
||||
meta(),
|
||||
json!(1.25),
|
||||
sender,
|
||||
);
|
||||
let task = tokio::spawn(observer::observe(c.clone(), operation));
|
||||
let ack: Value = serde_json::from_str(&receiver.recv().await.unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
ack["params"]["notifications"],
|
||||
if tools {
|
||||
json!({"toolsListChanged":true})
|
||||
} else {
|
||||
json!({})
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
ack["params"]["_meta"][signals::SUBSCRIPTION_ID_KEY],
|
||||
json!(1.25)
|
||||
);
|
||||
let result = tokio::time::timeout(Duration::from_secs(2), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
assert_eq!(c.sdk_subscription_handler_consumed(), 1);
|
||||
assert_eq!(c.sdk_subscription_owner_completed(), 1);
|
||||
if fail {
|
||||
assert_eq!(result.unwrap_err().message, "controlled refusal");
|
||||
} else {
|
||||
result.unwrap();
|
||||
}
|
||||
if tools {
|
||||
let value: Value = serde_json::from_str(&receiver.recv().await.unwrap()).unwrap();
|
||||
assert_eq!(value["method"], "notifications/tools/list_changed");
|
||||
}
|
||||
assert!(
|
||||
receiver.recv().await.is_none(),
|
||||
"no result/error/second ACK on wire"
|
||||
);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unpolled_body_and_pre_ack_drop_join_owner_and_release_permit() {
|
||||
for before_ack in [true, false] {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observer::observe(c.clone(), async {
|
||||
struct Pending;
|
||||
impl ServerHandler for Pending {
|
||||
fn accepted_subscription_filter(
|
||||
&self,
|
||||
_: &SubscriptionFilter,
|
||||
) -> Option<SubscriptionFilter> {
|
||||
Some(SubscriptionFilter::new())
|
||||
}
|
||||
async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> {
|
||||
context.cancelled().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
if before_ack {
|
||||
{
|
||||
let future =
|
||||
start_with(Pending, SubscriptionFilter::new(), meta(), json!("cancel"));
|
||||
tokio::pin!(future);
|
||||
assert!(futures_util::poll!(&mut future).is_pending());
|
||||
}
|
||||
} else {
|
||||
let (ack, receiver) =
|
||||
start_with(Pending, SubscriptionFilter::new(), meta(), json!("body"))
|
||||
.await
|
||||
.unwrap();
|
||||
let semaphore = Arc::new(tokio::sync::Semaphore::new(1));
|
||||
let guard = semaphore.clone().try_acquire_owned().unwrap();
|
||||
let body = signals::frames_stream(vec![ack], receiver, guard);
|
||||
drop(body);
|
||||
assert_eq!(semaphore.available_permits(), 1);
|
||||
}
|
||||
finished(&c).await;
|
||||
assert_eq!(c.sdk_subscription_owner_completed(), 1);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gone_catalog_finishes_real_listener_and_pre_ack_rejection_is_not_success() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observer::observe(c.clone(), async {
|
||||
let read: Reader = Box::new(|| panic!("Gone baseline must never read again"));
|
||||
let handler = Listener {
|
||||
capabilities: ServerCapabilities::default(),
|
||||
watch: Mutex::new(Some((
|
||||
Watch {
|
||||
workspace_slug: "w".into(),
|
||||
agent_slug: "a".into(),
|
||||
signals: signals::Signals::ALL,
|
||||
wire: signals::Wire::Legacy,
|
||||
legacy_stream: None,
|
||||
deadline: None,
|
||||
},
|
||||
read,
|
||||
Err(ReadError::Gone),
|
||||
))),
|
||||
};
|
||||
let (_, mut receiver) =
|
||||
start_with(handler, SubscriptionFilter::new(), meta(), json!("gone"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(receiver.recv().await.is_none(), "no final frame");
|
||||
finished(&c).await;
|
||||
assert_eq!(c.sdk_subscription_handler_completed(), 1);
|
||||
assert_eq!(c.sdk_subscription_handler_consumed(), 1);
|
||||
})
|
||||
.await;
|
||||
struct Refused;
|
||||
impl ServerHandler for Refused {}
|
||||
let result = start_with(Refused, SubscriptionFilter::new(), meta(), json!("refused")).await;
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"SDK refusal before ACK must not create a successful stream"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_catalog_read_is_dropped_and_sdk_tasks_join_on_body_close() {
|
||||
let c = Arc::new(CounterSet::default());
|
||||
observer::observe(c.clone(), async {
|
||||
let entered = Arc::new(tokio::sync::Notify::new());
|
||||
let dropped = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
struct DropRead(Arc<std::sync::atomic::AtomicUsize>);
|
||||
impl Drop for DropRead {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
let e = entered.clone();
|
||||
let d = dropped.clone();
|
||||
let read: Reader = Box::new(move || {
|
||||
let e = e.clone();
|
||||
let d = d.clone();
|
||||
Box::pin(async move {
|
||||
let _guard = DropRead(d);
|
||||
e.notify_one();
|
||||
std::future::pending().await
|
||||
})
|
||||
});
|
||||
let handler = Listener {
|
||||
capabilities: ServerCapabilities::default(),
|
||||
watch: Mutex::new(Some((
|
||||
Watch {
|
||||
workspace_slug: "w".into(),
|
||||
agent_slug: "a".into(),
|
||||
signals: signals::Signals::ALL,
|
||||
wire: signals::Wire::Legacy,
|
||||
legacy_stream: None,
|
||||
deadline: None,
|
||||
},
|
||||
read,
|
||||
Ok(CatalogFingerprint::default()),
|
||||
))),
|
||||
};
|
||||
assert_eq!(
|
||||
ServerHandler::supported_protocol_versions(&handler)
|
||||
.iter()
|
||||
.map(|v| v.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
crate::jsonrpc::SUPPORTED_PROTOCOL_VERSIONS
|
||||
);
|
||||
let (_, receiver) = start_with(
|
||||
handler,
|
||||
SubscriptionFilter::new(),
|
||||
meta(),
|
||||
json!("pending-read"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(2), entered.notified())
|
||||
.await
|
||||
.unwrap();
|
||||
drop(receiver);
|
||||
finished(&c).await;
|
||||
assert_eq!(dropped.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
assert_eq!(c.sdk_subscription_handler_completed(), 0);
|
||||
assert_eq!(c.sdk_subscription_handler_consumed(), 0);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -41,10 +41,16 @@ Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `com
|
||||
|
||||
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
|
||||
|
||||
Logging-handler-срез #107 поверх rc.38/rmcp3.9.0 подключает legacy `LoggingSetLevel` в `app/legacy_dispatch.rs` к прямому request-owned await `ServerHandler::set_level` в `app/rmcp_logging.rs`. Override применяет именно typed level к прежнему session store, активирует request-local level и записывает safe event; actual Result/ErrorData определяет JSON/SSE ответ. Bounded command validation остаётся до инертного bootstrap, bootstrap закрыт до рабочего handler. DTO-only execution оставлен только для старых protocol unit tests. HTTP completion/consumption, восемь levels, ignored extensions/admission, session/revocation guards и modern rejection дополняются direct typed mutation/error/single-execution/pending-drop controls; logging matrix и streamed carried scope сохраняются. try_lock skip по-прежнему не подтверждается readback и не превращается в blocking write; drop до эффекта не обещает rollback выполненного store.set. SDK Peer callbacks/transport/SessionManager не подключены; #107 остаётся partial, full/load/external-client qualification и production не входят в срез.
|
||||
|
||||
Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает штатный SSE `lifecycle::progress_frame` обеих revisions к сериализации `ProgressNotificationParam`, а legacy `handle_cancelled_notification` — к декодированию `CancelledNotificationParam.request_id`. Локальная projection+restore сохраняет исходные JSON numbers токена/ID и целочисленный u64 progress, включая значения вне i64/exact-f64; message и omissions берутся из SDK. Decoder передаёт SDK только requestId, не валидируя reason/_meta/extensions. Session+credential ownership, bounded queues/slots, transport, auth и modern stream-close cancellation не меняются. Runtime ATDD подтверждает SDK seams отдельно от wire; unit regression проверяет точную числовую форму. Decoder ignore действует только после HTTP admission: `_meta:[]` сохраняет прежний HTTP400/-32020 до SDK decoder. Отдельная HTTP-регрессия проверяет отказ без отмены активного вызова, а допустимый `_meta:{}` с reason/extensions — успешную SDK-отмену. Это частичная миграция params, не завершение #107, feature qualification или production deployment.
|
||||
|
||||
Progress-Peer-срез #107 поверх rc.40/rmcp3.9.0 заменяет DTO-only `lifecycle::progress_frame`: действующий `build_app` SSE обеих revisions вызывает request-local `Peer::notify_progress`, потребляет actual SDK outbound notification и передаёт её прежнему SSE consumer. Один endpoint принадлежит body; single-flight send и output1 не расширяют producer queue8/drop-newest и cancellation table256. SDK получает только постоянный внутренний progress token, чтобы его TRACE не раскрывал клиентское значение; после проверки actual output token восстанавливаются исходный string/numeric token и точный u64 progress, а message/omissions остаются SDK output. Глобальные TRACE/application logs не отключаются. Domain Tool не выполняется второй раз: send failure отключает только progress, без retry/fallback. Pending send одновременно poll-ит прежний domain future и cancellation; исходный upstream timeout закрывает bridge без нового deadline budget. Drop body закрывает endpoint, managed owner отменяет и join-ит SDK pump. JSON/no-token/invalid-token/no-carrier не создают endpoint; carried logging и terminal projection остаются прежними. Это перенос outbound progress, не новый HTTP transport/session manager и не завершение #107; full/load/external-client qualification и production не входят в срез.
|
||||
|
||||
Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены.
|
||||
|
||||
Subscriptions-handler-срез #107 поверх rc.39/rmcp3.9.0 подключает modern `app/dispatch.rs::SubscriptionsListen` к единственному request-owned default `Service::handle_request` в `app/rmcp_subscriptions.rs`. Живой локальный SDK Peer обслуживает только outbound notifications: actual SDK ACK и последовательные `SubscriptionSink` list-change notifications поступают через `app/rmcp_subscriptions_output.rs` в прежнюю очередь4 и SSE consumer. Registry capabilities и SDK requested/candidate/advertised intersection определяют accepted subset; URI subscriptions не включаются. Единственный общий watcher сохраняет baseline до ACK, scoped catalog reads, Retry/Gone, cadence/coalescing и legacy delivery. JSON subscriptionId восстанавливается без числового сужения; SDK final Result/ErrorData потребляется owner, не отправляется новым terminal frame. Закрытие body/отмена до ACK дропает pending watcher и завершает/join-ит SDK pump; permit остаётся у body. Это runtime-перенос действующей подписки, не замена HTTP transport/session и не full/load/external-client qualification всего #107.
|
||||
|
||||
Envelopes-срез #107 на базе rc.25/rmcp3.9.0 заменяет handwritten `jsonrpc_result`/`jsonrpc_error` в `jsonrpc.rs` сериализацией настоящих `JsonRpcResponse<Value>` и `JsonRpcError`/`ErrorData`. Уже подключённые consumers — общий `build_app` HTTP JSON и lifecycle SSE terminal обеих revisions; новые dispatch/transport пути не добавляются. Локальная projection+restore сразу возвращает исходные JSON id (включая null, u64 и точную floating-point форму) и i64 error code, которые SDK-типы не представляют полностью; произвольный result и omission error.data сохраняются. Прежний guard correlation не меняется: JSON protocol errors содержат correlation data, lifecycle SSE terminal errors по-прежнему её опускают. Runtime wire controls и отдельный SDK oracle проверяют success/protocol error, а affected regressions — admission, revoked credentials, tool isError и cancellation. Входная валидация, safe response id, auth, статусы/headers, очереди/сессии и transport остаются прежними; это не завершение #107, feature qualification или production deployment.
|
||||
|
||||
Negotiation-results-срез #107 на базе rc.26/rmcp3.9.0 заменяет handwritten ответы legacy `initialize` и modern `server/discover` на настоящие `InitializeResult`/`DiscoverResult` в `protocol/lifecycle_sdk.rs`. Уже подключённый потребитель — штатный `build_app` HTTP JSON/SSE. Версии и их порядок заданы прежним allowlist, capabilities поступают только из registry; server identity, omissions и discovery ttlMs=0/cacheScope=private сохранены. SDK `ServerCapabilities` не представляет дополнительные top-level имена registry: после typed serialization восстанавливаются только отсутствующие ключи, без замены SDK-known полей. HTTP ATDD отдельно проверяет прежний wire и SDK execution, legacy initialize→initialized→защищённый вызов и отсутствие session operations у modern discovery; affected regression сохраняет frozen advertisement, unsupported revision rejection, auth/revocation/Agent scope и legacy transport lifecycle. Следующий initialize-input-срез на базе rc.27 заменяет `app/request.rs::InitializeParams` декодированием настоящего `InitializeRequestParams` в `protocol/lifecycle_sdk.rs`: штатный `handle_initialize` использует SDK `protocol_version` в прежнем allowlist. Локальная projection передаёт только protocolVersion с инертными обязательными SDK capabilities/clientInfo; исходные ignored clientInfo/extensions не валидируются, а raw capabilities сохраняют прежний object-предикат elicitation. HTTP admission (включая запрет sequence params и malformed _meta) остаётся до SDK. Отдельный typed runtime oracle и JSON/SSE tolerance/session ATDD подтверждают использование результата SDK, отсутствие новых отказов и прежний initialize→initialized→защищённый вызов. Generic dispatch/ping, session storage/TTL/reconnect, admission/auth и transport не переносились. Существующий SSE error.data omission не исправляется; полный #107, feature qualification и production deployment не завершены.
|
||||
@@ -55,6 +61,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