Merge pull request 'MCP: execute modern subscriptions through SDK listen handler' (#143) from delivery/rmcp107-subscriptions into main
CI / UI Checks (push) Successful in 9s
CI / Rust Checks (push) Successful in 53m15s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
Community Release / release (push) Successful in 1h14m52s

This commit was merged in pull request #143.
This commit is contained in:
bsodfather committed 2026-11-14 07:37:20 +00:00
commit 8f494679b8
13 files changed
+1003 -46

No files matched your search

+2
View File
@@ -52,6 +52,8 @@ 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;
+14 -13
View File
@@ -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);
}
@@ -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 &notification.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;
}
}
@@ -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);
@@ -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;
}
+2
View File
@@ -47,6 +47,8 @@ Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает
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 не завершены.