Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48436538f1 | ||
|
|
8f494679b8 | ||
|
|
0755e6e8e8 | ||
|
|
d01bdf019c |
No files matched your search
@@ -46,12 +46,15 @@ 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))
|
||||
|
||||
@@ -89,6 +89,11 @@ pub(crate) struct CounterSet {
|
||||
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,
|
||||
|
||||
@@ -239,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)
|
||||
}
|
||||
@@ -615,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);
|
||||
}
|
||||
|
||||
@@ -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,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; }
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -60,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 @@ 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;
|
||||
}
|
||||
@@ -45,8 +45,12 @@ Logging-handler-срез #107 поверх rc.38/rmcp3.9.0 подключает
|
||||
|
||||
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 не завершены.
|
||||
|
||||
Reference in new issue
Block a user