//! Story 3.19: Resource and Prompt list-change signals (FR-19); Story 3.5 adds the Tools signal of //! the same seam (FR-14). //! //! The positive result of the story is that a client which asked for the list-change signal of its //! revision learns that the *committed* Resource, Prompt or Tool catalog changed, and that the //! ordinary `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, //! `prompts/get` and `tools/list` stay authoritative for a client that misses the notification. //! //! Shape of the chosen seam (ARC decision, kanban t_c12863fb): a **stream-local watcher**. One open //! notification stream owns one bounded periodic read of the published Agent catalog the stream is //! scoped to; a change of the visible Resource/Prompt/Tool projection of that snapshot (the Resource //! and Prompt bindings plus the exact Tool definitions `tools/list` serves) produces the revision's //! list-change notification. There is no post-commit hook, no cross-process bus and no durable //! queue: the committed catalog is the source of truth, so a signal can never be produced before its //! commit, and a failed read can never roll the commit back — it only skips that tick and stays //! observable in tracing. //! //! Bounds (issue requirement: bounded queues/frequency/bytes): //! * one in-flight read per stream, one fixed poll interval, a read timeout and skipped ticks; //! * at most one frame per change type per tick, so a burst coalesces by the latest observed //! revision instead of queueing every intermediate commit; //! * the queue is a fixed-capacity channel; a slow reader drops the newest frame instead of blocking //! the producer or growing memory, and recovers through the authoritative list methods; //! * every frame has a fixed shape — a closed method name plus the request id of the subscription — //! so the byte bound follows from the id bound ([`MAX_SUBSCRIPTION_ID_BYTES`]). //! //! Scope boundary: this module serves list-change signals only. URI-content subscriptions //! (`resources/subscribe` / `notifications/resources/updated`) stay unimplemented and are never //! acknowledged or emitted here. use std::{ collections::{HashMap, VecDeque}, future::Future, pin::Pin, sync::{ Arc, Mutex, MutexGuard, atomic::{AtomicU64, Ordering}, }, time::{Duration, Instant}, }; use axum::response::sse::Event; use crank_registry::PublishedAgentCatalog; use futures_util::stream; use rmcp::model::{SubscriptionFilter, SubscriptionsListenRequestParams}; use serde::{Deserialize, Deserializer, de::Error}; use serde_json::{Value, json}; #[path = "signals_sdk.rs"] mod sdk; use tokio::sync::mpsc; use tracing::warn; use crate::app::AppState; /// The pinned key that correlates every message of one subscription stream with its /// `subscriptions/listen` request id. pub(crate) const SUBSCRIPTION_ID_KEY: &str = "io.modelcontextprotocol/subscriptionId"; /// `notifications/resources/list_changed` (both approved revisions). pub(crate) const RESOURCE_LIST_CHANGED: &str = "notifications/resources/list_changed"; /// `notifications/prompts/list_changed` (both approved revisions). pub(crate) const PROMPT_LIST_CHANGED: &str = "notifications/prompts/list_changed"; /// `notifications/tools/list_changed` (both approved revisions, Story 3.5). pub(crate) const TOOL_LIST_CHANGED: &str = "notifications/tools/list_changed"; /// `notifications/subscriptions/acknowledged` (modern revision only). #[cfg(test)] pub(crate) const SUBSCRIPTIONS_ACKNOWLEDGED: &str = "notifications/subscriptions/acknowledged"; /// Engineering default of the watcher tick. It is not a measured latency SLO: the story only needs /// "after commit", and the client always keeps the authoritative list methods for recovery. pub(crate) const POLL_INTERVAL: Duration = Duration::from_secs(1); /// Upper bound of one watcher read. A read that exceeds it is a skipped tick, exactly like a failed /// read: no signal, no rollback, one safe tracing event. pub(crate) const READ_TIMEOUT: Duration = Duration::from_secs(5); /// Frames a slow reader may fall behind before the newest frame is dropped (`coalescing`). pub(crate) const SIGNAL_QUEUE_CAPACITY: usize = 4; /// Bound of the encoded `subscriptions/listen` id carried by every frame of one stream. pub(crate) const MAX_SUBSCRIPTION_ID_BYTES: usize = 64; /// Bound of the legacy session stream table (memory bound; see [`StreamRegistry`]). pub(crate) const MAX_TRACKED_STREAMS: usize = 1_024; /// Bound of the URIs a modern filter may name. The server does not implement URI subscriptions, so /// this many names is already far more than a well-behaved client asks for. pub(crate) const MAX_FILTER_URIS: usize = 32; /// Bound of one URI in the modern filter: longer values are rejected without being echoed back. pub(crate) const MAX_FILTER_URI_BYTES: usize = 2_048; /// The one safe detail of a malformed or oversized `subscriptions/listen` filter. pub(crate) const INVALID_LISTEN_FILTER: &str = "invalid subscriptions/listen notification filter"; /// The three list-change signal types this server implements. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) struct Signals { pub(crate) resources: bool, pub(crate) prompts: bool, pub(crate) tools: bool, } impl Signals { /// All types: the legacy revision defines no client opt-in, so its stream carries every type. pub(crate) const ALL: Self = Self { resources: true, prompts: true, tools: true, }; #[cfg_attr(not(test), allow(dead_code))] // read by the unit oracle of the projection pub(crate) fn any(self) -> bool { self.resources || self.prompts || self.tools } fn intersect(self, other: Self) -> Self { Self { resources: self.resources && other.resources, prompts: self.prompts && other.prompts, tools: self.tools && other.tools, } } } /// Compatibility bounds around the real SDK filter, not a second protocol field model. #[derive(Debug, Default)] pub(crate) struct ListenFilter(SubscriptionFilter); // SDK optional fields accept null; the existing public filter contract rejects explicit null. fn validate_filter(value: &Value) -> Result<(), &'static str> { let object = value.as_object().ok_or(INVALID_LISTEN_FILTER)?; for key in [ "toolsListChanged", "promptsListChanged", "resourcesListChanged", "resourceSubscriptions", ] { if object.get(key).is_some_and(Value::is_null) { return Err(INVALID_LISTEN_FILTER); } } Ok(()) } impl<'de> Deserialize<'de> for ListenFilter { fn deserialize>(deserializer: D) -> Result { let value = Value::deserialize(deserializer)?; validate_filter(&value).map_err(D::Error::custom)?; serde_json::from_value(value) .map(Self) .map_err(D::Error::custom) } } /// Decode only the reviewed notifications projection: HTTP admission already owns `_meta`. #[derive(Debug)] pub(crate) struct ListenParams { pub(crate) notifications: ListenFilter, } impl<'de> Deserialize<'de> for ListenParams { fn deserialize>(deserializer: D) -> Result { let value = Value::deserialize(deserializer)?; let notifications = value .as_object() .and_then(|object| object.get("notifications")) .ok_or_else(|| D::Error::custom(INVALID_LISTEN_FILTER))?; validate_filter(notifications).map_err(D::Error::custom)?; let params: SubscriptionsListenRequestParams = serde_json::from_value(json!({"notifications": notifications})) .map_err(D::Error::custom)?; #[cfg(test)] crate::app::dispatch_observer::sdk_subscriptions_listen_decoded(); Ok(Self { notifications: ListenFilter(params.notifications), }) } } /// The bounded input contract of a `subscriptions/listen` filter. pub(crate) enum FilterOutcome { /// The list-change subset this server honours for the stream. Accepted(Signals), /// One safe detail: no URI, name or value the client sent is echoed back. Invalid(&'static str), } impl ListenFilter { /// Validate the bounded inputs and keep only the honoured types. /// /// `resourceSubscriptions` is not implemented in the current scope, which is what the /// acknowledgment reports: it is simply not honoured, and the pinned schema forbids the server /// from sending a type it did not agree to. pub(crate) fn accepted(&self) -> FilterOutcome { let uris = self.0.resource_subscriptions.as_deref().unwrap_or_default(); if uris.len() > MAX_FILTER_URIS || uris.iter().any(|uri| uri.len() > MAX_FILTER_URI_BYTES) { return FilterOutcome::Invalid(INVALID_LISTEN_FILTER); } FilterOutcome::Accepted(Signals { resources: self.0.resources_list_changed == Some(true), prompts: self.0.prompts_list_changed == Some(true), tools: self.0.tools_list_changed == Some(true), }) } } /// The exact bound Resource/Prompt/Tool projection of one published Agent catalog. /// /// The projection is derived from the same committed catalog read that already feeds /// `resources/list`, `resources/templates/list`, `prompts/list`, `prompts/get` and `tools/list`: the /// exact Resource and Prompt bindings of the published Agent snapshot, in deterministic binding /// order, and the exact Tool definitions that `tools/list` would serve. The Tool part is taken from /// [`crate::manifest::catalog_tool_definitions`] rather than from the bindings, because that is the /// projection the client sees: it also depends on the Tool selection policy (mode, groups, search /// settings), and in `Search` mode it does not depend on the bindings at all. `catalog_revision` /// alone is *not* the comparison key — a commit that only changes Tools must not produce a Resource /// or Prompt signal, and vice versa — so the three projections are compared on their own. /// /// shortcut: a Resource revocation invalidates a bound publication without a new Agent snapshot, so /// it does not change this projection and produces no list-change signal; the revocation gate at /// read time (Story 3.8) still fails closed, and a faithful revocation signal needs a bounded /// registry read that the current scope does not have. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct CatalogFingerprint { resources: Vec<(String, u32)>, prompts: Vec<(String, u32)>, /// Canonical JSON of every definition `tools/list` serves, sorted so a re-ordered read is not a /// false change. tools: Vec, } impl CatalogFingerprint { pub(crate) fn of(catalog: &PublishedAgentCatalog) -> Self { fn sorted(values: impl Iterator) -> Vec { let mut sorted = values.collect::>(); sorted.sort_unstable(); sorted } Self { resources: sorted(catalog.resources.iter().map(|binding| { ( binding.resource_id.as_str().to_owned(), binding.resource_version, ) })), prompts: sorted(catalog.prompts.iter().map(|binding| { ( binding.prompt_id.as_str().to_owned(), binding.prompt_version, ) })), tools: sorted( crate::manifest::catalog_tool_definitions(catalog) .into_iter() .map(|definition| definition.to_string()), ), } } /// The list-change types whose visible projection differs between `previous` and `self`. pub(crate) fn changes_since(&self, previous: &Self) -> Signals { Signals { resources: self.resources != previous.resources, prompts: self.prompts != previous.prompts, tools: self.tools != previous.tools, } } } /// The wire contract of one stream. #[derive(Clone, Debug)] 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. Modern(Value), } impl Wire { fn signal_frames(&self, signals: Signals) -> Vec { let mut frames = Vec::with_capacity(3); for (changed, method) in [ (signals.resources, RESOURCE_LIST_CHANGED), (signals.prompts, PROMPT_LIST_CHANGED), (signals.tools, TOOL_LIST_CHANGED), ] { if !changed { continue; } let subscription_id = match self { Wire::Legacy => None, Wire::Modern(subscription_id) => Some(subscription_id), }; frames.push(sdk::signal_frame(method, subscription_id)); } frames } } /// The first modern frame: the accepted subset, before any list-change notification of the stream. pub(crate) fn acknowledged_frame(subscription_id: &Value, accepted: Signals) -> String { sdk::acknowledged_frame(subscription_id, accepted) } /// The subscription id of a `subscriptions/listen` request, or `None` when its encoding is not a /// bounded identity carrier. pub(crate) fn subscription_id(request_id: &Value) -> Option { let encoded = request_id.to_string(); (encoded.len() <= MAX_SUBSCRIPTION_ID_BYTES).then(|| request_id.clone()) } /// Bounded table of the legacy session that currently owns the notification stream. /// /// The pinned legacy transport forbids broadcasting one message across several SSE streams of the /// same session, and the community scope keeps exactly one producer per session: the newest admitted /// `GET` takes the signals over and the older stream ends. A retired stream (session `DELETE`) or a /// superseded generation never writes into a reconnect. #[derive(Default)] pub(crate) struct StreamRegistry { next_generation: AtomicU64, owners: Mutex>, } impl StreamRegistry { pub(crate) fn new() -> Self { Self::default() } /// Admit the notification stream of one session and return its generation. pub(crate) fn admit(&self, session_id: &str) -> Option { let generation = self.next_generation.fetch_add(1, Ordering::Relaxed) + 1; let mut owners = self.lock()?; if owners.len() >= MAX_TRACKED_STREAMS && !owners.contains_key(session_id) { // Bounded table: forget the whole owner set instead of growing without a limit. Each // running producer still holds its own generation, so the worst case is a stream that // can no longer be told apart from a newer one — never unbounded memory. owners.clear(); } owners.insert(session_id.to_owned(), generation); Some(generation) } /// Whether `generation` still owns the stream of `session_id`. pub(crate) fn is_current(&self, session_id: &str, generation: u64) -> bool { self.lock() .and_then(|owners| owners.get(session_id).copied()) .is_some_and(|current| current == generation) } /// Stop the producer of one session (`DELETE`, or a session that no longer exists). pub(crate) fn retire(&self, session_id: &str) { if let Some(mut owners) = self.lock() { owners.remove(session_id); } } fn lock(&self) -> Option>> { self.owners.try_lock().ok() } } /// Everything one watcher needs. pub(crate) struct Watch { pub(crate) workspace_slug: String, pub(crate) agent_slug: String, /// The signal types this stream may deliver. pub(crate) signals: Signals, pub(crate) wire: Wire, /// The legacy session lease: the producer stops when the stream is superseded or retired. pub(crate) legacy_stream: Option<(Arc, String, u64)>, /// Lifetime bound inherited from the legacy transport session TTL. pub(crate) deadline: Option, } /// One committed-catalog read of a watcher tick. /// /// The reader is a closure so the failure path is driveable in a unit oracle without a live /// registry: production passes [`read`] over the shared [`AppState`], and the oracle passes a /// scripted sequence. pub(crate) type ReadFuture = Pin> + Send>>; /// A source of committed-catalog reads. One call per tick. pub(crate) type Reader = Box ReadFuture + Send>; /// Start the stream-local watcher and return the bounded frame queue of the response stream. /// /// 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, watch: Watch) -> mpsc::Receiver { let scope = (watch.workspace_slug.clone(), watch.agent_slug.clone()); let reader: Reader = Box::new(move || { let state = Arc::clone(&state); let scope = scope.clone(); Box::pin(async move { read(&state, &scope).await }) }); let (sender, receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY); #[cfg(not(test))] tokio::spawn(run(watch, sender, reader)); #[cfg(test)] { let observer = crate::app::dispatch_observer::installed_observer(); tokio::spawn(async move { match observer { Some(observer) => { crate::app::dispatch_observer::observe(observer, run(watch, sender, reader)) .await } None => run(watch, sender, reader).await, } }); } receiver } async fn run(watch: Watch, sender: mpsc::Sender, mut read: Reader) { let mut baseline = match read().await { Ok(fingerprint) => Some(fingerprint), Err(ReadError::Gone) => return, Err(ReadError::Retry) => { observe_failure(); None } }; loop { if !still_owned(&watch) || sender.is_closed() { return; } if watch .deadline .is_some_and(|deadline| Instant::now() >= deadline) { return; } tokio::time::sleep(POLL_INTERVAL).await; if !still_owned(&watch) { return; } 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); } } 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, // The committed catalog is untouched: the failure is observable and this tick is skipped. Err(_) => observe_failure(), } } } pub(crate) enum ReadError { /// The published Agent behind this stream is gone: the producer ends. Gone, /// The catalog could not be read this tick: skip it, keep the committed state. Retry, } fn still_owned(watch: &Watch) -> bool { match &watch.legacy_stream { Some((registry, session_id, generation)) => registry.is_current(session_id, *generation), None => true, } } async fn read(state: &AppState, scope: &(String, String)) -> Result { let catalog = tokio::time::timeout(READ_TIMEOUT, state.catalog.get_catalog(&scope.0, &scope.1)) .await .map_err(|_| ReadError::Retry)? .map_err(|error| match error { crank_registry::RegistryError::PublishedAgentNotFound { .. } => ReadError::Gone, _ => ReadError::Retry, })?; Ok(CatalogFingerprint::of(&catalog)) } /// One safe, closed-vocabulary observation of a skipped tick: no URI, Agent name, credential or raw /// error text is read here. fn observe_failure() { warn!( name: "mcp.signals.read_failed", error_category = "catalog", "catalog change signal read failed" ); } /// The bounded SSE body of one signal stream: the leading frames (acknowledgment), then the queue, /// ending when the producer ends. The caller's stream permit lives in `guard` and is released when /// the response stream is dropped. pub(crate) fn frames_stream( first: Vec, receiver: mpsc::Receiver, guard: G, ) -> impl stream::Stream> { let pending: VecDeque = first.into(); 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))); } let frame = receiver.recv().await?; pending.push_back(frame); } }, ) } #[cfg(test)] #[path = "signals_tests.rs"] mod tests;