diff --git a/crates/rmcp/Cargo.toml b/crates/rmcp/Cargo.toml index c78b7af1c..3103cc030 100644 --- a/crates/rmcp/Cargo.toml +++ b/crates/rmcp/Cargo.toml @@ -24,6 +24,9 @@ features = [ "client", "client-side-sse", "elicitation", + "events", + "events-webhook", + "events-webhook-receiver", "macros", "request-state", "reqwest", @@ -152,6 +155,12 @@ elicitation = ["dep:url"] # SEP-2322 requestState integrity helper (HMAC-SHA256 seal/open codec) request-state = ["dep:hmac", "dep:zeroize", "base64"] skills-fs = ["server", "base64", "dep:cap-std", "dep:cap-fs-ext", "dep:yaml_serde", "dep:windows-sys"] +# MCP Events Beta catalog, polling, and push; role and transport features stay independent. +events = [] +# Standard Webhooks verification and the low-level Events client RPCs. +events-webhook-receiver = ["events", "base64", "dep:hmac", "dep:http", "dep:rand", "dep:zeroize", "zeroize/serde"] +# Events server dispatcher with HTTPS-only outbound delivery. +events-webhook = ["server", "events-webhook-receiver", "reqwest", "dep:url", "dep:bytes", "tokio/net"] # reqwest http client __reqwest = ["dep:reqwest"] @@ -223,6 +232,7 @@ schemars = ["dep:schemars"] [dev-dependencies] tokio = { version = "1", features = ["full", "test-util"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs"] } schemars = { version = "1.1.0", features = ["chrono04"] } axum = { version = "0.8", default-features = false, features = ["http1", "tokio"] } hyper = { version = "1", features = ["server", "http1"] } diff --git a/crates/rmcp/README.md b/crates/rmcp/README.md index 6f57acfd5..b0ab8afe3 100644 --- a/crates/rmcp/README.md +++ b/crates/rmcp/README.md @@ -27,6 +27,9 @@ For **getting started**, **usage guides**, and **full MCP feature documentation* | `auth-enterprise-managed` | EMA/XAA refresh-token and ID-JAG exchanges for registered public and confidential clients (includes `auth`) | | | `elicitation` | Elicitation support | | | `skills-fs` | Serve SEP-2640 skills from a directory tree (`SkillCatalog`) | | +| `events` | SEP-3415 Events: discovery, polling, push, and catalog change notifications (MCP 2026-07-28 or later) | | +| `events-webhook-receiver` | Verify Events webhook deliveries and subscribe to them from a client (includes `events`) | | +| `events-webhook` | Deliver Events by webhook from a server (includes `events-webhook-receiver`) | | ### Transport features diff --git a/crates/rmcp/src/events.rs b/crates/rmcp/src/events.rs new file mode 100644 index 000000000..c28f141b3 --- /dev/null +++ b/crates/rmcp/src/events.rs @@ -0,0 +1,86 @@ +//! MCP Events Beta for protocol 2026-07-28 and later. +//! +//! Install an `EventsServer` in `ServerHandler::events`. Use `EventsClient` +//! with a peer that advertised Events in discovery. +//! Persist only checkpoints whose events you have processed. +//! +//! ``` +//! # #[cfg(feature = "server")] +//! # fn main() -> Result<(), rmcp::events::wire::EventsError> { +//! use rmcp::{ServerHandler, events::{ +//! server::{CheckedBatch, Descriptor, EventsServer}, +//! wire::DeliveryMode, +//! }, model::JsonObject}; +//! +//! struct App(EventsServer); +//! impl ServerHandler for App { +//! fn events(&self) -> Option<&EventsServer> { Some(&self.0) } +//! } +//! let events = EventsServer::new(); +//! events.register_check( +//! Descriptor::typed::("demo.tick", "Demo tick", [DeliveryMode::Poll]), +//! |_, _, _| async { Ok(CheckedBatch::new("head")) }, +//! )?; +//! let _app = App(events); +//! # Ok(()) +//! # } +//! # #[cfg(not(feature = "server"))] +//! # fn main() {} +//! ``` + +#[cfg(feature = "client")] +pub mod client; +#[cfg(feature = "server")] +pub mod server; +#[cfg(feature = "events-webhook-receiver")] +pub mod webhook; +pub mod wire; + +#[cfg(any(feature = "server", feature = "client"))] +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct StreamParams { + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + arguments: Option, + #[serde(skip_serializing_if = "Option::is_none")] + cursor: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_age_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + heartbeat_ms: Option, +} + +pub(crate) const EXTENSION: &str = "io.modelcontextprotocol/events"; +pub(crate) fn advertises_list_changes(capabilities: &crate::model::ServerCapabilities) -> bool { + capabilities + .extensions + .as_ref() + .and_then(|extensions| extensions.get(EXTENSION)) + .and_then(|settings| settings.get("listChanged")) + .and_then(serde_json::Value::as_bool) + == Some(true) +} + +#[cfg(any(feature = "server", feature = "client"))] +mod methods { + pub(crate) const LIST: &str = "events/list"; + pub(crate) const POLL: &str = "events/poll"; + pub(crate) const STREAM: &str = "events/stream"; + pub(crate) const ACTIVE: &str = "notifications/events/active"; + pub(crate) const EVENT: &str = "notifications/events/event"; + pub(crate) const HEARTBEAT: &str = "notifications/events/heartbeat"; + pub(crate) const ERROR: &str = "notifications/events/error"; + pub(crate) const TERMINATED: &str = "notifications/events/terminated"; + pub(crate) const LIST_CHANGED: &str = "notifications/events/list_changed"; +} +#[cfg(any(feature = "server", feature = "client"))] +pub(crate) use methods::*; + +#[cfg(feature = "server")] +pub(crate) fn named_method(method: &str) -> bool { + matches!( + method, + POLL | STREAM | "events/subscribe" | "events/unsubscribe" + ) +} diff --git a/crates/rmcp/src/events/client.rs b/crates/rmcp/src/events/client.rs new file mode 100644 index 000000000..330064de3 --- /dev/null +++ b/crates/rmcp/src/events/client.rs @@ -0,0 +1,240 @@ +//! Explicit client access to a discovered Events catalog, polls, and subscriptions. + +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; + +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; + +use super::{ + EXTENSION, LIST, POLL, + wire::{ + DeliveryMode, EventsError, ListEventsResult, PollParams, PollResult, not_found, unsupported, + }, +}; +use crate::{ + Peer, RoleClient, ServiceError, + model::{ClientRequest, CustomRequest, JsonObject, ProtocolVersion, ServerResult}, + service::PeerRequestOptions, +}; + +const REQUEST_BUDGET: std::time::Duration = std::time::Duration::from_secs(15); + +mod subscription; +#[cfg(feature = "events-webhook-receiver")] +mod webhook; +pub use subscription::{EventSubscription, EventUpdate, SubscriptionOptions}; + +/// A client for a peer that advertised the Events Beta via modern discovery. +/// +/// Start the underlying service in Discover mode (or Auto with successful +/// discovery). Invoking these methods never opts a legacy peer into Events. +pub struct EventsClient { + peer: Peer, + catalog: Arc>>, +} + +#[derive(Clone)] +struct CatalogEntry { + delivery: Vec, + input_schema: Arc, +} + +impl std::fmt::Debug for EventsClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("EventsClient").finish_non_exhaustive() + } +} + +/// A validated catalog entry selected for this request; the HTTP worker +/// consumes it without maintaining its own Events catalog. +#[cfg(feature = "transport-streamable-http-client")] +#[derive(Clone)] +pub(crate) struct RoutingSchema(pub(crate) Option>); + +impl EventsClient { + /// Use a peer whose discovery result advertises Events. + pub fn new(peer: Peer) -> Self { + Self { + peer, + catalog: Arc::default(), + } + } + + /// List one catalog page. Starting a new list invalidates cached routing schemas. + pub async fn list_page(&self, cursor: Option<&str>) -> Result { + self.require_advertisement()?; + if cursor.is_none() { + self.invalidate_catalog().await; + } + self.request_page(cursor).await + } + + async fn request_page(&self, cursor: Option<&str>) -> Result { + let params = cursor.map(|cursor| json!({ "cursor": cursor })); + let request = CustomRequest::new(LIST, params); + #[cfg(feature = "transport-streamable-http-client")] + let request = { + let mut request = request; + request.extensions.insert(RoutingSchema(None)); + request + }; + decode_result(self.request(request).await?) + } + + /// Poll once. Persist a non-null cursor only after consuming the batch. + pub async fn poll(&self, params: PollParams) -> Result { + self.require_advertisement()?; + let body = encode_params(¶ms)?; + self.with_route(¶ms.name, |entry| { + let request = route(POLL, body.clone(), entry.input_schema); + async move { decode_result(self.request(request).await?) } + }) + .await + } + + fn require_advertisement(&self) -> Result<(), EventsError> { + if self.peer.peer_info().is_some_and(|peer| { + peer.protocol_version >= ProtocolVersion::V_2026_07_28 + && peer + .capabilities + .extensions + .as_ref() + .is_some_and(|extensions| extensions.contains_key(EXTENSION)) + }) { + Ok(()) + } else { + Err(EventsError::MethodNotFound) + } + } + + async fn request(&self, request: CustomRequest) -> Result { + self.peer + .send_request_with_option( + ClientRequest::CustomRequest(request), + PeerRequestOptions::with_timeout(REQUEST_BUDGET), + ) + .await + .map_err(from_service)? + .await_response() + .await + .map_err(from_service) + } + + async fn invalidate_catalog(&self) { + self.catalog.lock().await.clear(); + } + + async fn with_route>>( + &self, + name: &str, + request: impl Fn(CatalogEntry) -> F, + ) -> Result { + match request(self.descriptor_cached(name, false).await?).await { + Err(EventsError::HeaderMismatch(_)) => { + request(self.descriptor_cached(name, true).await?).await + } + result => result, + } + } + + async fn descriptor_cached( + &self, + name: &str, + refresh: bool, + ) -> Result { + let mut cached = self.catalog.lock().await; + if refresh || !cached.contains_key(name) { + cached.clear(); + *cached = self.load_catalog().await?; + } + cached.get(name).cloned().ok_or_else(not_found) + } + + async fn load_catalog(&self) -> Result, EventsError> { + let mut catalog = HashMap::new(); + let mut seen = HashSet::new(); + let mut cursor = None; + loop { + let page = self.request_page(cursor.as_deref()).await?; + for descriptor in page.events { + catalog.insert( + descriptor.name, + CatalogEntry { + delivery: descriptor.delivery, + input_schema: descriptor.input_schema, + }, + ); + } + let Some(next) = page.next_cursor else { + return Ok(catalog); + }; + if !seen.insert(next.clone()) { + return Err(EventsError::UnexpectedResponse); + } + cursor = Some(next); + } + } +} + +fn from_service(error: ServiceError) -> EventsError { + match error { + ServiceError::McpError(error) => EventsError::from(error), + error => EventsError::Service(Box::new(error)), + } +} + +fn decode_result(result: ServerResult) -> Result { + let ServerResult::CustomResult(result) = result else { + return Err(EventsError::UnexpectedResponse); + }; + serde_json::from_value(result.0).map_err(|_| EventsError::UnexpectedResponse) +} + +fn encode_params(params: &impl Serialize) -> Result { + serde_json::to_value(params) + .map_err(|_| EventsError::InvalidParams("invalid Events parameters".into())) +} + +fn route(method: &str, params: Value, schema: Arc) -> CustomRequest { + let request = CustomRequest::new(method, Some(params)); + #[cfg(feature = "transport-streamable-http-client")] + let request = { + let mut request = request; + request.extensions.insert(RoutingSchema(Some(schema))); + request + }; + #[cfg(not(feature = "transport-streamable-http-client"))] + let _ = schema; + request +} + +#[cfg(all(test, feature = "transport-streamable-http-client"))] +mod tests { + use super::*; + + #[test] + fn malformed_entries_are_excluded_before_their_headers_are_used() { + let event = |name, field, annotation| { + json!({ + "name": name, "delivery": ["poll"], "payloadSchema": {}, + "inputSchema": {"properties": {"scope": {"type": field, "x-mcp-header": annotation}}} + }) + }; + let result: ListEventsResult = serde_json::from_value(json!({ + "resultType": "complete", "nextCursor": "next", + "events": [ + event("valid", "string", "Scope"), + event("invalid-token", "string", "bad token"), + event("invalid-schema", "number", "Scope"), + {"name":"missing-payload","delivery":["poll"],"inputSchema":{}} + ] + })) + .unwrap(); + assert_eq!(result.events.len(), 1); + assert_eq!(result.events[0].name, "valid"); + assert_eq!(result.next_cursor.as_deref(), Some("next")); + } +} diff --git a/crates/rmcp/src/events/client/subscription.rs b/crates/rmcp/src/events/client/subscription.rs new file mode 100644 index 000000000..600c91248 --- /dev/null +++ b/crates/rmcp/src/events/client/subscription.rs @@ -0,0 +1,665 @@ +use std::{ + fmt, + hash::{BuildHasher, RandomState}, + pin::Pin, + task::{Context, Poll}, + time::Duration, +}; + +use futures::{Stream, StreamExt, stream}; +use serde::Deserialize; +use tokio::{ + sync::mpsc, + time::{Instant, sleep_until, timeout_at}, +}; + +use super::*; +use crate::{ + events::{ + ACTIVE, ERROR, EVENT, HEARTBEAT, STREAM, StreamParams, TERMINATED, + wire::{EventOccurrence, terminal}, + }, + model::{ErrorCode, GetMeta, JsonObject, ServerNotification}, + service::{PeerRequestOptions, RequestHandle}, +}; + +const FRAME_CAPACITY: usize = 64; +const POLL_FLOOR_MS: u64 = 1_000; + +/// Mode selection and replay position for [`EventsClient::subscribe`]. +#[derive(Clone, Debug, Default)] +#[non_exhaustive] +pub struct SubscriptionOptions { + /// Require a particular delivery mode. By default, prefer push to polling. + pub mode: Option, + /// Last consumed Events cursor, or `None` to start at the current head. + pub cursor: Option, + /// Limit historical replay by age, in milliseconds. + pub max_age_ms: Option, +} + +/// An ordered update from one Events subscription. +#[derive(Debug)] +#[non_exhaustive] +pub enum EventUpdate { + /// A delivered occurrence. + Occurrence(EventOccurrence), + /// A safe position to persist, including after quiet progress. + Checkpoint(String), + /// Some occurrences may have been skipped. Delivered before the new checkpoint. + Gap, + /// Delivery can continue, possibly after reconnecting. + RecoverableError(EventsError), + /// Delivery ended. + Terminated(EventsError), +} + +#[cfg(not(feature = "local"))] +type Updates = Pin + Send>>; +#[cfg(feature = "local")] +type Updates = Pin>>; + +/// One push or managed-poll subscription. Poll the stream to drive delivery. +/// +/// A checkpoint follows the events it covers; only persist it after handling +/// those events. Dropping this handle stops polling or cancels the push request. +pub struct EventSubscription { + updates: Updates, +} + +impl fmt::Debug for EventSubscription { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EventSubscription").finish_non_exhaustive() + } +} + +impl Stream for EventSubscription { + type Item = EventUpdate; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.updates.as_mut().poll_next(cx) + } +} + +impl EventsClient { + /// Select a usable catalog mode and create a subscription to one event type. + /// + /// The delivery request starts when the returned stream is polled. Drop + /// the stream to stop delivery without affecting other subscriptions. + pub async fn subscribe( + &self, + name: impl Into, + arguments: Option, + options: SubscriptionOptions, + ) -> Result { + if options.mode == Some(DeliveryMode::Webhook) { + return Err(unsupported(DeliveryMode::Webhook)); + } + self.require_advertisement()?; + let name = name.into(); + let descriptor = self.descriptor_cached(&name, false).await?; + let mode = match options.mode { + Some(mode) if supports(&descriptor, mode) => mode, + Some(mode) => return Err(unsupported(mode)), + None if supports(&descriptor, DeliveryMode::Push) => DeliveryMode::Push, + None if supports(&descriptor, DeliveryMode::Poll) => DeliveryMode::Poll, + None => { + return Err(EventsError::Unsupported { + feature: "deliveryMode".into(), + value: None, + reason: None, + }); + } + }; + let driver = Driver { + client: EventsClient { + peer: self.peer.clone(), + catalog: self.catalog.clone(), + }, + name, + arguments, + mode, + cursor: options.cursor, + max_age_ms: options.max_age_ms, + delivery: Delivery::default(), + push: None, + retry: 0, + next_at: None, + done: false, + }; + Ok(EventSubscription { + updates: Box::pin( + stream::unfold(driver, |mut driver| async { + let item = driver.next().await?; + Some((item, driver)) + }) + .fuse(), + ), + }) + } +} + +fn supports(descriptor: &CatalogEntry, mode: DeliveryMode) -> bool { + matches!(mode, DeliveryMode::Push | DeliveryMode::Poll) && descriptor.delivery.contains(&mode) +} + +// Keep only the current poll page (or one push frame) outside the existing +// bounded notification channel. Advance over it as the consumer pulls. +#[derive(Default)] +struct Delivery { + events: std::vec::IntoIter, + event: Option, + position: Option<(Option, bool)>, + gap: bool, +} + +impl Delivery { + fn stage_position(&mut self, position: Option, truncated: bool) { + self.gap = truncated && position.is_some(); + self.position = Some((position, self.gap)); + } + + fn next(&mut self, cursor: &mut Option) -> Option { + if std::mem::take(&mut self.gap) { + return Some(EventUpdate::Gap); + } + if let Some(event) = self.event.take().or_else(|| self.events.next()) { + return Some(EventUpdate::Occurrence(event)); + } + if let Some((position, report_gap_checkpoint)) = self.position.take() + && (*cursor != position || report_gap_checkpoint) + { + *cursor = position; + return cursor.clone().map(EventUpdate::Checkpoint); + } + None + } +} + +struct Driver { + client: EventsClient, + name: String, + arguments: Option, + mode: DeliveryMode, + cursor: Option, + max_age_ms: Option, + delivery: Delivery, + push: Option, + retry: u8, + next_at: Option, + done: bool, +} + +impl Driver { + async fn next(&mut self) -> Option { + while !self.done { + if let Some(update) = self.delivery.next(&mut self.cursor) { + return Some(update); + } + if let Some(at) = self.next_at.take() { + sleep_until(at).await; + } + let result = match self.mode { + DeliveryMode::Push => self.push_update().await, + DeliveryMode::Poll => self.poll_page().await.map(|()| None), + _ => unreachable!("mode selected from usable catalog delivery"), + }; + match result { + Ok(Some(update)) => return Some(update), + Ok(None) => {} + Err(error) if self.can_retry(&error) => { + self.push = None; + let minimum = if self.mode == DeliveryMode::Poll { + POLL_FLOOR_MS + } else { + 0 + }; + self.next_at = Some(Instant::now() + retry_delay(self.retry, minimum)); + self.retry = self.retry.saturating_add(1); + return Some(EventUpdate::RecoverableError(error)); + } + Err(error) => return Some(self.finish(error).await), + } + } + None + } + + fn can_retry(&self, error: &EventsError) -> bool { + !self.client.peer.is_transport_closed() && retryable(error) + } + + async fn finish(&mut self, error: EventsError) -> EventUpdate { + self.done = true; + self.push = None; + if terminal(&error) { + self.client.invalidate_catalog().await; + } + EventUpdate::Terminated(error) + } + + async fn poll_page(&mut self) -> Result<(), EventsError> { + let params = PollParams { + name: self.name.clone(), + arguments: self.arguments.clone(), + cursor: self.cursor.clone(), + max_age_ms: self.max_age_ms, + max_events: None, + }; + let result = self.client.poll(params).await?; + if result.events.iter().any(|event| event.name != self.name) { + return Err(EventsError::UnexpectedResponse); + } + self.max_age_ms = None; + self.retry = 0; + let progressed = result.cursor.is_some() && self.cursor != result.cursor; + if !result.has_more || !progressed { + let delay = if result.has_more { + POLL_FLOOR_MS + } else { + result.next_poll_ms.max(POLL_FLOOR_MS) + }; + self.next_at = Some(deadline(delay)); + } else { + tokio::task::yield_now().await; + } + self.delivery.events = result.events.into_iter(); + self.delivery + .stage_position(result.cursor, result.truncated); + Ok(()) + } + + async fn open(&self, entry: CatalogEntry) -> Result<(Push, Frame), EventsError> { + if !supports(&entry, DeliveryMode::Push) { + return Err(unsupported(DeliveryMode::Push)); + } + let params = StreamParams { + name: self.name.clone(), + arguments: self.arguments.clone(), + cursor: self.cursor.clone(), + max_age_ms: self.max_age_ms, + heartbeat_ms: None, + }; + let request = route(STREAM, encode_params(¶ms)?, entry.input_schema); + let deadline = Instant::now() + REQUEST_BUDGET; + let (request, frames) = timeout_at( + deadline, + self.client.peer.send_subscription_request( + ClientRequest::CustomRequest(request), + PeerRequestOptions::no_options(), + FRAME_CAPACITY, + ), + ) + .await + .map_err(|_| timed_out(REQUEST_BUDGET))? + .map_err(from_service)?; + let mut push = Push { + request, + frames, + deadline, + watchdog: REQUEST_BUDGET, + active: false, + }; + // An error before activation may require rebuilding the routing headers. + loop { + let frame = push.next().await?; + if !matches!(frame, Frame::Unknown) { + return Ok((push, frame)); + } + } + } + + async fn push_update(&mut self) -> Result, EventsError> { + let frame = match &mut self.push { + Some(push) => push.next().await?, + None => { + let (push, frame) = self + .client + .with_route(&self.name, |entry| self.open(entry)) + .await?; + self.push = Some(push); + frame + } + }; + let push = self.push.as_mut().expect("opened push request"); + if push.active && !matches!(&frame, Frame::Active(_) | Frame::Unknown) { + self.retry = 0; + } + match frame { + Frame::Unknown => {} + Frame::Active(active) => { + if active.heartbeat_ms == 0 { + return Err(EventsError::UnexpectedResponse); + } + push.active = true; + push.watchdog = delay(active.heartbeat_ms.saturating_mul(3)); + push.deadline = Instant::now() + push.watchdog; + self.delivery + .stage_position(active.position.cursor, active.truncated); + } + _ if !push.active => return Err(EventsError::UnexpectedResponse), + Frame::Event(event) => { + if event.name != self.name { + return Err(EventsError::UnexpectedResponse); + } + let cursor = event.cursor.clone(); + self.delivery.event = Some(event); + self.delivery.stage_position(cursor, false); + } + Frame::Heartbeat(position) => self.delivery.stage_position(position.cursor, false), + Frame::Error(error) => return Ok(Some(EventUpdate::RecoverableError(error))), + Frame::Terminated(error) => { + // Release the pending request even if the peer never writes + // the final frame. The notification alone ends the subscription. + return Ok(Some(self.finish(error).await)); + } + } + Ok(None) + } +} + +impl Drop for Push { + fn drop(&mut self) { + let request = &mut self.request; + request.peer.unregister_subscription(&request.id); + if matches!( + request.rx.try_recv(), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) + ) { + request + .peer + .try_cancel_request(request.id.clone(), Some("Events request cancelled".into())); + } + } +} + +struct Push { + request: RequestHandle, + frames: mpsc::Receiver, + deadline: Instant, + watchdog: Duration, + active: bool, +} + +impl Push { + async fn next(&mut self) -> Result { + tokio::select! { + biased; + Some(frame) = self.frames.recv() => { + if frame.get_meta().subscription_id().as_ref() != Some(&self.request.id) { + return Err(EventsError::UnexpectedResponse); + } + if self.active { + self.deadline = Instant::now() + self.watchdog; + } + Frame::decode(frame) + } + result = &mut self.request.rx => { + if let Ok(Err(error)) = result { + return Err(from_service(error)); + } + Err(from_service(ServiceError::TransportClosed)) + } + () = sleep_until(self.deadline) => Err(timed_out(self.watchdog)), + } + } +} + +#[derive(Deserialize)] +struct Position { + cursor: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Active { + #[serde(flatten)] + position: Position, + #[serde(default)] + truncated: bool, + heartbeat_ms: u64, +} + +#[derive(Deserialize)] +struct Problem { + error: crate::ErrorData, +} + +enum Frame { + Active(Active), + Event(EventOccurrence), + Heartbeat(Position), + Error(EventsError), + Terminated(EventsError), + Unknown, +} + +impl Frame { + fn decode(notification: ServerNotification) -> Result { + let ServerNotification::CustomNotification(notification) = notification else { + return Err(EventsError::UnexpectedResponse); + }; + if notification.method.starts_with("notifications/events/") + && !matches!( + notification.method.as_str(), + ACTIVE | EVENT | HEARTBEAT | ERROR | TERMINATED + ) + { + return Ok(Self::Unknown); + } + let value = notification.params.ok_or(EventsError::UnexpectedResponse)?; + Ok(match notification.method.as_str() { + ACTIVE => Self::Active(parse(value)?), + EVENT => { + let mut event: EventOccurrence = parse(value)?; + let metadata = notification + .extensions + .get::(); + if let Some(metadata) = metadata { + event + .meta + .get_or_insert_default() + .extend(metadata.0.0.clone()); + } + if let Some(meta) = &mut event.meta { + meta.remove("io.modelcontextprotocol/subscriptionId"); + if meta.is_empty() { + event.meta = None; + } + } + Self::Event(event) + } + HEARTBEAT => Self::Heartbeat(parse(value)?), + ERROR => Self::Error(parse::(value)?.error.into()), + TERMINATED => Self::Terminated(parse::(value)?.error.into()), + _ => return Err(EventsError::UnexpectedResponse), + }) + } +} + +fn parse(value: Value) -> Result { + serde_json::from_value(value).map_err(|_| EventsError::UnexpectedResponse) +} + +fn timed_out(timeout: Duration) -> EventsError { + from_service(ServiceError::Timeout { timeout }) +} + +fn retryable(error: &EventsError) -> bool { + match error { + EventsError::Service(error) => matches!( + error.as_ref(), + ServiceError::TransportClosed + | ServiceError::TransportSend(_) + | ServiceError::Timeout { .. } + | ServiceError::SubscriptionLagged { .. } + ), + // Streamable HTTP also represents request-scoped EOF using -32603. + EventsError::Remote(error) => error.code == ErrorCode::INTERNAL_ERROR, + _ => false, + } +} + +fn retry_delay(attempt: u8, minimum: u64) -> Duration { + let ceiling = (250u64 << attempt.min(5)).max(minimum); + let jitter = RandomState::new().hash_one(ceiling) % ceiling; + Duration::from_millis(ceiling + jitter) +} + +fn delay(ms: u64) -> Duration { + Duration::from_millis(ms.min(u64::from(u32::MAX))) +} + +fn deadline(ms: u64) -> Instant { + Instant::now() + delay(ms) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(feature = "server")] + mod backpressure { + use tokio::sync::oneshot; + use tokio_util::sync::CancellationToken; + + use super::*; + use crate::{ + ClientLifecycleMode, ClientServiceExt, RoleClient, ServerHandler, ServiceExt, + events::server::{CheckedBatch, Descriptor, EventsServer}, + model::ClientConfig, + service::{RunningService, spawn_service_task}, + }; + + struct App(EventsServer); + + impl ServerHandler for App { + fn events(&self) -> Option<&EventsServer> { + Some(&self.0) + } + } + + async fn connect( + runtime: EventsServer, + ) -> ( + RunningService, + tokio::task::JoinHandle<()>, + ) { + let (server, client) = tokio::io::duplex(4096); + let server = spawn_service_task(async move { + App(runtime) + .serve(server) + .await + .unwrap() + .waiting() + .await + .unwrap(); + }); + let client = ClientConfig::default() + .serve_with_lifecycle( + client, + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28], + }, + ) + .await + .unwrap(); + (client, server) + } + + fn source() -> Descriptor { + Descriptor::typed::("source", "", [DeliveryMode::Push]) + } + + #[tokio::test(start_paused = true)] + async fn activation_deadline_with_full_queue() { + tokio::task::LocalSet::new().run_until(async { + let runtime = EventsServer::new(); + runtime.register_check(source(), |_, _, _| async { + panic!("queue was saturated before the push request opened"); + }).unwrap(); + let (client, server) = connect(runtime).await; + let api = EventsClient::new(client.peer().clone()); + let mut stream = api.subscribe("source", None, SubscriptionOptions::default()).await.unwrap(); + let reserved = client.reserve_outbound_capacity().await; + let start = Instant::now(); + assert!(matches!(stream.next().await, + Some(EventUpdate::RecoverableError(EventsError::Service(error))) + if matches!(*error, ServiceError::Timeout { timeout } if timeout == REQUEST_BUDGET))); + assert_eq!(start.elapsed(), REQUEST_BUDGET); + assert!(!client.has_subscription_channels()); + drop(stream); + drop(reserved); + tokio::time::timeout(Duration::from_secs(5), api.list_page(None)).await.unwrap().unwrap(); + client.cancel().await.unwrap(); + server.await.unwrap(); + }).await; + } + + #[tokio::test(start_paused = true)] + async fn dropping_active_stream_with_full_queue_cancels_source() { + tokio::task::LocalSet::new().run_until(async { + let runtime = EventsServer::new(); + let (entered, live) = oneshot::channel(); + let entered = std::sync::Mutex::new(Some(entered)); + let dropped = CancellationToken::new(); + let producer = dropped.clone(); + runtime.register_check(source(), move |_, _, query| { + let entered = (query.cursor.as_deref() == Some("head")) + .then(|| entered.lock().unwrap().take().unwrap()); + let producer = producer.clone(); + async move { + if let Some(entered) = entered { + let _guard = producer.drop_guard(); + entered.send(()).unwrap(); + std::future::pending().await + } else { + let mut page = CheckedBatch::new("head"); + page.has_more = true; + Ok(page) + } + } + }).unwrap(); + let (client, server) = connect(runtime).await; + let api = EventsClient::new(client.peer().clone()); + let options = SubscriptionOptions { cursor: Some("seed".into()), ..Default::default() }; + let mut stream = api.subscribe("source", None, options).await.unwrap(); + assert!(matches!(stream.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head")); + tokio::time::timeout(Duration::from_secs(5), live).await.unwrap().unwrap(); + let reserved = client.reserve_outbound_capacity().await; + drop(stream); + assert!(!client.has_subscription_channels()); + tokio::task::yield_now().await; + assert!(!dropped.is_cancelled()); + drop(reserved); + tokio::time::timeout(Duration::from_secs(5), dropped.cancelled()).await.unwrap(); + client.cancel().await.unwrap(); + server.await.unwrap(); + }).await; + } + } + + #[test] + fn jitter_stays_in_exponential_bounds() { + for minimum in [0, POLL_FLOOR_MS] { + for attempt in 0..=u8::MAX { + let base: u128 = (250u64 << attempt.min(5)).max(minimum).into(); + assert!((base..base * 2).contains(&(retry_delay(attempt, minimum).as_millis()))); + } + } + } + + #[test] + fn client_retries_internal_errors_but_not_invalid_or_unknown_rpc_errors() { + let error = |code| { + from_service(ServiceError::McpError(crate::ErrorData::new( + ErrorCode(code), + "fixture", + None, + ))) + }; + assert!(retryable(&error(-32603))); + for code in [-32023, -32024, -32026, -32602, -32601, -32099] { + assert!(!retryable(&error(code)), "incorrectly retried {code}"); + } + } +} diff --git a/crates/rmcp/src/events/client/webhook.rs b/crates/rmcp/src/events/client/webhook.rs new file mode 100644 index 000000000..9e9e790d7 --- /dev/null +++ b/crates/rmcp/src/events/client/webhook.rs @@ -0,0 +1,136 @@ +use super::*; +use crate::{ + events::webhook::{ + SUBSCRIBE, SubscribeDelivery, SubscribeMode, SubscribeParams, UNSUBSCRIBE, + UnsubscribeDelivery, UnsubscribeParams, WebhookOptions, WebhookSubscription, + }, + model::{JsonObject, ResultType}, +}; + +impl EventsClient { + /// Subscribe or refresh the same `(principal, url, name, arguments)` grant. + /// + /// Stage the secret at the endpoint before calling. Reuse the last safe + /// checkpoint and refresh before the returned deadline. This low-level + /// method does not run a receiver, schedule refreshes or persist cursors. + pub async fn subscribe_webhook( + &self, + name: impl Into, + arguments: Option, + options: WebhookOptions, + ) -> Result { + let params = SubscribeParams { + name: name.into(), + arguments, + delivery: SubscribeDelivery { + mode: SubscribeMode::Webhook, + url: options.url, + secret: options.secret.encode(), + }, + cursor: options.cursor, + max_age_ms: options.max_age_ms, + ttl_ms: options.ttl, + }; + decode_result( + self.webhook_request(SUBSCRIBE, ¶ms.name, ¶ms) + .await?, + ) + } + + /// End the webhook grant selected by the same key used to subscribe. + pub async fn unsubscribe_webhook( + &self, + name: impl Into, + arguments: Option, + url: impl Into, + ) -> Result<(), EventsError> { + let params = UnsubscribeParams { + name: name.into(), + arguments, + delivery: UnsubscribeDelivery { url: url.into() }, + }; + unsubscribe_result( + self.webhook_request(UNSUBSCRIBE, ¶ms.name, ¶ms) + .await?, + ) + } + + async fn webhook_request( + &self, + method: &'static str, + name: &str, + params: &impl Serialize, + ) -> Result { + self.require_advertisement()?; + let body = encode_params(params)?; + self.with_route(name, |descriptor| { + let body = body.clone(); + async move { + if method == SUBSCRIBE && !descriptor.delivery.contains(&DeliveryMode::Webhook) { + return Err(unsupported(DeliveryMode::Webhook)); + } + self.request(route(method, body, descriptor.input_schema)) + .await + } + }) + .await + } +} + +fn unsubscribe_result(result: ServerResult) -> Result<(), EventsError> { + #[derive(serde::Deserialize)] + struct Complete { + #[serde( + rename = "resultType", + default, + deserialize_with = "crate::events::wire::complete" + )] + _result_type: ResultType, + } + let value = match result { + ServerResult::EmptyResult(_) => return Ok(()), + ServerResult::CustomResult(result) => result.0, + result => serde_json::to_value(result).map_err(|_| EventsError::UnexpectedResponse)?, + }; + // Struct deserialization can also accept arrays; only Result objects are valid. + if !value.is_object() { + return Err(EventsError::UnexpectedResponse); + } + serde_json::from_value::(value) + .map(|_| ()) + .map_err(|_| EventsError::UnexpectedResponse) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_complete_result_objects() { + for wire in [ + json!({}), + json!({"_meta":{"hint":true}}), + json!({"resultType":"complete"}), + json!({"resultType":"complete", "_meta":{"hint":true}}), + json!({"resultType":"complete","extra":42}), + json!({"extra":42}), + json!({"action":"accept"}), + ] { + assert!(unsubscribe_result(serde_json::from_value(wire.clone()).unwrap()).is_ok()); + assert!( + unsubscribe_result(ServerResult::CustomResult(crate::model::CustomResult(wire))) + .is_ok() + ); + } + for wire in [json!({"resultType":"task"}), json!({"resultType":null})] { + let result: ServerResult = serde_json::from_value(wire.clone()).unwrap(); + assert!( + matches!( + unsubscribe_result(result.clone()), + Err(EventsError::UnexpectedResponse) + ), + "{wire}: {result:?}" + ); + } + } +} diff --git a/crates/rmcp/src/events/server.rs b/crates/rmcp/src/events/server.rs new file mode 100644 index 000000000..5f229e5ec --- /dev/null +++ b/crates/rmcp/src/events/server.rs @@ -0,0 +1,836 @@ +//! Register application event sources and serve the Events catalog, polls, and push streams. + +#[cfg(feature = "local")] +use std::rc::Rc as Shared; +#[cfg(not(feature = "local"))] +use std::sync::Arc as Shared; +use std::{ + collections::BTreeMap, + fmt, + future::Future, + io, + pin::Pin, + sync::{Mutex, MutexGuard}, +}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use tokio::sync::Notify; +use uuid::Uuid; + +use super::{ + EXTENSION, LIST, POLL, STREAM, + wire::{ + DEFAULT_POLL_MS, DeliveryMode, EventDescriptor, EventOccurrence, EventsError, + ListEventsResult, PollParams, PollResult, not_found, unsupported, + }, +}; +use crate::{ + RoleServer, + handler::server::common::{schema_for_output, schema_for_type}, + model::{CustomRequest, CustomResult, JsonObject, ResultType, ServerCapabilities}, + service::{MaybeSend, MaybeSendFuture, RequestContext, SubscriptionSink}, +}; + +mod emit; +mod push; +pub use emit::EmitHandle; +use emit::{EmitPage, Ring}; +#[cfg(feature = "events-webhook")] +pub use webhook::WebhookEgress; + +const MAX_BATCH: usize = 64; +const MAX_BATCH_BYTES: usize = 256 * 1024; + +macro_rules! hook { + ($name:ident = $($signature:tt)+) => { + #[cfg(not(feature = "local"))] + type $name = dyn $($signature)+ + Send + Sync; + #[cfg(feature = "local")] + type $name = dyn $($signature)+; + }; +} +hook!(ValidateArguments = Fn(&JsonObject) -> Result<(), EventsError>); +hook!(Authorize = Fn(RequestContext, JsonObject, DeliveryMode) -> HookFuture>); +hook!(Matches = Fn(&RequestContext, &EventOccurrence, &JsonObject) -> bool); +hook!(Check = Fn(RequestContext, JsonObject, CheckQuery) -> HookFuture>); +#[cfg(feature = "events-webhook")] +mod webhook; +#[cfg(not(feature = "local"))] +type HookFuture = Pin + Send>>; +#[cfg(feature = "local")] +type HookFuture = Pin>>; + +/// Server registration and policy for a wire [`EventDescriptor`]. +#[derive(Clone)] +pub struct Descriptor { + wire: EventDescriptor, + validate_arguments: Shared, + authorize: Option>, + matches: Option>, +} + +impl fmt::Debug for Descriptor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Descriptor") + .field("name", &self.wire.name) + .field("delivery", &self.wire.delivery) + .finish_non_exhaustive() + } +} + +impl Descriptor { + /// Generate argument and payload schemas and validate incoming arguments. + pub fn typed( + name: impl Into, + description: impl Into, + delivery: impl IntoIterator, + ) -> Self + where + Args: schemars::JsonSchema + DeserializeOwned + 'static, + Payload: schemars::JsonSchema + 'static, + { + Self { + wire: EventDescriptor::new( + name, + description, + delivery.into_iter().collect(), + schema_for_type::(), + schema_for_output::(), + ), + validate_arguments: Shared::new(|value| { + serde_json::from_value::(Value::Object(value.clone())) + .map(|_| ()) + .map_err(|_| invalid("argument schema validation failed")) + }), + authorize: None, + matches: None, + } + } + + /// Supply wire schemas and an argument validator. + pub fn raw( + descriptor: EventDescriptor, + validate_arguments: impl Fn(&JsonObject) -> Result<(), EventsError> + MaybeSend + 'static, + ) -> Self { + Self { + wire: descriptor, + validate_arguments: Shared::new(validate_arguments), + authorize: None, + matches: None, + } + } + + /// Check access before reading a source. Omitting the hook means allow-all. + pub fn authorize(mut self, authorize: F) -> Self + where + F: Fn(RequestContext, JsonObject, DeliveryMode) -> Fut + MaybeSend + 'static, + Fut: Future> + MaybeSendFuture + 'static, + { + self.authorize = Some(Shared::new(move |ctx, args, mode| { + Box::pin(authorize(ctx, args, mode)) + })); + self + } + + /// Filter occurrences from an emit source without changing their positions. + /// The hook borrows the request context, occurrence, and arguments. + pub fn matches( + mut self, + matches: impl Fn(&RequestContext, &EventOccurrence, &JsonObject) -> bool + + MaybeSend + + 'static, + ) -> Self { + self.matches = Some(Shared::new(matches)); + self + } + + fn validate_source(&self, source: &Source) -> Result<(), EventsError> { + if matches!(source, Source::Check(_)) && self.matches.is_some() { + return Err(invalid("matches requires an emit source")); + } + Ok(()) + } +} + +/// Classify a replacement; the SDK does not infer schema compatibility. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Replacement { + /// Existing arguments, cursors, and consumers remain compatible. + Additive, + /// Stop in-flight reads using the previous schema. + Breaking, +} + +/// Bounded read requested from a replay source. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct CheckQuery { + /// Position to resume strictly after; `None` means return an empty batch at the current head. + pub cursor: Option, + /// Earliest eligible timestamp during age-limited replay. + pub age_floor: Option>, + /// Maximum number of items to return. + pub max_events: usize, + /// Maximum compact JSON bytes in a batch. + pub max_bytes: usize, +} + +/// A bounded ordered read with source-owned, durable positions. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct CheckedBatch { + /// Only on a gap: a fresh replay position before the first eligible item. + /// The SDK returns an empty truncated page at this position. + pub start: Option, + /// Occurrences in order, with optional replay cursors after each item. + pub events: Vec, + /// End of scan, not necessarily the position of the last event. + pub end: String, + /// Whether more source work remains after `end`. + pub has_more: bool, + /// Suggested delay in milliseconds once the caller drains the backlog. + pub next_poll_ms: Option, +} + +impl CheckedBatch { + /// Create an empty, untruncated batch ending at a source-issued cursor. + pub fn new(end: impl Into) -> Self { + Self { + start: None, + events: Vec::new(), + end: end.into(), + has_more: false, + next_poll_ms: None, + } + } +} + +/// Catalog and event sources shared by server handlers. +/// +/// Active push streams may close without a final result when the service shuts down. +#[derive(Clone)] +pub struct EventsServer(Shared); + +impl fmt::Debug for EventsServer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EventsServer").finish_non_exhaustive() + } +} + +struct Registry { + epoch: Uuid, + state: Mutex, + changes: Notify, + #[cfg(feature = "events-webhook")] + webhooks: Option>, +} + +#[derive(Default)] +struct State { + revision: u64, + entries: BTreeMap, +} + +struct Entry { + descriptor: Shared, + registration: u64, + generation: u64, + input_generation: u64, + source: Source, + emitted: Option>, +} + +enum Source { + Check(Shared), + Emit(Ring), +} + +enum Read { + Check(Shared), + Emit(EmitPage), +} + +fn invalid(reason: impl Into) -> EventsError { + EventsError::InvalidParams(reason.into()) +} + +fn limit(name: &str, max: usize) -> EventsError { + EventsError::ResourceExhausted { + limit: name.into(), + max: Some(max as u64), + } +} + +fn schema_changed(input_changed: bool) -> EventsError { + EventsError::Unsupported { + feature: if input_changed { + "inputSchema" + } else { + "payloadSchema" + } + .into(), + value: None, + reason: Some("schema_changed".into()), + } +} + +impl Registry { + fn state(&self) -> MutexGuard<'_, State> { + self.state.lock().expect("Events registry lock poisoned") + } + + fn changed(&self, state: &mut State) { + state.revision += 1; + self.changes.notify_waiters(); + } +} + +impl Default for EventsServer { + fn default() -> Self { + Self::new() + } +} + +impl EventsServer { + /// Create a shared runtime with a mutable catalog and list notifications. + pub fn new() -> Self { + Self(Shared::new(Registry { + epoch: Uuid::new_v4(), + state: Mutex::new(State::default()), + changes: Notify::new(), + #[cfg(feature = "events-webhook")] + webhooks: None, + })) + } + + /// Register a source that supplies its own cursors and honors the query bounds. + /// Return the current head for a null cursor. + pub fn register_check( + &self, + descriptor: Descriptor, + check: F, + ) -> Result<(), EventsError> + where + F: Fn(RequestContext, JsonObject, CheckQuery) -> Fut + MaybeSend + 'static, + Fut: Future> + MaybeSendFuture + 'static, + { + self.insert( + descriptor, + Source::Check(Shared::new(move |ctx, args, query| { + Box::pin(check(ctx, args, query)) + })), + )?; + Ok(()) + } + + fn insert(&self, descriptor: Descriptor, source: Source) -> Result { + validate_enabled_descriptor(&descriptor, self.webhooks_enabled())?; + descriptor.validate_source(&source)?; + let mut state = self.0.state(); + if state.entries.contains_key(&descriptor.wire.name) { + return Err(invalid("duplicate event name")); + } + let generation = state.revision + 1; + let emitted = (matches!(&source, Source::Emit(_)) && self.notifies_emits(&descriptor)) + .then(|| Shared::new(Notify::new())); + state.entries.insert( + descriptor.wire.name.clone(), + Entry { + descriptor: Shared::new(descriptor), + registration: generation, + generation, + input_generation: generation, + source, + emitted, + }, + ); + self.0.changed(&mut state); + Ok(generation) + } + + /// Replace a descriptor. Breaking changes end subscriptions and reset emit history. + pub fn replace(&self, descriptor: Descriptor, change: Replacement) -> Result<(), EventsError> { + validate_enabled_descriptor(&descriptor, self.webhooks_enabled())?; + let mut state = self.0.state(); + let generation = state.revision + 1; + let entry = state + .entries + .get_mut(&descriptor.wire.name) + .ok_or_else(not_found)?; + descriptor.validate_source(&entry.source)?; + if change == Replacement::Breaking { + if entry.descriptor.wire.input_schema != descriptor.wire.input_schema { + entry.input_generation = generation; + } + entry.generation = generation; + if let Source::Emit(ring) = &mut entry.source { + *ring = Ring::default(); + } + } + if self.notifies_emits(&descriptor) && matches!(&entry.source, Source::Emit(_)) { + entry + .emitted + .get_or_insert_with(|| Shared::new(Notify::new())); + } + let previous = std::mem::replace(&mut entry.descriptor, Shared::new(descriptor)); + self.0.changed(&mut state); + drop(state); + drop(previous); + Ok(()) + } + + /// Remove an event type and terminate its subscriptions. + pub fn remove(&self, name: &str) -> Result<(), EventsError> { + let mut state = self.0.state(); + let removed = state.entries.remove(name).ok_or_else(not_found)?; + self.0.changed(&mut state); + drop(state); + drop(removed); + Ok(()) + } + + pub(crate) fn revision(&self) -> u64 { + self.0.state().revision + } + + pub(crate) async fn notify(&self, mut revision: u64, sink: SubscriptionSink) { + loop { + // Register before inspecting the revision to avoid missing a wake-up. + let changed = self.0.changes.notified(); + let next = self.revision(); + if next == revision { + changed.await; + continue; + } + revision = next; + if sink.notify_events_list_changed().await.is_err() { + break; + } + } + } + + fn list(&self, params: Option) -> Result { + #[derive(Deserialize, Default)] + struct ListParams { + cursor: Option, + } + let params = params + .map(serde_json::from_value::) + .transpose() + .map_err(|_| invalid("invalid catalog parameters"))? + .unwrap_or_default(); + let state = self.0.state(); + if params.cursor.is_some() { + return Err(invalid("invalid catalog cursor")); + } + let events = state + .entries + .values() + .map(|entry| { + let mut wire = entry.descriptor.wire.clone(); + wire.delivery.retain(|mode| match mode { + DeliveryMode::Webhook => self.webhooks_enabled(), + _ => true, + }); + wire + }) + .collect(); + Ok(ListEventsResult { + result_type: ResultType::COMPLETE, + events, + next_cursor: None, + meta: None, + }) + } + + pub(crate) async fn dispatch( + &self, + request: CustomRequest, + context: RequestContext, + ) -> Result { + let method = request.method.as_str(); + if method == LIST { + return encode(self.list(request.params)?); + } + if !super::named_method(method) { + return Err(EventsError::MethodNotFound); + } + let ct = context.ct.clone(); + tokio::select! { + biased; + () = ct.cancelled() => Err(source_error("Events request cancelled")), + result = self.dispatch_named(method, request.params, context) => result, + } + } + + async fn dispatch_named( + &self, + method: &str, + params: Option, + context: RequestContext, + ) -> Result { + let raw = params.ok_or_else(|| invalid("missing event parameters"))?; + let name = raw + .get("name") + .and_then(Value::as_str) + .ok_or_else(|| invalid("missing event name"))?; + let registered = self.0.state().entries.get(name).map(|entry| { + ( + entry.descriptor.clone(), + entry.registration, + entry.generation, + ) + }); + #[cfg(all(feature = "transport-streamable-http-server", not(feature = "local")))] + validate_event_routing( + &context, + method, + &raw, + name, + registered + .as_ref() + .map(|(descriptor, _, _)| descriptor.wire.input_schema.as_ref()), + )?; + #[cfg(feature = "events-webhook")] + if matches!( + method, + super::webhook::SUBSCRIBE | super::webhook::UNSUBSCRIBE + ) && let Some(dispatcher) = &self.0.webhooks + { + let principal = dispatcher.principal(&context)?; + return self + .dispatch_webhook(method, raw, context, principal, registered) + .await; + } + let (descriptor, registration, generation) = registered.ok_or_else(not_found)?; + if method == STREAM { + let params = + serde_json::from_value(raw).map_err(|_| invalid("invalid stream parameters"))?; + return self + .stream(params, context, descriptor, registration, generation) + .await; + } + if method != POLL { + return Err(unsupported(DeliveryMode::Webhook)); + } + if !descriptor.wire.delivery.contains(&DeliveryMode::Poll) { + return Err(unsupported(DeliveryMode::Poll)); + } + let params = serde_json::from_value(raw).map_err(|_| invalid("invalid poll parameters"))?; + encode(self.poll(params, context, descriptor).await?) + } + + fn webhooks_enabled(&self) -> bool { + #[cfg(feature = "events-webhook")] + { + self.0.webhooks.is_some() + } + #[cfg(not(feature = "events-webhook"))] + { + false + } + } + + fn notifies_emits(&self, descriptor: &Descriptor) -> bool { + let delivery = &descriptor.wire.delivery; + delivery.contains(&DeliveryMode::Push) + || (self.webhooks_enabled() && delivery.contains(&DeliveryMode::Webhook)) + } + + async fn poll( + &self, + params: PollParams, + context: RequestContext, + descriptor: Shared, + ) -> Result { + let max_events = params + .max_events + .unwrap_or(MAX_BATCH as u64) + .min(MAX_BATCH as u64) as usize; + if max_events == 0 { + return Err(invalid("maxEvents must be positive")); + } + let floor = age_floor(params.cursor.as_deref(), params.max_age_ms); + let args = params.arguments.unwrap_or_default(); + (descriptor.validate_arguments)(&args)?; + if let Some(authorize) = &descriptor.authorize { + authorize(context.clone(), args.clone(), DeliveryMode::Poll).await?; + } + let query = CheckQuery { + cursor: params.cursor, + age_floor: floor, + max_events, + max_bytes: MAX_BATCH_BYTES, + }; + let (current, read) = { + let mut state = self.0.state(); + let entry = state.entries.get_mut(¶ms.name).ok_or_else(not_found)?; + let read = match &mut entry.source { + Source::Check(check) => Read::Check(check.clone()), + Source::Emit(ring) => Read::Emit(ring.read( + self.0.epoch, + entry.registration, + entry.generation, + &query, + )), + }; + (entry.descriptor.clone(), read) + }; + if !Shared::ptr_eq(¤t, &descriptor) { + (current.validate_arguments)(&args)?; + if let Some(authorize) = ¤t.authorize { + authorize(context.clone(), args.clone(), DeliveryMode::Poll).await?; + } + } + let check = match read { + Read::Check(check) => check, + Read::Emit(page) => return Ok(page.finish(&context, &args, ¤t, false)), + }; + let batch = check(context, args, query.clone()).await?; + checked_result(batch, &query, false) + } +} + +pub(crate) fn set_advertisement( + events: Option<&EventsServer>, + capabilities: &mut ServerCapabilities, + modern: bool, +) { + if events.is_none() { + return; + } + if modern { + capabilities.extensions.get_or_insert_default().insert( + EXTENSION.into(), + JsonObject::from_iter([("listChanged".into(), json!(true))]), + ); + } else if let Some(extensions) = &mut capabilities.extensions { + extensions.remove(EXTENSION); + if extensions.is_empty() { + capabilities.extensions = None; + } + } +} + +#[cfg(all(feature = "transport-streamable-http-server", not(feature = "local")))] +fn validate_event_routing( + context: &RequestContext, + method: &str, + params: &Value, + name: &str, + schema: Option<&JsonObject>, +) -> Result<(), EventsError> { + if let Some(parts) = context.extensions.get::() { + crate::transport::common::mcp_headers::validate_routing_headers( + &parts.headers, + method, + Some(params), + Some(name), + schema, + ) + .map_err(EventsError::HeaderMismatch)?; + } + Ok(()) +} + +fn ensure_current(entry: &Entry, registration: u64, generation: u64) -> Result<(), EventsError> { + if entry.registration != registration { + Err(not_found()) + } else if entry.generation != generation { + Err(schema_changed(entry.input_generation > generation)) + } else { + Ok(()) + } +} + +#[cfg(test)] +fn validate_descriptor(descriptor: &Descriptor) -> Result<(), EventsError> { + validate_enabled_descriptor(descriptor, false) +} + +fn validate_enabled_descriptor( + descriptor: &Descriptor, + webhooks_enabled: bool, +) -> Result<(), EventsError> { + if descriptor.wire.name.is_empty() { + return Err(invalid("empty event name")); + } + if !descriptor.wire.delivery.iter().any(|mode| match mode { + DeliveryMode::Webhook => webhooks_enabled, + _ => true, + }) { + return Err(EventsError::Unsupported { + feature: "deliveryMode".into(), + value: Some(json!(descriptor.wire.delivery)), + reason: Some("this source requires an enabled delivery mode".into()), + }); + } + crate::transport::common::mcp_headers::validate_param_header_annotations( + &descriptor.wire.input_schema, + ) + .map_err(EventsError::InvalidParams) +} + +fn encode(result: impl Serialize) -> Result { + serde_json::to_value(result) + .map(CustomResult) + .map_err(|_| source_error("could not encode Events result")) +} + +fn source_error(message: &'static str) -> EventsError { + EventsError::Remote(Box::new(crate::ErrorData::internal_error(message, None))) +} + +fn age_floor(cursor: Option<&str>, max_age_ms: Option) -> Option> { + cursor + .and(max_age_ms) + .and_then(|age| i64::try_from(age).ok()) + .and_then(chrono::TimeDelta::try_milliseconds) + .and_then(|age| Utc::now().checked_sub_signed(age)) +} + +// None means the occurrence cannot fit the poll byte budget. +fn event_bytes(event: &EventOccurrence) -> Result, EventsError> { + struct Counter { + bytes: usize, + overflow: bool, + } + impl io::Write for Counter { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.len() > MAX_BATCH_BYTES - self.bytes { + self.overflow = true; + return Err(io::Error::other("event too large")); + } + self.bytes += buf.len(); + Ok(buf.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let mut counter = Counter { + bytes: 0, + overflow: false, + }; + match serde_json::to_writer(&mut counter, event) { + Ok(()) => Ok(Some(counter.bytes)), + Err(_) if counter.overflow => Ok(None), + Err(_) => Err(source_error("invalid occurrence")), + } +} + +fn checked_result( + mut batch: CheckedBatch, + query: &CheckQuery, + item_cursors: bool, +) -> Result { + let next = batch.next_poll_ms.unwrap_or(DEFAULT_POLL_MS); + if query.cursor.is_none() { + return Ok(poll_result(Vec::new(), batch.end, false, false, next)); + } + if let Some(start) = batch.start { + let more = batch.has_more || start != batch.end; + return Ok(poll_result(Vec::new(), start, true, more, next)); + } + let mut bytes = 0; + let mut cut = None; + for (index, event) in batch.events.iter().enumerate() { + let size = event_bytes(event)?.unwrap_or(usize::MAX); + if index == query.max_events || size > query.max_bytes - bytes { + let (keep, cursor) = cut + .filter(|(_, cursor)| query.cursor.as_ref() != Some(cursor) && *cursor != batch.end) + .ok_or_else(|| limit("pollBytes", query.max_bytes))?; + batch.events.truncate(keep); + batch.end = cursor; + batch.has_more = true; + break; + } + bytes += size; + if let Some(cursor) = &event.cursor { + cut = Some((index + 1, cursor.clone())); + } + } + if !item_cursors { + for event in &mut batch.events { + event.cursor = None; + } + } + Ok(poll_result( + batch.events, + batch.end, + false, + batch.has_more, + next, + )) +} + +fn poll_result( + events: Vec, + cursor: String, + truncated: bool, + has_more: bool, + next_poll_ms: u64, +) -> PollResult { + PollResult { + result_type: ResultType::COMPLETE, + events, + cursor: Some(cursor), + truncated, + has_more, + next_poll_ms, + meta: None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncated_check_page_exposes_safe_start_before_events() { + let mut query = CheckQuery { + cursor: Some("old".into()), + age_floor: None, + max_events: 1, + max_bytes: MAX_BATCH_BYTES, + }; + let mut batch = CheckedBatch::new("end"); + batch.start = Some("gap".into()); + batch.events.push(EventOccurrence::new( + "id", + "sample", + Utc::now(), + JsonObject::new(), + )); + let result = checked_result(batch.clone(), &query, false).unwrap(); + assert!(result.truncated && result.has_more); + assert!(result.events.is_empty()); + assert_eq!(result.cursor.as_deref(), Some("gap")); + query.cursor = None; + let result = checked_result(batch, &query, false).unwrap(); + assert!(!result.truncated && !result.has_more && result.events.is_empty()); + assert_eq!(result.cursor.as_deref(), Some("end")); + } + + #[test] + fn rejects_invalid_annotations_without_http() { + let schema = json!({"properties":{"x":{"type":"string","x-mcp-header":"not a token"}}}); + let descriptor = Descriptor::raw( + EventDescriptor::new( + "sample", + "", + vec![DeliveryMode::Poll], + schema.as_object().unwrap().clone().into(), + Default::default(), + ), + |_| Ok(()), + ); + assert!(matches!( + validate_descriptor(&descriptor), + Err(EventsError::InvalidParams(_)) + )); + } +} diff --git a/crates/rmcp/src/events/server/emit.rs b/crates/rmcp/src/events/server/emit.rs new file mode 100644 index 000000000..a58455110 --- /dev/null +++ b/crates/rmcp/src/events/server/emit.rs @@ -0,0 +1,264 @@ +#[cfg(feature = "local")] +use std::rc::Weak; +#[cfg(not(feature = "local"))] +use std::sync::Weak; +use std::{collections::VecDeque, fmt, sync::Arc, time::Duration}; + +use chrono::{DateTime, Utc}; +use tokio::time::Instant; +use uuid::Uuid; + +use super::{ + CheckQuery, DEFAULT_POLL_MS, Descriptor, EventOccurrence, EventsError, EventsServer, + JsonObject, MAX_BATCH_BYTES, PollResult, Registry, RequestContext, RoleServer, Shared, Source, + event_bytes, limit, not_found, poll_result, +}; + +const MAX_RECORDS: usize = 256; +const RETENTION: Duration = Duration::from_secs(3600); + +/// Producer for a bounded emit source. The producer becomes invalid if the +/// registration is removed, even if the same name is registered again. +#[derive(Clone)] +pub struct EmitHandle { + registry: Weak, + name: String, + registration: u64, +} + +impl fmt::Debug for EmitHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EmitHandle") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + +impl EventsServer { + /// Register a process-local ring limited to 256 events, 256 KiB, and one hour. + pub fn register_emit(&self, descriptor: Descriptor) -> Result { + let name = descriptor.wire.name.clone(); + let registration = self.insert(descriptor, Source::Emit(Ring::default()))?; + Ok(EmitHandle { + registry: Shared::downgrade(&self.0), + name, + registration, + }) + } +} + +impl EmitHandle { + /// Append an occurrence using a supplied stable upstream ID or a generated + /// ID when the upstream has none. + pub fn emit( + &self, + event_id: Option, + timestamp: DateTime, + data: JsonObject, + ) -> Result<(), EventsError> { + let registry = self.registry.upgrade().ok_or_else(not_found)?; + let id = event_id.unwrap_or_else(|| Uuid::new_v4().to_string()); + let event = EventOccurrence::new(id, &self.name, timestamp, data); + let bytes = event_bytes(&event)?.ok_or_else(|| limit("eventBytes", MAX_BATCH_BYTES))?; + let mut state = registry.state(); + let entry = state + .entries + .get_mut(&self.name) + .filter(|entry| entry.registration == self.registration) + .ok_or_else(not_found)?; + let Source::Emit(ring) = &mut entry.source else { + return Err(not_found()); + }; + ring.append(event, bytes); + if let Some(emitted) = &entry.emitted { + emitted.notify_waiters(); + } + Ok(()) + } +} + +#[derive(Default)] +pub(super) struct Ring { + records: VecDeque, + head: u64, + bytes: usize, +} + +struct Record { + position: u64, + inserted: Instant, + bytes: usize, + event: Arc, +} + +impl Ring { + fn evict_front(&mut self) { + if let Some(record) = self.records.pop_front() { + self.bytes -= record.bytes; + } + } + + fn prune(&mut self, now: Instant) { + while self + .records + .front() + .is_some_and(|record| now.duration_since(record.inserted) >= RETENTION) + { + self.evict_front(); + } + } + + fn append(&mut self, event: EventOccurrence, bytes: usize) { + let position = self.head + 1; + let inserted = Instant::now(); + self.prune(inserted); + while self.records.len() >= MAX_RECORDS || self.bytes + bytes > MAX_BATCH_BYTES { + self.evict_front(); + } + self.head = position; + self.bytes += bytes; + self.records.push_back(Record { + position, + inserted, + bytes, + event: Arc::new(event), + }); + } + + pub(super) fn read( + &mut self, + epoch: Uuid, + registration: u64, + generation: u64, + query: &CheckQuery, + ) -> EmitPage { + self.prune(Instant::now()); + let scope = format!("{epoch}:{registration}:{generation}:"); + let boundary = self + .records + .front() + .map_or(self.head, |record| record.position - 1); + let mut page = EmitPage { + scope, + position: self.head, + records: Vec::new(), + truncated: false, + has_more: false, + }; + let Some(cursor) = query.cursor.as_deref() else { + return page; + }; + let position = cursor + .strip_prefix(&page.scope) + .and_then(|pos| pos.parse::().ok()); + page.truncated = position.is_none_or(|pos| pos < boundary || pos > self.head); + page.position = position + .filter(|pos| *pos >= boundary && *pos <= self.head) + .unwrap_or(boundary); + let old = |record: &Record| { + query + .age_floor + .is_some_and(|floor| record.event.timestamp < floor) + }; + let start = page.position; + let mut remaining = self + .records + .iter() + .skip_while(|record| record.position <= start) + .peekable(); + while remaining.peek().is_some_and(|record| old(record)) { + if let Some(record) = remaining.next() { + page.position = record.position; + page.truncated = true; + } + } + if !page.truncated { + while let Some(record) = remaining.peek() { + if page.records.len() == query.max_events || old(record) { + break; + } + page.records.push((record.position, record.event.clone())); + remaining.next(); + } + } + page.has_more = remaining.peek().is_some(); + page + } +} + +pub(super) struct EmitPage { + scope: String, + position: u64, + records: Vec<(u64, Arc)>, + truncated: bool, + has_more: bool, +} + +impl EmitPage { + pub(super) fn finish( + self, + context: &RequestContext, + args: &JsonObject, + descriptor: &Descriptor, + item_cursors: bool, + ) -> PollResult { + let Self { + scope, + mut position, + records, + truncated, + has_more, + } = self; + let mut events = Vec::new(); + for (next, event) in records { + if descriptor + .matches + .as_ref() + .is_some_and(|matches| !matches(context, &event, args)) + { + position = next; + continue; + } + let mut event = (*event).clone(); + position = next; + if item_cursors { + event.cursor = Some(format!("{scope}{position}")); + } + events.push(event); + } + poll_result( + events, + format!("{scope}{position}"), + truncated, + has_more, + DEFAULT_POLL_MS, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test(start_paused = true)] + async fn empty_age_eviction_and_foreign_or_future_cursor_reset_once() { + let mut ring = Ring::default(); + let epoch = Uuid::new_v4(); + let mut query = CheckQuery { + cursor: Some(format!("{epoch}:1:1:0")), + age_floor: None, + max_events: 1, + max_bytes: MAX_BATCH_BYTES, + }; + let event = EventOccurrence::new("id", "event", Utc::now(), JsonObject::new()); + ring.append(event.clone(), event_bytes(&event).unwrap().unwrap()); + tokio::time::advance(RETENTION).await; + let gap = ring.read(epoch, 1, 1, &query); + assert!(gap.truncated && !gap.has_more && gap.records.is_empty()); + query.cursor = Some(format!("{}{}", gap.scope, gap.position)); + assert!(!ring.read(epoch, 1, 1, &query).truncated); + assert!(ring.read(Uuid::new_v4(), 1, 1, &query).truncated); + query.cursor = Some(format!("{epoch}:1:1:99999999")); + assert!(ring.read(epoch, 1, 1, &query).truncated); + } +} diff --git a/crates/rmcp/src/events/server/push.rs b/crates/rmcp/src/events/server/push.rs new file mode 100644 index 000000000..e698092e2 --- /dev/null +++ b/crates/rmcp/src/events/server/push.rs @@ -0,0 +1,398 @@ +use std::{pin::pin, time::Duration}; + +use tokio::time::{Instant, sleep_until, timeout}; + +use super::{super::wire::terminal, *}; +use crate::{ + events::{ACTIVE, ERROR, EVENT, HEARTBEAT, StreamParams, TERMINATED}, + model::{CustomNotification, GetMeta, ServerNotification, SubscriptionsListenResult}, +}; + +const ACTIVATION_BUDGET: Duration = Duration::from_secs(10); +const MIN_HEARTBEAT_MS: u64 = 1_000; +const MAX_HEARTBEAT_MS: u64 = 30_000; +const AUTHORIZE_INTERVAL: Duration = Duration::from_secs(30); + +struct Push<'a> { + server: &'a EventsServer, + context: RequestContext, + name: String, + args: JsonObject, + registration: u64, + generation: u64, + query: CheckQuery, + heartbeat_ms: u64, + last_frame: Instant, +} + +#[derive(Default)] +struct Authorization { + grant: Option<(Shared, Instant)>, + idle_retry_at: Option, +} + +impl EventsServer { + pub(super) async fn stream( + &self, + params: StreamParams, + context: RequestContext, + descriptor: Shared, + registration: u64, + generation: u64, + ) -> Result { + if !descriptor.wire.delivery.contains(&DeliveryMode::Push) { + return Err(unsupported(DeliveryMode::Push)); + } + let mut push = Push { + server: self, + name: params.name, + args: params.arguments.unwrap_or_default(), + registration, + generation, + query: CheckQuery { + age_floor: age_floor(params.cursor.as_deref(), params.max_age_ms), + cursor: params.cursor, + max_events: MAX_BATCH, + max_bytes: MAX_BATCH_BYTES, + }, + context, + heartbeat_ms: params + .heartbeat_ms + .unwrap_or(MAX_HEARTBEAT_MS) + .clamp(MIN_HEARTBEAT_MS, MAX_HEARTBEAT_MS), + last_frame: Instant::now(), + }; + push.run().await + } +} + +impl Push<'_> { + async fn run(&mut self) -> Result { + let (emitted, mut descriptor) = { + let state = self.server.0.state(); + let entry = state.entries.get(&self.name).ok_or_else(not_found)?; + ensure_current(entry, self.registration, self.generation)?; + (entry.emitted.clone(), entry.descriptor.clone()) + }; + // Arm before the head snapshot: append can race any read or write. + let mut wake = emitted.as_ref().map(|emitted| emitted.notified()); + let mut authorization = Authorization::default(); + let mut page = timeout(ACTIVATION_BUDGET, self.read(true, &mut authorization)) + .await + .map_err(|_| source_error("event stream activation timed out"))??; + let active_cursor = if page.truncated || page.events.is_empty() { + page.cursor.clone() + } else { + self.query.cursor.clone() + }; + self.active(active_cursor, page.truncated).await?; + + loop { + page.has_more &= page.cursor != self.query.cursor; + if let Err(error) = self.deliver(&mut page).await { + if terminal(&error) { + return self.finish(error).await; + } + return Err(error); + } + // A quiet, immediately draining backlog must not starve the clock. + if Instant::now() >= self.heartbeat_at(self.last_frame) { + self.send(HEARTBEAT, json!({"cursor": self.query.cursor})) + .await?; + } + if !page.has_more { + self.query.age_floor = None; + let at = emitted + .is_none() + .then(|| Instant::now() + check_delay(page.next_poll_ms)); + match self + .wait(wake.take(), at, &descriptor, &mut authorization) + .await + { + Ok(()) => {} + Err(error) if terminal(&error) => return self.finish(error).await, + Err(error) => return Err(error), + } + } + loop { + wake = emitted.as_ref().map(|emitted| emitted.notified()); + match self.current() { + Ok(current) => descriptor = current, + Err(error) => return self.finish(error).await, + } + match self.read_live(&mut authorization).await { + Ok(next) => { + page = next; + if page.truncated { + self.active(page.cursor.clone(), true).await?; + } + break; + } + Err(error) if terminal(&error) => return self.finish(error).await, + Err(error) => { + self.problem(ERROR, error).await?; + let retry = Instant::now() + check_delay(page.next_poll_ms); + if let Err(error) = self + .wait(None, Some(retry), &descriptor, &mut authorization) + .await + { + return self.finish(error).await; + } + } + } + } + } + } + + fn current(&self) -> Result, EventsError> { + let state = self.server.0.state(); + let entry = state.entries.get(&self.name).ok_or_else(not_found)?; + ensure_current(entry, self.registration, self.generation)?; + Ok(entry.descriptor.clone()) + } + + async fn authorize( + &self, + descriptor: &Shared, + authorization: &mut Authorization, + ) -> Result<(), EventsError> { + let grant = authorization.grant.as_ref(); + let same = grant.is_some_and(|(previous, _)| Shared::ptr_eq(previous, descriptor)); + if same && grant.is_some_and(|(_, until)| Instant::now() < *until) { + return Ok(()); + } + if !same { + (descriptor.validate_arguments)(&self.args)?; + } + if let Some(authorize) = &descriptor.authorize { + authorize(self.context.clone(), self.args.clone(), DeliveryMode::Push).await?; + } + authorization.grant = Some((descriptor.clone(), Instant::now() + AUTHORIZE_INTERVAL)); + authorization.idle_retry_at = None; + Ok(()) + } + + async fn read( + &self, + activating: bool, + authorization: &mut Authorization, + ) -> Result { + let registry = &self.server.0; + loop { + let mut changed = pin!(registry.changes.notified()); + let descriptor = self.current()?; + if activating && !descriptor.wire.delivery.contains(&DeliveryMode::Push) { + return Err(unsupported(DeliveryMode::Push)); + } + let read = async { + self.authorize(&descriptor, authorization).await?; + let source = { + let mut state = registry.state(); + let entry = state.entries.get_mut(&self.name).ok_or_else(not_found)?; + ensure_current(entry, self.registration, self.generation)?; + match &mut entry.source { + Source::Check(check) => Read::Check(check.clone()), + Source::Emit(ring) => Read::Emit(ring.read( + registry.epoch, + entry.registration, + entry.generation, + &self.query, + )), + } + }; + match source { + Read::Emit(page) => { + Ok(page.finish(&self.context, &self.args, &descriptor, true)) + } + Read::Check(check) => { + let batch = + check(self.context.clone(), self.args.clone(), self.query.clone()) + .await?; + checked_result(batch, &self.query, true) + } + } + }; + tokio::pin!(read); + loop { + tokio::select! { + biased; + () = &mut changed => { + changed.set(registry.changes.notified()); + if !Shared::ptr_eq(&self.current()?, &descriptor) { + break; + } + } + result = &mut read => { + if Shared::ptr_eq(&self.current()?, &descriptor) { + return result; + } + break; + } + } + } + } + } + + async fn read_live( + &mut self, + authorization: &mut Authorization, + ) -> Result { + let (last_frame, result) = self + .heartbeat_while(self.read(false, authorization)) + .await?; + self.last_frame = last_frame; + result + } + + fn heartbeat_at(&self, last_frame: Instant) -> Instant { + last_frame + Duration::from_millis(self.heartbeat_ms) + } + + async fn heartbeat_while( + &self, + work: impl Future, + ) -> Result<(Instant, T), EventsError> { + let mut last_frame = self.last_frame; + let mut work = pin!(work); + loop { + tokio::select! { + biased; + result = &mut work => return Ok((last_frame, result)), + () = sleep_until(self.heartbeat_at(last_frame)) => { + self.write(HEARTBEAT, json!({"cursor": self.query.cursor})).await?; + last_frame = Instant::now(); + } + } + } + } + + async fn wait( + &mut self, + emitted: Option>, + wake_at: Option, + read_descriptor: &Shared, + authorization: &mut Authorization, + ) -> Result<(), EventsError> { + let registry = &self.server.0; + let mut emitted = pin!(emitted); + loop { + let mut changed = pin!(registry.changes.notified()); + let descriptor = self.current()?; + if !Shared::ptr_eq(read_descriptor, &descriptor) { + return Ok(()); + } + let heartbeat_at = self.heartbeat_at(self.last_frame); + let authorize_at = authorization + .idle_retry_at + .or_else(|| authorization.grant.as_ref().map(|(_, until)| *until)) + .unwrap_or_else(Instant::now); + tokio::select! { + () = &mut changed => continue, + () = async { + match emitted.as_mut().as_pin_mut() { + Some(emit) => emit.await, + None => std::future::pending().await, + } + } => return Ok(()), + () = async { + match wake_at { + Some(at) => sleep_until(at).await, + None => std::future::pending().await, + } + } => return Ok(()), + () = sleep_until(authorize_at), if descriptor.authorize.is_some() => { + let (last_frame, result) = tokio::select! { + () = &mut changed => { + return Ok(()); + } + result = self.heartbeat_while(self.authorize(&descriptor, authorization)) => result?, + }; + self.last_frame = last_frame; + if !Shared::ptr_eq(&self.current()?, read_descriptor) { + return Ok(()); + } + match result { + Ok(()) => {} + Err(error) if terminal(&error) => return Err(error), + Err(error) => { + self.problem(ERROR, error).await?; + authorization.idle_retry_at = Some(Instant::now() + AUTHORIZE_INTERVAL); + } + } + } + () = sleep_until(heartbeat_at) => { + self.send(HEARTBEAT, json!({"cursor": self.query.cursor})).await?; + } + } + } + } + + async fn deliver(&mut self, page: &mut PollResult) -> Result<(), EventsError> { + let mut events = std::mem::take(&mut page.events).into_iter().peekable(); + while let Some(mut event) = events.next() { + self.current()?; + event.cursor = if events.peek().is_none() { + page.cursor.clone() + } else { + event.cursor.or_else(|| self.query.cursor.clone()) + }; + let position = event.cursor.clone(); + self.send( + EVENT, + serde_json::to_value(event).map_err(|_| source_error("invalid occurrence"))?, + ) + .await?; + self.query.cursor = position; + } + self.query.cursor.clone_from(&page.cursor); + Ok(()) + } + + async fn active(&mut self, cursor: Option, truncated: bool) -> Result<(), EventsError> { + self.send( + ACTIVE, + json!({ + "cursor": cursor, "truncated": truncated, "heartbeatMs": self.heartbeat_ms + }), + ) + .await + } + + async fn finish(&mut self, error: EventsError) -> Result { + self.problem(TERMINATED, error).await?; + encode(SubscriptionsListenResult::complete(self.context.id.clone())) + } + + async fn problem(&mut self, method: &str, error: EventsError) -> Result<(), EventsError> { + self.send(method, json!({"error": crate::ErrorData::from(error)})) + .await + } + + async fn send(&mut self, method: &str, params: Value) -> Result<(), EventsError> { + self.write(method, params).await?; + self.last_frame = Instant::now(); + Ok(()) + } + + async fn write(&self, method: &str, mut params: Value) -> Result<(), EventsError> { + let metadata = params + .as_object_mut() + .and_then(|object| object.remove("_meta")); + let mut notification = CustomNotification::new(method, Some(params)); + if let Some(Value::Object(metadata)) = metadata { + notification.get_meta_mut().0.0.extend(metadata); + } + notification + .get_meta_mut() + .set_subscription_id(self.context.id.clone()); + self.context + .peer + .send_notification(ServerNotification::CustomNotification(notification)) + .await + .map_err(|_| source_error("event stream transport closed")) + } +} + +fn check_delay(ms: u64) -> Duration { + Duration::from_millis(ms.clamp(1_000, 86_400_000)) +} diff --git a/crates/rmcp/src/events/server/webhook.rs b/crates/rmcp/src/events/server/webhook.rs new file mode 100644 index 000000000..93ce8ff8d --- /dev/null +++ b/crates/rmcp/src/events/server/webhook.rs @@ -0,0 +1,965 @@ +use std::{ + collections::{HashMap, VecDeque}, + time::Duration, +}; + +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use bytes::Bytes; +use futures::{StreamExt, stream::FuturesUnordered}; +use reqwest::{StatusCode, Url}; +use tokio::time::{Instant, sleep_until, timeout_at}; +use tokio_util::sync::CancellationToken; + +use super::*; +use crate::{ + ErrorData, + events::webhook::{ + MAX_BODY, SUBSCRIBE, SubscribeParams, UnsubscribeParams, WebhookSecret, + WebhookSubscription, WebhookSubscriptionStatus, WebhookTtl, + }, + model::{ErrorCode, Extensions, ResultType}, + service::spawn_service_task, +}; + +mod egress; +mod key; +pub use egress::WebhookEgress; +use egress::{Egress, Reason, callback_url, echo}; +use key::Key; + +const RPC_BUDGET: Duration = Duration::from_secs(12); +const DEFAULT_TTL_MS: u64 = 30 * 60 * 1_000; +const MAX_TTL_MS: u64 = 60 * 60 * 1_000; +const ROTATION_GRACE: Duration = Duration::from_secs(60); +const AUTH_INTERVAL: Duration = Duration::from_secs(30); +const PROOF_TTL: Duration = Duration::from_secs(60 * 60); +const VERIFY_INTERVAL: Duration = Duration::from_secs(1); +const MAX_GRANTS: usize = 1024; +const MAX_PROOFS: usize = 4096; +const MAX_PENDING: usize = 4; +const MAX_ATTEMPTS: usize = 5; +const RETRY_WINDOW: Duration = Duration::from_secs(60); + +hook!(Principal = Fn(&Extensions) -> Option); + +pub(super) struct Dispatcher { + principal: Shared, + egress: Egress, + state: Mutex, +} + +#[derive(Default)] +struct DispatchState { + grants: HashMap>, + proofs: HashMap<(String, String), Instant>, + host_limit: HashMap>>, +} + +struct Grant { + id: String, + registration: u64, + generation: u64, + stop: CancellationToken, + changed: Notify, + policy_changed: Notify, + data: Mutex, +} + +struct GrantData { + lease: Instant, + refresh_before: DateTime, + context: RequestContext, + context_revision: u64, + permitted: Shared, + secret: WebhookSecret, + old_secret: Option<(Instant, WebhookSecret)>, + cursor: Option, + truncated: bool, + last_delivery: Option>, + error: Option, + termination: Option, +} + +type Registration = (Shared, u64, u64); + +fn lock(state: &Mutex) -> MutexGuard<'_, T> { + state.lock().expect("Events webhook lock poisoned") +} + +fn forbidden() -> EventsError { + EventsError::Forbidden { reason: None } +} + +fn missing_grant() -> EventsError { + EventsError::NotFound { + kind: Some("subscription".into()), + } +} + +fn callback_error(reason: Reason) -> EventsError { + EventsError::Remote(Box::new(ErrorData::new( + ErrorCode(-32027), + "webhook callback endpoint failed", + Some(json!({"reason": reason.category()})), + ))) +} + +fn random() -> String { + URL_SAFE_NO_PAD.encode(rand::random::<[u8; 24]>()) +} + +fn message_id(kind: Option<&str>) -> String { + let random = random(); + match kind { + Some(kind) => format!("msg_{kind}_{random}"), + None => format!("msg_{random}"), + } +} + +fn ttl(hint: WebhookTtl) -> Duration { + Duration::from_millis(match hint { + WebhookTtl::Default | WebhookTtl::NoExpiry => DEFAULT_TTL_MS, + WebhookTtl::Milliseconds(ms) => ms.clamp(1000, MAX_TTL_MS), + }) +} + +impl Dispatcher { + pub(super) fn principal( + &self, + context: &RequestContext, + ) -> Result { + (self.principal)(&context.extensions) + .filter(|principal| !principal.is_empty()) + .ok_or_else(forbidden) + } + + async fn consent( + &self, + key: (String, String), + url: &Url, + id: &str, + secret: &WebhookSecret, + deadline: Instant, + ) -> Result<(), EventsError> { + let host = url + .host_str() + .expect("validated host") + .trim_end_matches('.') + .to_owned(); + let slot = { + let now = Instant::now(); + let mut state = lock(&self.state); + state.proofs.retain(|_, expires| *expires > now); + if state.proofs.contains_key(&key) { + return Ok(()); + } + state.host_limit.retain(|_, slot| { + Shared::strong_count(slot) > 1 || slot.try_lock().is_ok_and(|next| *next > now) + }); + if let Some(slot) = state.host_limit.get(&host) { + slot.clone() + } else { + if state.host_limit.len() >= MAX_PROOFS { + return Err(limit("webhookVerificationHosts", MAX_PROOFS)); + } + let slot = Shared::new(tokio::sync::Mutex::new(now)); + state.host_limit.insert(host, slot.clone()); + slot + } + }; + let exhausted = || EventsError::ResourceExhausted { + limit: "webhookVerificationRate".into(), + max: None, + }; + let mut next = timeout_at(deadline, slot.lock()) + .await + .map_err(|_| exhausted())?; + if lock(&self.state) + .proofs + .get(&key) + .is_some_and(|expires| *expires > Instant::now()) + { + return Ok(()); + } + if *next >= deadline { + return Err(exhausted()); + } + sleep_until(*next).await; + if Instant::now() >= deadline { + return Err(exhausted()); + } + *next = Instant::now() + VERIFY_INTERVAL; + let nonce = random(); + let body = Bytes::from(json!({"type": "verification", "challenge": nonce}).to_string()); + let response = self + .egress + .post( + url, + id, + &message_id(Some("verification")), + body, + (secret, None), + ) + .await + .map_err(callback_error)?; + echo(response, &nonce).await.map_err(callback_error)?; + let mut state = lock(&self.state); + if state.proofs.len() >= MAX_PROOFS + && let Some(oldest) = state + .proofs + .iter() + .min_by_key(|(_, expiry)| *expiry) + .map(|(key, _)| key.clone()) + { + state.proofs.remove(&oldest); + } + state.proofs.insert(key, Instant::now() + PROOF_TTL); + Ok(()) + } +} + +impl DispatchState { + fn detach(&mut self, key: &Key, grant: &Shared) { + if self + .grants + .get(key) + .is_some_and(|g| Shared::ptr_eq(g, grant)) + { + self.grants.remove(key); + } + grant.stop.cancel(); + } +} + +impl GrantData { + fn live(&self) -> bool { + self.lease > Instant::now() && self.termination.is_none() + } + + fn response(&mut self, id: &str, refreshing: bool) -> WebhookSubscription { + WebhookSubscription { + result_type: ResultType::COMPLETE, + id: id.into(), + refresh_before: Some(self.refresh_before), + cursor: self.cursor.clone(), + truncated: std::mem::take(&mut self.truncated), + delivery_status: refreshing.then(|| WebhookSubscriptionStatus { + active: true, + last_delivery_at: self.last_delivery, + last_error: self.error.map(|reason| reason.category().into()), + }), + } + } +} + +impl Grant { + fn refresh( + &self, + mut context: RequestContext, + secret: &WebhookSecret, + duration: Duration, + ) -> Option { + let mut data = lock(&self.data); + if !data.live() || self.stop.is_cancelled() { + return None; + } + context.ct = self.stop.clone(); + data.context = context; + data.context_revision += 1; + if !data.secret.same_key(secret) { + data.old_secret = Some(( + Instant::now() + ROTATION_GRACE, + std::mem::replace(&mut data.secret, secret.clone()), + )); + } + data.lease = Instant::now() + duration; + data.refresh_before = Utc::now() + duration; + let response = data.response(&self.id, true); + self.changed.notify_waiters(); + Some(response) + } + + async fn expiry(&self) { + loop { + let changed = self.changed.notified(); + let lease = lock(&self.data).lease; + tokio::select! { + biased; + () = changed => {}, + () = sleep_until(lease) => { + if lock(&self.data).lease <= Instant::now() { + return; + } + } + } + } + } +} + +impl EventsServer { + /// Configure outbound Events webhooks on a new registry, before sharing + /// it or creating emit handles. + /// + /// `principal` receives only request extensions, not user-supplied + /// `_meta`. Return a stable, tenant-scoped ID from trusted authentication + /// middleware, or `None` if the request is unauthenticated. A descriptor's + /// authorizer remains responsible for the principal's event permissions. + pub fn with_webhooks( + mut self, + principal: impl Fn(&Extensions) -> Option + MaybeSend + 'static, + egress: WebhookEgress, + ) -> Result { + let registry = Shared::get_mut(&mut self.0) + .ok_or_else(|| invalid("configure webhooks before sharing the Events registry"))?; + if registry.webhooks.is_some() { + return Err(invalid("webhooks are already configured")); + } + registry.webhooks = Some(Box::new(Dispatcher { + principal: Shared::new(principal), + egress: Egress::new(egress)?, + state: Mutex::default(), + })); + Ok(self) + } + + pub(super) async fn dispatch_webhook( + &self, + method: &str, + raw: Value, + context: RequestContext, + principal: String, + registration: Option, + ) -> Result { + let dispatcher = self.0.webhooks.as_ref().expect("checked configuration"); + let deadline = Instant::now() + RPC_BUDGET; + let work = async { + if method == SUBSCRIBE { + let params: SubscribeParams = serde_json::from_value(raw) + .map_err(|_| invalid("invalid webhook subscribe parameters"))?; + let registration = registration.ok_or_else(not_found)?; + let call = Subscribe { + params, + context, + principal, + registration, + }; + encode(self.subscribe_webhook(dispatcher, call, deadline).await?) + } else { + let params: UnsubscribeParams = serde_json::from_value(raw) + .map_err(|_| invalid("invalid webhook unsubscribe parameters"))?; + callback_url(¶ms.delivery.url)?; + let args = params.arguments.unwrap_or_default(); + let (descriptor, registration, generation) = + registration.ok_or_else(missing_grant)?; + authorize(&descriptor, &context, &args).await?; + let key = Key::new(&principal, ¶ms.delivery.url, ¶ms.name, &args)?; + let registry = self.0.state(); + let entry = registry + .entries + .get(¶ms.name) + .ok_or_else(missing_grant)?; + ensure_current(entry, registration, generation)?; + if !Shared::ptr_eq(&entry.descriptor, &descriptor) { + // A descriptor race also needs the client's relist and retry. + return Err(EventsError::HeaderMismatch( + "event descriptor changed during authorization".into(), + )); + } + let mut state = lock(&dispatcher.state); + let grant = state.grants.get(&key).ok_or_else(missing_grant)?; + if grant.registration != registration + || grant.generation != generation + || !lock(&grant.data).live() + || grant.stop.is_cancelled() + { + return Err(missing_grant()); + } + grant.stop.cancel(); + state.grants.remove(&key); + encode(crate::model::TaskAckResult::new()) + } + }; + timeout_at(deadline, work) + .await + .map_err(|_| source_error("webhook RPC budget exceeded"))? + } + + async fn subscribe_webhook( + &self, + dispatcher: &Dispatcher, + call: Subscribe, + deadline: Instant, + ) -> Result { + let Subscribe { + params, + mut context, + principal, + registration: (descriptor, registration, generation), + } = call; + if !descriptor.wire.delivery.contains(&DeliveryMode::Webhook) { + return Err(unsupported(DeliveryMode::Webhook)); + } + let url = callback_url(¶ms.delivery.url)?; + let secret = WebhookSecret::from_existing(¶ms.delivery.secret)?; + let duration = ttl(params.ttl_ms); + let args = params.arguments.unwrap_or_default(); + let name = params.name; + let key = Key::new(&principal, ¶ms.delivery.url, &name, &args)?; + let id = key.id(); + let source = SourceRef { + server: self.clone(), + name, + args, + registration, + generation, + }; + let grant = { + let state = lock(&dispatcher.state); + let grant = state.grants.get(&key); + if grant.is_none() && state.grants.len() >= MAX_GRANTS { + return Err(limit("webhookSubscriptions", MAX_GRANTS)); + } + grant.filter(|grant| source.matches_grant(grant)).cloned() + }; + let approved = authorize(&descriptor, &context, &source.args).await; + source.same_descriptor(&descriptor)?; + if let Err(error) = approved { + if let EventsError::Forbidden { reason } = &error + && let Some(grant) = grant + { + let mut state = lock(&dispatcher.state); + lock(&grant.data).termination = Some( + EventsError::Forbidden { + reason: reason.clone(), + } + .into(), + ); + state.detach(&key, &grant); + } + return Err(error); + } + if let Some(grant) = grant + && let Some(response) = grant.refresh(context.clone(), &secret, duration) + { + return Ok(response); + } + dispatcher + .consent( + (principal, params.delivery.url), + &url, + &id, + &secret, + deadline, + ) + .await?; + source.same_descriptor(&descriptor)?; + let mut query = CheckQuery { + age_floor: age_floor(params.cursor.as_deref(), params.max_age_ms), + cursor: params.cursor, + max_events: 1, + max_bytes: MAX_BODY, + }; + let mut initial = source.read(&context, &query, &descriptor).await?; + source.same_descriptor(&descriptor)?; + let mut state = lock(&dispatcher.state); + if let Some(grant) = state.grants.get(&key) + && source.matches_grant(grant) + && let Some(response) = grant.refresh(context.clone(), &secret, duration) + { + return Ok(response); + } + if state.grants.len() >= MAX_GRANTS && !state.grants.contains_key(&key) { + return Err(limit("webhookSubscriptions", MAX_GRANTS)); + } + let truncated = std::mem::take(&mut initial.truncated); + if initial.events.is_empty() { + query.cursor.clone_from(&initial.cursor); + } + let stop = CancellationToken::new(); + context.ct = stop.clone(); + let mut data = GrantData { + lease: Instant::now() + duration, + refresh_before: Utc::now() + duration, + context, + context_revision: 0, + permitted: descriptor.clone(), + secret, + old_secret: None, + cursor: query.cursor.clone(), + truncated, + last_delivery: None, + error: None, + termination: None, + }; + let response = data.response(&id, false); + let grant = Shared::new(Grant { + id, + registration, + generation, + stop, + changed: Notify::new(), + policy_changed: Notify::new(), + data: Mutex::new(data), + }); + state.grants.insert(key.clone(), grant.clone()); + drop(state); + let worker = Worker { + source, + grant, + url, + key, + }; + spawn_service_task(worker.run(query, initial)); + Ok(response) + } +} + +struct Subscribe { + params: SubscribeParams, + context: RequestContext, + principal: String, + registration: Registration, +} + +async fn authorize( + descriptor: &Descriptor, + context: &RequestContext, + args: &JsonObject, +) -> Result<(), EventsError> { + (descriptor.validate_arguments)(args)?; + if let Some(authorize) = &descriptor.authorize { + authorize(context.clone(), args.clone(), DeliveryMode::Webhook).await?; + } + Ok(()) +} + +struct SourceRef { + server: EventsServer, + name: String, + args: JsonObject, + registration: u64, + generation: u64, +} + +impl SourceRef { + fn matches_grant(&self, grant: &Grant) -> bool { + self.registration == grant.registration && self.generation == grant.generation + } + + fn emitted(&self) -> Option> { + self.server + .0 + .state() + .entries + .get(&self.name) + .and_then(|entry| entry.emitted.clone()) + } + + fn current(&self) -> Result, EventsError> { + let state = self.server.0.state(); + let entry = state.entries.get(&self.name).ok_or_else(not_found)?; + ensure_current(entry, self.registration, self.generation)?; + if !entry + .descriptor + .wire + .delivery + .contains(&DeliveryMode::Webhook) + { + return Err(unsupported(DeliveryMode::Webhook)); + } + Ok(entry.descriptor.clone()) + } + + fn same_descriptor(&self, descriptor: &Shared) -> Result<(), EventsError> { + if Shared::ptr_eq(&self.current()?, descriptor) { + Ok(()) + } else { + // A descriptor race also needs the client's relist and retry. + Err(EventsError::HeaderMismatch( + "event descriptor changed during authorization".into(), + )) + } + } + + async fn read( + &self, + context: &RequestContext, + query: &CheckQuery, + descriptor: &Shared, + ) -> Result { + let registry = &self.server.0; + let source = { + let mut state = registry.state(); + let entry = state.entries.get_mut(&self.name).ok_or_else(not_found)?; + ensure_current(entry, self.registration, self.generation)?; + match &mut entry.source { + Source::Check(check) => Read::Check(check.clone()), + Source::Emit(ring) => Read::Emit(ring.read( + registry.epoch, + entry.registration, + entry.generation, + query, + )), + } + }; + match source { + Read::Emit(page) => Ok(page.finish(context, &self.args, descriptor, true)), + Read::Check(check) => { + let batch = check(context.clone(), self.args.clone(), query.clone()).await?; + let (end, more, next) = (batch.end.clone(), batch.has_more, batch.next_poll_ms); + match checked_result(batch, query, true) { + Err(EventsError::ResourceExhausted { limit, .. }) if limit == "pollBytes" => { + Ok(poll_result( + Vec::new(), + end, + true, + more, + next.unwrap_or(DEFAULT_POLL_MS), + )) + } + result => result, + } + } + } + } +} + +struct Worker { + source: SourceRef, + grant: Shared, + url: Url, + key: Key, +} + +impl Drop for Worker { + fn drop(&mut self) { + lock(&self.dispatcher().state).detach(&self.key, &self.grant); + } +} + +impl Worker { + fn dispatcher(&self) -> &Dispatcher { + self.source + .server + .0 + .webhooks + .as_deref() + .expect("configured dispatcher") + } + + async fn run(self, query: CheckQuery, initial: PollResult) { + let error = tokio::select! { + biased; + () = self.grant.stop.cancelled() => lock(&self.grant.data).termination.clone(), + () = self.grant.expiry() => None, + error = self.policy() => Some(error), + error = self.deliver(query, initial) => Some(error.into()), + }; + if let Some(error) = error { + lock(&self.dispatcher().state).detach(&self.key, &self.grant); + let body = json!({"type": "terminated", "error": error}).to_string(); + if body.len() <= MAX_BODY { + let _ = self + .post(&message_id(Some("terminated")), body.into()) + .await; + } + } + } + + async fn policy(&self) -> ErrorData { + let mut next = Instant::now() + AUTH_INTERVAL; + 'policy: loop { + let mut changed = std::pin::pin!(self.source.server.0.changes.notified()); + let grant_changed = self.grant.changed.notified(); + let (context, revision, permitted) = { + let data = lock(&self.grant.data); + if let Some(error) = &data.termination { + return error.clone(); + } + ( + data.context.clone(), + data.context_revision, + data.permitted.clone(), + ) + }; + let current = match self.source.current() { + Ok(current) => current, + Err(error) => return error.into(), + }; + if !Shared::ptr_eq(¤t, &permitted) + || (current.authorize.is_some() && next <= Instant::now()) + { + let mut authorization = + std::pin::pin!(authorize(¤t, &context, &self.source.args)); + tokio::pin!(grant_changed); + let authorization = loop { + tokio::select! { + biased; + () = &mut changed => { + changed.set(self.source.server.0.changes.notified()); + match self.source.current() { + Ok(latest) if Shared::ptr_eq(&latest, ¤t) => {} + Ok(_) => continue 'policy, + Err(error) => return error.into(), + } + } + () = &mut grant_changed => continue 'policy, + result = &mut authorization => break result, + } + }; + let latest = match self.source.current() { + Ok(latest) => latest, + Err(error) => return error.into(), + }; + let mut data = lock(&self.grant.data); + if revision != data.context_revision || !Shared::ptr_eq(&latest, ¤t) { + continue; + } + if let Err(error) = authorization { + return error.into(); + } + data.permitted = current.clone(); + next = Instant::now() + AUTH_INTERVAL; + self.grant.policy_changed.notify_waiters(); + continue; + } + tokio::select! { + () = changed => {}, + () = grant_changed => {}, + () = sleep_until(next), if current.authorize.is_some() => {}, + } + } + } + + async fn post(&self, id: &str, body: Bytes) -> Result { + let (secret, previous) = { + let mut data = lock(&self.grant.data); + if data + .old_secret + .as_ref() + .is_some_and(|(until, _)| *until <= Instant::now()) + { + data.old_secret = None; + } + ( + data.secret.clone(), + data.old_secret.as_ref().map(|(_, key)| key.clone()), + ) + }; + self.dispatcher() + .egress + .post( + &self.url, + &self.grant.id, + id, + body, + (&secret, previous.as_ref()), + ) + .await + } + + async fn attempt(&self, sequence: u64, id: String, body: Bytes) -> u64 { + let expires = Instant::now() + RETRY_WINDOW; + for attempt in 0..MAX_ATTEMPTS { + if Instant::now() >= expires { + break; + } + let response = timeout_at(expires, self.post(&id, body.clone())) + .await + .unwrap_or(Err(Reason::Timeout)); + let (settled, failure) = match response { + Ok(response) => { + let status = response.status(); + if status.is_success() { + let mut data = lock(&self.grant.data); + data.last_delivery = Some(Utc::now()); + data.error = None; + return sequence; + } + ( + matches!(status, StatusCode::GONE | StatusCode::PAYLOAD_TOO_LARGE), + Reason::status(status), + ) + } + Err(reason) => (false, reason), + }; + lock(&self.grant.data).error = Some(failure); + if settled || attempt + 1 == MAX_ATTEMPTS { + break; + } + let retry = Instant::now() + + Duration::from_millis((1000 << attempt) + rand::random_range(0..250_u64)); + if retry >= expires { + break; + } + sleep_until(retry).await; + } + sequence + } + + async fn deliver(&self, mut query: CheckQuery, initial: PollResult) -> EventsError { + let emitted = self.source.emitted(); + let mut wake = emitted.as_ref().map(|emitted| Box::pin(emitted.notified())); + let mut attempts = FuturesUnordered::new(); + let mut pending: VecDeque = VecDeque::new(); + let mut page = Some(initial); + let mut sequence = 0_u64; + let mut read_at = Some(Instant::now()); + let mut activating = true; + loop { + let updated = self.grant.policy_changed.notified(); + let changed = self.source.server.0.changes.notified(); + let descriptor = match self.source.current() { + Ok(current) => current, + Err(error) => return error, + }; + let permitted = Shared::ptr_eq(&lock(&self.grant.data).permitted, &descriptor); + // A gap cannot publish a cursor past an earlier unresolved event. + let ready = permitted + && pending.len() < MAX_PENDING + && !pending.iter().any(|item| item.gap) + && page + .as_ref() + .is_none_or(|page| !page.truncated || pending.is_empty()); + if ready && let Some(mut current) = page.take() { + let cursor = current.cursor.take(); + let mut gap = current.truncated; + let mut body = None; + if let Some(mut event) = current.events.pop() { + // Beta L521: the message's replay token is the settled + // prefix before this attempt, not the occurrence's own position. + event.cursor.clone_from(&lock(&self.grant.data).cursor); + match event_bytes(&event) { + Ok(Some(_)) => match serde_json::to_vec(&event) { + Ok(encoded) => body = Some(Bytes::from(encoded)), + Err(_) => { + return source_error("could not encode webhook occurrence"); + } + }, + Ok(None) => gap = true, + Err(error) => return error, + } + } + if gap { + if !pending.is_empty() { + current.cursor = cursor; + current.truncated = true; + page = Some(current); + continue; + } + let encoded = json!({"type": "gap", "cursor": cursor}).to_string(); + if encoded.len() > MAX_BODY { + return source_error("event cursor exceeds webhook body size"); + } + body = Some(encoded.into()); + } + current.has_more &= query.cursor != cursor; + query.cursor.clone_from(&cursor); + sequence += 1; + let settled = body.is_none(); + let item = Pending { + sequence, + cursor, + gap, + settled, + }; + pending.push_back(item); + if let Some(body) = body { + attempts.push(self.attempt(sequence, message_id(gap.then_some("gap")), body)); + } + self.advance(&mut pending); + if !current.has_more { + query.age_floor = None; + read_at = if emitted.is_some() { + activating.then(Instant::now) + } else { + Some( + Instant::now() + + Duration::from_millis(current.next_poll_ms.clamp(1000, 30_000)), + ) + }; + } else { + read_at = Some(Instant::now()); + } + activating = false; + tokio::task::yield_now().await; + continue; + } + let context = lock(&self.grant.data).context.clone(); + tokio::select! { + biased; + () = updated => {}, + () = changed => {}, + Some(acked) = attempts.next(), if !attempts.is_empty() => { + if let Some(item) = pending.iter_mut().find(|item| item.sequence == acked) { + item.settled = true; + } + self.advance(&mut pending); + } + () = async { wake.as_mut().expect("emit notification").await }, if wake.is_some() => { + wake = emitted.as_ref().map(|emitted| Box::pin(emitted.notified())); + read_at = Some(Instant::now()); + } + result = async { + sleep_until(read_at.expect("scheduled source read")).await; + self.source.read(&context, &query, &descriptor).await + }, if ready && page.is_none() && read_at.is_some() => { + match result { + Ok(result) => page = Some(result), + Err(error @ (EventsError::Forbidden { .. } | EventsError::NotFound { .. })) => return error, + Err(_) => read_at = Some(Instant::now() + Duration::from_secs(1)), + } + } + } + } + } + + fn advance(&self, pending: &mut VecDeque) { + while pending.front().is_some_and(|item| item.settled) { + let item = pending.pop_front().expect("settled prefix"); + let mut data = lock(&self.grant.data); + data.cursor = item.cursor; + data.truncated |= item.gap; + } + } +} + +struct Pending { + sequence: u64, + cursor: Option, + gap: bool, + settled: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test(start_paused = true)] + async fn verification_slot_wait_reports_resource_exhaustion() { + let server = EventsServer::new() + .with_webhooks(|_| None, WebhookEgress::default()) + .unwrap(); + let dispatcher = server.0.webhooks.as_ref().unwrap(); + let slot = Shared::new(tokio::sync::Mutex::new(Instant::now())); + let _in_flight = slot.lock().await; + lock(&dispatcher.state) + .host_limit + .insert("example.com".into(), slot.clone()); + let url = callback_url("https://example.com/callback").unwrap(); + let deadline = Instant::now() + RPC_BUDGET; + let result = timeout_at( + deadline, + dispatcher.consent( + ("principal".into(), url.to_string()), + &url, + "grant", + &WebhookSecret::generate(), + deadline, + ), + ) + .await + .unwrap(); + assert!(matches!(result, Err(EventsError::ResourceExhausted { .. }))); + } +} diff --git a/crates/rmcp/src/events/server/webhook/egress.rs b/crates/rmcp/src/events/server/webhook/egress.rs new file mode 100644 index 000000000..b1f2e3ecd --- /dev/null +++ b/crates/rmcp/src/events/server/webhook/egress.rs @@ -0,0 +1,408 @@ +use std::{ + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + sync::Arc, + time::Duration, +}; + +use reqwest::{ + Client, Response, StatusCode, Url, + dns::{Addrs, Name, Resolve, Resolving}, +}; +use tokio::sync::Semaphore; +use url::Host; + +use super::{EventsError, WebhookSecret, invalid}; +use crate::events::webhook::constant_time_eq; + +const ATTEMPT: Duration = Duration::from_secs(5); + +/// Additional outbound network and TLS trust for the Events webhook dispatcher. +/// +/// The default policy accepts only globally routable destinations and uses +/// the platform trust store. +#[derive(Debug, Clone, Default)] +#[non_exhaustive] +pub struct WebhookEgress { + /// Additional allowed address prefixes, as address and prefix-length pairs. + pub additional_allowed_networks: Vec<(IpAddr, u8)>, + /// Extra DER-encoded CA certificates; hostname verification remains enabled. + pub additional_root_certificates: Vec>, +} + +pub(super) struct Egress { + client: Client, + policy: Arc, +} + +struct Policy { + networks: Arc<[(IpAddr, u8)]>, + lookups: Arc, +} + +impl Egress { + pub(super) fn new(config: WebhookEgress) -> Result { + if config + .additional_allowed_networks + .iter() + .any(|(addr, bits)| match addr { + IpAddr::V4(_) => *bits > 32, + IpAddr::V6(addr) => *bits > 128 || addr.to_ipv4_mapped().is_some(), + }) + { + return Err(invalid( + "invalid webhook network prefix; use IPv4 for mapped addresses", + )); + } + let policy = Arc::new(Policy { + networks: config.additional_allowed_networks.into(), + lookups: Arc::new(Semaphore::new(32)), + }); + let mut builder = Client::builder() + .tls_backend_rustls() + .https_only(true) + .no_proxy() + .no_gzip() + .no_brotli() + .no_deflate() + .no_zstd() + .redirect(reqwest::redirect::Policy::none()) + .retry(reqwest::retry::never()) + .pool_max_idle_per_host(2) + .pool_idle_timeout(Duration::from_secs(15)) + .dns_resolver(policy.clone()) + .timeout(ATTEMPT); + for der in config.additional_root_certificates { + builder = builder.add_root_certificate( + reqwest::Certificate::from_der(&der) + .map_err(|_| invalid("invalid webhook root certificate"))?, + ); + } + let client = builder + .build() + .map_err(|_| invalid("could not configure webhook HTTPS client"))?; + Ok(Self { client, policy }) + } + + pub(super) async fn post( + &self, + url: &Url, + id: &str, + message: &str, + body: bytes::Bytes, + secrets: (&WebhookSecret, Option<&WebhookSecret>), + ) -> Result { + let literal = match url.host() { + Some(Host::Ipv4(ip)) => Some(IpAddr::V4(ip)), + Some(Host::Ipv6(ip)) => Some(IpAddr::V6(ip)), + _ => None, + }; + if literal.is_some_and(|ip| !self.policy.allows(ip)) { + return Err(Reason::ConnectionRefused); + } + let timestamp = chrono::Utc::now().timestamp().to_string(); + let mut signature = secrets.0.signature(message, ×tamp, &body); + if let Some(previous) = secrets.1 { + signature.push(' '); + signature.push_str(&previous.signature(message, ×tamp, &body)); + } + let mut signature = http::HeaderValue::from_str(&signature).expect("ASCII signature"); + signature.set_sensitive(true); + self.client + .post(url.clone()) + .header("content-type", "application/json") + .header("webhook-id", message) + .header("webhook-timestamp", timestamp) + .header("webhook-signature", signature) + .header("x-mcp-subscription-id", id) + .body(body) + .send() + .await + .map_err(Reason::transport) + } +} + +pub(super) fn callback_url(url: &str) -> Result { + let invalid = + || invalid("webhook callback must be HTTPS without credentials, fragment or port 0"); + let (scheme, rest) = url.split_once("://").ok_or_else(invalid)?; + // Reject authority credentials even when empty and normalized away by URL parsing. + if !scheme.eq_ignore_ascii_case("https") + || rest.starts_with(['/', '\\']) + || rest + .split(['/', '?', '#']) + .next() + .is_some_and(|authority| authority.contains(['@', '\\'])) + || url.bytes().any(|b| b.is_ascii_control()) + { + return Err(invalid()); + } + let parsed = Url::parse(url).map_err(|_| invalid())?; + if parsed.scheme() != "https" + || !parsed.has_host() + || !parsed.username().is_empty() + || parsed.password().is_some() + || parsed.fragment().is_some() + || parsed.port() == Some(0) + { + return Err(invalid()); + } + Ok(parsed) +} + +impl Resolve for Policy { + fn resolve(&self, name: Name) -> Resolving { + let networks = self.networks.clone(); + let lookups = self.lookups.clone(); + Box::pin(async move { + tokio::time::timeout(Duration::from_secs(2), async move { + let permit = lookups.acquire_owned().await?; + // Dropping a waiter cannot interrupt a running OS lookup. + // Keep its permit until the resolver task actually returns. + let checked = tokio::spawn(async move { + let _permit = permit; + let addresses = tokio::net::lookup_host((name.as_str(), 0)).await?; + let checked: Vec<_> = addresses + .filter_map(|addr| { + let ip = addr.ip().to_canonical(); + Policy::allows_ip(&networks, ip).then(|| { + if ip == addr.ip() { + addr + } else { + SocketAddr::new(ip, addr.port()) + } + }) + }) + .collect(); + if checked.is_empty() { + return Err(std::io::Error::from(std::io::ErrorKind::ConnectionRefused)); + } + Ok(checked) + }) + .await??; + Ok(Box::new(checked.into_iter()) as Addrs) + }) + .await + .map_err(|_| std::io::Error::from(std::io::ErrorKind::TimedOut))? + }) + } +} + +impl Policy { + fn allows(&self, ip: IpAddr) -> bool { + Self::allows_ip(&self.networks, ip.to_canonical()) + } + + fn allows_ip(prefixes: &[(IpAddr, u8)], ip: IpAddr) -> bool { + prefixes.iter().any(|(net, bits)| match (*net, ip) { + (IpAddr::V4(net), IpAddr::V4(ip)) => { + prefix(u32::from(net).into(), u32::from(ip).into(), 32, *bits) + } + (IpAddr::V6(net), IpAddr::V6(ip)) => prefix(net.into(), ip.into(), 128, *bits), + _ => false, + }) || match ip { + IpAddr::V4(ip) => global_v4(ip), + IpAddr::V6(ip) => global_v6(ip), + } + } +} + +fn prefix(network: u128, address: u128, width: u8, length: u8) -> bool { + length == 0 || (network ^ address) >> (width - length) == 0 +} + +fn global_v4(ip: Ipv4Addr) -> bool { + !matches!(ip.octets(), + [0 | 10 | 127 | 224..=255, ..] | + [100, 64..=127, ..] | + [169, 254, ..] | + [172, 16..=31, ..] | + [192, 0, 0, 0..=8 | 11..=255] | + [192, 0, 2, _] | + [192, 88, 99, _] | + [192, 168, ..] | + [198, 18 | 19, ..] | + [198, 51, 100, _] | + [203, 0, 113, _] + ) +} + +fn global_v6(ip: Ipv6Addr) -> bool { + // Only public unicast allocations. Reject translation/tunneling ranges + // by default too: their apparent destination can hide a private peer. + match ip.segments() { + [0x2001, 1, 0, 0, 0, 0, 0, 1..=3] + | [0x2001, 3, ..] + | [0x2001, 4, 0x112, ..] + | [0x2001, 0x20..=0x3f, ..] => true, + [0x2001, 0..=0x1ff | 0xdb8, ..] | [0x2002 | 0x3fff, ..] => false, + [0x2000..=0x3ffe, ..] => true, + _ => false, + } +} + +#[derive(Clone, Copy)] +pub(super) enum Reason { + ConnectionRefused, + Timeout, + TlsError, + Http4xx, + Http5xx, + ChallengeFailed, +} + +impl Reason { + pub(super) fn category(self) -> &'static str { + match self { + Self::ConnectionRefused => "connection_refused", + Self::Timeout => "timeout", + Self::TlsError => "tls_error", + Self::Http4xx => "http_4xx", + Self::Http5xx => "http_5xx", + Self::ChallengeFailed => "challenge_failed", + } + } + + fn transport(error: reqwest::Error) -> Self { + if error.is_timeout() { + return Self::Timeout; + } + let mut source = std::error::Error::source(&error); + while let Some(error) = source { + if let Some(io) = error.downcast_ref::() { + if io.kind() == std::io::ErrorKind::InvalidData { + return Self::TlsError; + } + if io.kind() == std::io::ErrorKind::TimedOut { + return Self::Timeout; + } + } + source = error + .downcast_ref::() + .and_then(std::io::Error::get_ref) + .map(|cause| cause as &dyn std::error::Error) + .or_else(|| error.source()); + } + Self::ConnectionRefused + } + + pub(super) fn status(status: StatusCode) -> Self { + if status.is_client_error() { + Self::Http4xx + } else if status.is_server_error() { + Self::Http5xx + } else { + Self::ChallengeFailed + } + } +} + +pub(super) async fn echo(mut response: Response, challenge: &str) -> Result<(), Reason> { + if !response.status().is_success() { + return Err(Reason::status(response.status())); + } + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(Reason::transport)? { + if chunk.len() > 1024 - body.len() { + return Err(Reason::ChallengeFailed); + } + body.extend_from_slice(&chunk); + } + #[derive(serde::Deserialize)] + struct Echo { + challenge: String, + } + let echoed: Echo = serde_json::from_slice(&body).map_err(|_| Reason::ChallengeFailed)?; + if constant_time_eq(challenge.as_bytes(), echoed.challenge.as_bytes()) { + Ok(()) + } else { + Err(Reason::ChallengeFailed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn callback_egress_policy() { + let mut policy = Policy { + networks: Arc::from([]), + lookups: Arc::new(Semaphore::new(1)), + }; + for (address, allowed) in [ + ("0.1.2.3", false), + ("10.0.0.1", false), + ("100.63.255.255", true), + ("100.64.0.0", false), + ("100.127.255.255", false), + ("100.128.0.0", true), + ("127.0.0.1", false), + ("169.254.1.1", false), + ("172.31.0.1", false), + ("192.0.0.8", false), + ("192.0.0.9", true), + ("192.0.0.10", true), + ("192.0.0.11", false), + ("192.0.2.1", false), + ("192.88.99.1", false), + ("192.168.0.1", false), + ("198.18.0.0", false), + ("198.19.255.255", false), + ("198.20.0.0", true), + ("198.51.100.1", false), + ("203.0.113.1", false), + ("224.0.0.1", false), + ("240.0.0.1", false), + ("255.255.255.255", false), + ("::1", false), + ("fe80::1", false), + ("febf::1", false), + ("fc00::1", false), + ("fdff::1", false), + ("64:ff9b::808:808", false), + ("2002:808:808::1", false), + ("2001:0:808:808::1", false), + ("2001:db8::1", false), + ("3fff::", false), + ("2606:4700::1111", true), + ("::ffff:127.0.0.1", false), + ("::ffff:8.8.8.8", true), + ] { + assert_eq!( + policy.allows(address.parse().unwrap()), + allowed, + "{address}" + ); + } + for (network, bits, address, allowed) in [ + ("0.0.0.0", 0, "10.0.0.1", true), + ("0.0.0.0", 0, "::1", false), + ("::", 0, "::1", true), + ("::", 0, "10.0.0.1", false), + ("127.0.0.1", 32, "::ffff:127.0.0.1", true), + ("127.0.0.1", 32, "127.0.0.2", false), + ("fc00::1", 128, "fc00::1", true), + ("fc00::1", 128, "fc00::2", false), + ] { + policy.networks = Arc::from([(network.parse().unwrap(), bits)]); + assert_eq!( + policy.allows(address.parse().unwrap()), + allowed, + "{network}/{bits}: {address}" + ); + } + for url in [ + "http://example.com", + "https://user:pass@example.com", + "https://@example.com", + "https://example.com/#fragment", + "https://example.com:0", + r"https://example.com\callback", + "https://exam\tple.com", + "https://example.com/\u{7f}", + ] { + assert!(callback_url(url).is_err(), "{url:?}"); + } + assert!(callback_url("https://example.com:8443/callback?q=@").is_ok()); + } +} diff --git a/crates/rmcp/src/events/server/webhook/key.rs b/crates/rmcp/src/events/server/webhook/key.rs new file mode 100644 index 000000000..fe52c96dd --- /dev/null +++ b/crates/rmcp/src/events/server/webhook/key.rs @@ -0,0 +1,159 @@ +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use sha2::{Digest, Sha256}; + +use super::{EventsError, JsonObject, Value, invalid}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(super) struct Key(Vec); + +impl Key { + pub(super) fn new( + principal: &str, + url: &str, + name: &str, + args: &JsonObject, + ) -> Result { + let mut encoded = b"io.modelcontextprotocol/events webhook key v1\0".to_vec(); + for part in [principal, url, name] { + string(&mut encoded, part); + } + object(&mut encoded, args)?; + Ok(Self(encoded)) + } + + pub(super) fn id(&self) -> String { + let hash = Sha256::digest(&self.0); + format!("sub_{}", URL_SAFE_NO_PAD.encode(&hash[..16])) + } +} + +fn length(out: &mut Vec, len: usize) { + out.extend_from_slice(&(len as u64).to_be_bytes()); +} + +fn string(out: &mut Vec, s: &str) { + length(out, s.len()); + out.extend_from_slice(s.as_bytes()); +} + +fn object(out: &mut Vec, obj: &JsonObject) -> Result<(), EventsError> { + let mut sorted: Vec<_> = obj.iter().collect(); + sorted.sort_unstable_by_key(|(key, _)| *key); + length(out, sorted.len()); + for (key, value) in sorted { + string(out, key); + encode_value(out, value)?; + } + Ok(()) +} + +fn encode_value(out: &mut Vec, value: &Value) -> Result<(), EventsError> { + match value { + Value::Null => out.push(b'n'), + Value::Bool(v) => out.push(if *v { b't' } else { b'f' }), + Value::String(s) => { + out.push(b's'); + string(out, s); + } + Value::Array(items) => { + out.push(b'a'); + length(out, items.len()); + for item in items { + encode_value(out, item)?; + } + } + Value::Object(obj) => { + out.push(b'o'); + object(out, obj)?; + } + Value::Number(n) => { + if let Some(n) = n.as_u64() { + out.push(b'u'); + out.extend_from_slice(&n.to_be_bytes()); + } else if let Some(n) = n.as_i64() { + if n == 0 { + out.push(b'u'); + } else { + out.push(b'i'); + } + out.extend_from_slice(&n.to_be_bytes()); + } else { + let n = n + .as_f64() + .ok_or_else(|| invalid("unsupported webhook argument number"))?; + // Outside binary64's safe integer range, never merge a + // rounded floating-point token with an exact JSON integer. + if n.fract() == 0.0 && n.abs() <= 9_007_199_254_740_991.0 { + if n < 0.0 { + out.push(b'i'); + out.extend_from_slice(&(n as i64).to_be_bytes()); + } else { + out.push(b'u'); + out.extend_from_slice(&(n as u64).to_be_bytes()); + } + } else { + out.push(b'd'); + out.extend_from_slice(&n.to_bits().to_be_bytes()); + } + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_arguments_and_stable_ids() { + let key = |principal, text| { + let arguments = serde_json::from_str(text).unwrap(); + Key::new(principal, "https://example.net/", "demo", &arguments).unwrap() + }; + let expected = key( + "alice", + r#"{"a":[18446744073709551615, -9223372036854775808, 0], "b":0.0000001}"#, + ); + assert_eq!( + expected, + key( + "alice", + r#"{"b":1e-7,"a":[18446744073709551615,-9223372036854775808,-0]}"# + ) + ); + assert_eq!( + expected, + key( + "alice", + r#"{"b":1E-7,"a":[18446744073709551615,-9223372036854775808,-0.0]}"# + ) + ); + assert_ne!( + expected, + key( + "alice", + r#"{"b":1e-7,"a":[18446744073709551614,-9223372036854775808,-0]}"# + ) + ); + assert_ne!( + expected, + key( + "alice", + r#"{"b":1e-7,"a":[18446744073709551615,-9223372036854775807,-0]}"# + ) + ); + assert_ne!(key("alice", "{}"), key("bob", "{}")); + assert_eq!(key("alice", r#"{"a":2}"#), key("alice", r#"{"a":2.0}"#)); + assert_ne!( + key("alice", r#"{"a":9007199254740992}"#), + key("alice", r#"{"a":9007199254740992.0}"#) + ); + assert_ne!( + key("alice", r#"{"a":[1,2]}"#), + key("alice", r#"{"a":[2,1]}"#) + ); + assert_ne!(key("alice", r#"{"a":2}"#), key("alice", r#"{"a":"2"}"#)); + assert!(expected.id().starts_with("sub_")); + } +} diff --git a/crates/rmcp/src/events/webhook.rs b/crates/rmcp/src/events/webhook.rs new file mode 100644 index 000000000..2ae26e2ce --- /dev/null +++ b/crates/rmcp/src/events/webhook.rs @@ -0,0 +1,339 @@ +//! Standard Webhooks authentication for the Events Beta. + +use std::fmt; + +use base64::{Engine, engine::general_purpose::STANDARD}; +use chrono::{DateTime, Utc}; +use hmac::{Hmac, KeyInit, Mac}; +use http::HeaderMap; +use serde_json::{Value, json}; +use sha2::Sha256; +use zeroize::Zeroizing; + +use super::wire::{EventOccurrence, EventsError}; +use crate::{ErrorData, model::JsonObject}; + +pub(super) const MAX_BODY: usize = 256 * 1024; + +#[cfg(all(feature = "events-webhook", feature = "server"))] +pub(super) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (a, b)| diff | (a ^ b)) == 0 +} + +#[cfg(any( + feature = "client", + all(feature = "events-webhook", feature = "server") +))] +mod rpc; +#[cfg(feature = "client")] +pub use rpc::WebhookOptions; +#[cfg(any( + feature = "client", + all(feature = "events-webhook", feature = "server") +))] +pub(super) use rpc::*; +#[cfg(any( + feature = "client", + all(feature = "events-webhook", feature = "server") +))] +pub use rpc::{WebhookSubscription, WebhookSubscriptionStatus, WebhookTtl}; + +/// A Standard Webhooks symmetric signing key. +#[derive(Clone)] +pub struct WebhookSecret(Zeroizing>); + +impl WebhookSecret { + /// Create a key containing 32 bytes from the system-seeded CSPRNG. + pub fn generate() -> Self { + let mut bytes = Zeroizing::new(vec![0; 32]); + rand::fill(bytes.as_mut_slice()); + Self(bytes) + } + + /// Import an existing `whsec_` key containing 24 to 64 random bytes. + pub fn from_existing(secret: &str) -> Result { + let invalid = || EventsError::InvalidParams("invalid webhook secret".into()); + let encoded = secret.strip_prefix("whsec_").ok_or_else(invalid)?; + if !(32..=88).contains(&encoded.len()) { + return Err(invalid()); + } + let bytes = Zeroizing::new(STANDARD.decode(encoded).map_err(|_| invalid())?); + if !(24..=64).contains(&bytes.len()) { + return Err(invalid()); + } + Ok(Self(bytes)) + } + + #[cfg(feature = "client")] + pub(super) fn encode(&self) -> Zeroizing { + let mut encoded = Zeroizing::new(String::with_capacity(6 + 88)); + encoded.push_str("whsec_"); + STANDARD.encode_string(self.0.as_slice(), &mut encoded); + encoded + } + + #[cfg(all(feature = "events-webhook", feature = "server"))] + pub(super) fn same_key(&self, other: &Self) -> bool { + constant_time_eq(&self.0, &other.0) + } + + fn mac(&self, id: &str, timestamp: &str, body: &[u8]) -> Hmac { + let mut mac = Hmac::::new_from_slice(&self.0).expect("HMAC accepts arbitrary keys"); + mac.update(id.as_bytes()); + mac.update(b"."); + mac.update(timestamp.as_bytes()); + mac.update(b"."); + mac.update(body); + mac + } + + #[cfg(any(test, all(feature = "events-webhook", feature = "server")))] + pub(super) fn signature(&self, id: &str, timestamp: &str, body: &[u8]) -> String { + format!( + "v1,{}", + STANDARD.encode(self.mac(id, timestamp, body).finalize().into_bytes()) + ) + } +} + +impl fmt::Debug for WebhookSecret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WebhookSecret([redacted])") + } +} + +/// An authenticated webhook body. The application owns routing and acceptance. +#[derive(Debug)] +#[non_exhaustive] +pub enum WebhookMessage { + /// An event, with its event ID and safe checkpoint. + Occurrence(EventOccurrence), + /// Replay was truncated; reconcile from this fresh checkpoint. + Gap { + /// Fresh checkpoint. + cursor: Option, + }, + /// The subscription ended on the server. + Terminated { + /// Termination reason. + error: ErrorData, + }, + /// Echo the challenge locally; do not forward it. + Verification { + /// The authenticated nonce. + challenge: String, + }, + /// An authenticated future control that can be acknowledged and ignored. + UnknownControl, +} + +/// A verified webhook and the identity information needed for safe routing. +#[derive(Debug)] +#[non_exhaustive] +pub struct VerifiedWebhook<'a> { + /// Authenticated per-message ID, stable across retries. + pub webhook_id: &'a str, + /// The subscription routing header, which is **not** signed. + pub subscription_id: &'a str, + /// Index in the supplied candidate secret slice. + pub matched_secret: usize, + /// Parsed body, verified before parsing. + pub message: WebhookMessage, +} + +/// Verify a raw webhook body (at most 256 KiB) with a five-minute clock window. +/// +/// The routing header is unsigned. Check that the matched secret belongs to +/// the indicated subscription before accepting a delivery. This function +/// does not store secrets, message IDs or cursors. +pub fn verify_webhook<'a>( + headers: &'a HeaderMap, + body: &[u8], + secrets: &[WebhookSecret], + now: DateTime, +) -> Result, EventsError> { + let invalid = || EventsError::InvalidParams("invalid webhook delivery".into()); + if body.len() > MAX_BODY { + return Err(invalid()); + } + let header = |name| { + let mut values = headers.get_all(name).iter(); + let value = values.next()?.to_str().ok()?; + (values.next().is_none() && !value.is_empty()).then_some(value) + }; + let webhook_id = header("webhook-id").ok_or_else(invalid)?; + if webhook_id.contains('.') { + return Err(invalid()); + } + let subscription_id = header("x-mcp-subscription-id").ok_or_else(invalid)?; + let timestamp = header("webhook-timestamp").ok_or_else(invalid)?; + let digits = timestamp.strip_prefix('-').unwrap_or(timestamp); + if !digits.bytes().all(|b| b.is_ascii_digit()) { + return Err(invalid()); + } + let seconds: i64 = timestamp.parse().map_err(|_| invalid())?; + if now.timestamp().abs_diff(seconds) > 300 { + return Err(invalid()); + } + let signatures = header("webhook-signature").ok_or_else(invalid)?; + let matched_secret = secrets + .iter() + .position(|secret| { + let mac = secret.mac(webhook_id, timestamp, body); + signatures.split_ascii_whitespace().any(|signature| { + let mut bytes = [0; 32]; + signature.strip_prefix("v1,").is_some_and(|encoded| { + STANDARD.decode_slice(encoded, &mut bytes) == Ok(32) + && mac.clone().verify_slice(&bytes).is_ok() + }) + }) + }) + .ok_or_else(invalid)?; + let value: Value = serde_json::from_slice(body).map_err(|_| invalid())?; + let message = match value.get("type") { + None => WebhookMessage::Occurrence(serde_json::from_value(value).map_err(|_| invalid())?), + Some(Value::String(kind)) => match kind.as_str() { + "gap" => WebhookMessage::Gap { + cursor: value + .get("cursor") + .map(|cursor| serde_json::from_value::>(cursor.clone())) + .transpose() + .map_err(|_| invalid())? + .flatten(), + }, + "terminated" => WebhookMessage::Terminated { + error: serde_json::from_value(value.get("error").ok_or_else(invalid)?.clone()) + .map_err(|_| invalid())?, + }, + "verification" => WebhookMessage::Verification { + challenge: value + .get("challenge") + .and_then(Value::as_str) + .ok_or_else(invalid)? + .to_owned(), + }, + _ => WebhookMessage::UnknownControl, + }, + Some(_) => return Err(invalid()), + }; + Ok(VerifiedWebhook { + webhook_id, + subscription_id, + matched_secret, + message, + }) +} + +/// Create the JSON body for a successful verification response. +pub fn challenge_response(challenge: &str) -> JsonObject { + JsonObject::from_iter([("challenge".into(), json!(challenge))]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn standard_webhooks_reference_vector() { + // standard-webhooks/libraries/rust/src/lib.rs, test_sign + let secret = + WebhookSecret::from_existing("whsec_C2FVsBQIhrscChlQIMV+b5sSYspob7oD").unwrap(); + let signature = secret.signature( + "msg_27UH4WbU6Z5A5EzD8u03UvzRbpk", + "1649367553", + br#"{"email":"test@example.com","username":"test_user"}"#, + ); + assert_eq!(signature, "v1,tZ1I4/hDygAJgO5TYxiSd6Sd0kDW6hPenDe+bTa3Kkw="); + } + + #[test] + fn secret_lengths_and_redaction() { + for len in [0, 23, 24, 32, 64, 65] { + let encoded = format!("whsec_{}", STANDARD.encode(vec![1; len])); + assert_eq!( + WebhookSecret::from_existing(&encoded).is_ok(), + (24..=64).contains(&len) + ); + } + assert!(WebhookSecret::from_existing("not_a_secret").is_err()); + assert!(WebhookSecret::from_existing("whsec_!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!").is_err()); + let secret = WebhookSecret::generate(); + assert_eq!(secret.0.len(), 32); + assert_eq!(format!("{secret:?}"), "WebhookSecret([redacted])"); + let request = crate::model::CustomRequest::new( + "events/subscribe", + Some(json!({"delivery": {"secret": "whsec_example"}})), + ); + assert!(!format!("{request:?}").contains("whsec_example")); + } + + #[test] + fn verifies_raw_bytes_with_multiple_keys_and_versions() { + let old = WebhookSecret::generate(); + let new = WebhookSecret::generate(); + let bad = WebhookSecret::generate(); + let id = "msg_verification_example"; + let seconds = 1649367553_i64; + let timestamp = seconds.to_string(); + let now = |offset| DateTime::from_timestamp(seconds + offset, 0).unwrap(); + let body = br#"{ "type": "verification", "challenge": "sample" }"#; + let signature = format!( + "v1a,unused {} {}", + new.signature(id, ×tamp, body), + old.signature(id, ×tamp, body), + ); + let mut headers = HeaderMap::new(); + headers.insert("webhook-id", id.parse().unwrap()); + headers.insert("x-mcp-subscription-id", "sub_abc".parse().unwrap()); + headers.insert("webhook-timestamp", timestamp.parse().unwrap()); + headers.insert("webhook-signature", signature.parse().unwrap()); + let receipt = + verify_webhook(&headers, body, &[bad.clone(), old.clone()], now(-300)).unwrap(); + assert_eq!(receipt.webhook_id, id); + assert_eq!(receipt.subscription_id, "sub_abc"); + assert_eq!(receipt.matched_secret, 1); + let WebhookMessage::Verification { challenge } = receipt.message else { + panic!("expected challenge") + }; + assert_eq!( + Value::Object(challenge_response(&challenge)), + json!({"challenge": "sample"}) + ); + assert!(verify_webhook(&headers, body, std::slice::from_ref(&new), now(300)).is_ok()); + for offset in [-301, 301] { + assert!( + verify_webhook(&headers, body, std::slice::from_ref(&old), now(offset)).is_err() + ); + } + assert!(verify_webhook(&headers, body, &[bad], now(0)).is_err()); + assert!(verify_webhook(&headers, &body[1..], &[old], now(0)).is_err()); + } + + #[test] + fn authenticates_future_controls_and_tolerates_missing_or_null_gap_cursor() { + let secret = WebhookSecret::generate(); + let id = "msg_control_example"; + let now = DateTime::from_timestamp(1649367553, 0).unwrap(); + let timestamp = now.timestamp().to_string(); + let mut headers = HeaderMap::new(); + headers.insert("webhook-id", id.parse().unwrap()); + headers.insert("x-mcp-subscription-id", "sub_abc".parse().unwrap()); + headers.insert("webhook-timestamp", timestamp.parse().unwrap()); + for (body, unknown) in [ + (br#"{"type":"future"}"#.as_slice(), true), + (br#"{"type":"gap"}"#.as_slice(), false), + (br#"{"type":"gap","cursor":null}"#.as_slice(), false), + ] { + headers.insert( + "webhook-signature", + secret.signature(id, ×tamp, body).parse().unwrap(), + ); + let got = verify_webhook(&headers, body, std::slice::from_ref(&secret), now).unwrap(); + if unknown { + assert!(matches!(got.message, WebhookMessage::UnknownControl)); + } else { + assert!(matches!(got.message, WebhookMessage::Gap { cursor: None })); + } + } + } +} diff --git a/crates/rmcp/src/events/webhook/rpc.rs b/crates/rmcp/src/events/webhook/rpc.rs new file mode 100644 index 000000000..3cd960715 --- /dev/null +++ b/crates/rmcp/src/events/webhook/rpc.rs @@ -0,0 +1,199 @@ +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use zeroize::Zeroizing; + +#[cfg(feature = "client")] +use super::WebhookSecret; +use crate::model::{JsonObject, ResultType}; + +pub(in crate::events) const SUBSCRIBE: &str = "events/subscribe"; +pub(in crate::events) const UNSUBSCRIBE: &str = "events/unsubscribe"; + +/// Lifetime suggested to the webhook server. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum WebhookTtl { + /// Omit the suggestion and use the server's default. + #[default] + Default, + /// Request a grant without expiry. The server can grant a finite lifetime. + NoExpiry, + /// Suggest a finite lifetime, in milliseconds. + Milliseconds(u64), +} + +impl WebhookTtl { + fn is_default(&self) -> bool { + *self == Self::Default + } +} + +impl Serialize for WebhookTtl { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Milliseconds(ms) => serializer.serialize_u64(*ms), + _ => serializer.serialize_none(), + } + } +} + +impl<'de> Deserialize<'de> for WebhookTtl { + fn deserialize>(deserializer: D) -> Result { + Ok(Option::::deserialize(deserializer)?.map_or(Self::NoExpiry, Self::Milliseconds)) + } +} + +/// Inputs for subscribing or refreshing a webhook. +#[cfg(feature = "client")] +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct WebhookOptions { + /// HTTPS callback URL. + pub url: String, + /// Key the endpoint expects. Supply a replacement here to rotate it. + pub secret: WebhookSecret, + /// Desired grant; the response deadline is authoritative. + pub ttl: WebhookTtl, + /// Last safe checkpoint, or `None` to start from now. + pub cursor: Option, + /// Optional age floor for a resumed grant. + pub max_age_ms: Option, +} + +#[cfg(feature = "client")] +impl WebhookOptions { + /// Start from now with the server's default lifetime. + pub fn new(url: impl Into, secret: WebhookSecret) -> Self { + Self { + url: url.into(), + secret, + ttl: WebhookTtl::Default, + cursor: None, + max_age_ms: None, + } + } +} + +/// The authoritative webhook grant returned by a subscribe or refresh. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct WebhookSubscription { + #[serde(default, deserialize_with = "crate::events::wire::complete")] + pub(in crate::events) result_type: ResultType, + /// Stable server-derived routing handle (not a credential). + pub id: String, + /// Expiry. `None` is a grant with no expiry. + #[serde(deserialize_with = "Deserialize::deserialize")] + pub refresh_before: Option>, + /// Latest safe checkpoint. Do not persist a null checkpoint. + pub cursor: Option, + /// The server had to start after the requested checkpoint. + #[serde(default)] + pub truncated: bool, + /// Optional delivery health snapshot. + #[serde(skip_serializing_if = "Option::is_none")] + pub delivery_status: Option, +} + +/// Delivery health reported by the webhook server. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct WebhookSubscriptionStatus { + /// Whether delivery is active. + pub active: bool, + /// Time of the last successful acknowledgement. + pub last_delivery_at: Option>, + /// Fixed error category, not endpoint response content. + pub last_error: Option, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(in crate::events) struct SubscribeParams { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub arguments: Option, + pub delivery: SubscribeDelivery, + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_age_ms: Option, + #[serde(default, skip_serializing_if = "WebhookTtl::is_default")] + pub ttl_ms: WebhookTtl, +} + +#[derive(Serialize, Deserialize)] +pub(in crate::events) struct SubscribeDelivery { + pub mode: SubscribeMode, + pub url: String, + pub secret: Zeroizing, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(in crate::events) enum SubscribeMode { + Webhook, +} + +#[derive(Serialize, Deserialize)] +pub(in crate::events) struct UnsubscribeParams { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub arguments: Option, + pub delivery: UnsubscribeDelivery, +} + +#[derive(Serialize, Deserialize)] +pub(in crate::events) struct UnsubscribeDelivery { + pub url: String, +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::*; + + #[test] + fn omitted_null_and_finite_ttl_remain_distinct() { + let mut request = json!({ + "name": "example", + "delivery": {"mode": "webhook", "url": "https://example.net", "secret": "fixture"} + }); + let omitted: SubscribeParams = serde_json::from_value(request.clone()).unwrap(); + assert_eq!(omitted.ttl_ms, WebhookTtl::Default); + assert!( + serde_json::to_value(omitted) + .unwrap() + .get("ttlMs") + .is_none() + ); + for (value, hint) in [ + (Value::Null, WebhookTtl::NoExpiry), + (json!(123), WebhookTtl::Milliseconds(123)), + ] { + request["ttlMs"] = value.clone(); + let params: SubscribeParams = serde_json::from_value(request.clone()).unwrap(); + assert_eq!(params.ttl_ms, hint); + assert_eq!(serde_json::to_value(params).unwrap()["ttlMs"], value); + } + } + + #[test] + fn missing_result_type_means_complete_but_grant_deadline_is_required() { + let mut wire = json!({"id": "sub_fixture", "refreshBefore": null}); + let result: WebhookSubscription = serde_json::from_value(wire.clone()).unwrap(); + assert!(result.result_type.is_complete()); + assert!(result.refresh_before.is_none()); + assert!( + serde_json::from_value::( + json!({"id":"sub_fixture", "refreshBefore":null, "resultType":"task"}) + ) + .is_err() + ); + wire.as_object_mut().unwrap().remove("refreshBefore"); + assert!(serde_json::from_value::(wire).is_err()); + } +} diff --git a/crates/rmcp/src/events/wire.rs b/crates/rmcp/src/events/wire.rs new file mode 100644 index 000000000..c1b09c480 --- /dev/null +++ b/crates/rmcp/src/events/wire.rs @@ -0,0 +1,524 @@ +//! Catalog, poll, and error types for the Events Beta. + +use std::sync::Arc; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::model::{ErrorCode, ErrorData, JsonObject, ResultType}; + +/// Delivery mode advertised for an event type. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub enum DeliveryMode { + /// One-shot cursor-based reads. + Poll, + /// An active transport stream. + Push, + /// Delivery to a registered HTTPS endpoint. + Webhook, +} + +#[cfg(any(feature = "client", feature = "server"))] +pub(super) fn not_found() -> EventsError { + EventsError::NotFound { + kind: Some("event".into()), + } +} + +#[cfg(any(feature = "client", feature = "server"))] +pub(super) fn unsupported(mode: DeliveryMode) -> EventsError { + EventsError::Unsupported { + feature: "deliveryMode".into(), + value: Some(json!(mode)), + reason: None, + } +} + +#[cfg(any(feature = "client", feature = "server"))] +pub(super) fn terminal(error: &EventsError) -> bool { + matches!( + error, + EventsError::NotFound { .. } | EventsError::Forbidden { .. } + ) || matches!(error, EventsError::Unsupported { reason: Some(reason), .. } if reason == "schema_changed") +} + +/// A wire catalog entry, separate from the server's registration policy. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct EventDescriptor { + /// Event type name. + pub name: String, + /// Human-readable description, empty when omitted by the peer. + #[serde(default)] + pub description: String, + /// Recognized modes. An unknown-only peer entry has an empty list here. + #[serde(deserialize_with = "read_delivery")] + pub delivery: Vec, + /// Subscription argument schema. + pub input_schema: Arc, + /// Occurrence data schema. + pub payload_schema: Arc, + /// Optional catalog metadata. + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +impl EventDescriptor { + /// Construct a wire descriptor for use with a raw server registration. + pub fn new( + name: impl Into, + description: impl Into, + delivery: Vec, + input_schema: Arc, + payload_schema: Arc, + ) -> Self { + Self { + name: name.into(), + description: description.into(), + delivery, + input_schema, + payload_schema, + meta: None, + } + } +} + +fn read_delivery<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let modes = Vec::::deserialize(deserializer)?; + if modes.is_empty() { + return Err(serde::de::Error::custom("empty Events delivery")); + } + Ok(modes + .into_iter() + .filter_map(|mode| match mode.as_str() { + "poll" => Some(DeliveryMode::Poll), + "push" => Some(DeliveryMode::Push), + "webhook" => Some(DeliveryMode::Webhook), + _ => None, + }) + .collect()) +} + +/// One upstream event delivered to a subscriber. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct EventOccurrence { + /// Stable identifier used for deduplication within a subscription. + pub event_id: String, + /// Event type name. + pub name: String, + /// When the event occurred, in UTC. + #[serde(serialize_with = "utc_timestamp")] + pub timestamp: DateTime, + /// Object payload matching the advertised schema. + pub data: JsonObject, + /// Optional occurrence metadata. + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, + /// Optional position after this event. Poll replies carry a page cursor instead. + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, +} + +impl EventOccurrence { + /// Construct an occurrence without item cursor or metadata. + pub fn new( + event_id: impl Into, + name: impl Into, + timestamp: DateTime, + data: JsonObject, + ) -> Self { + Self { + event_id: event_id.into(), + name: name.into(), + timestamp, + data, + meta: None, + cursor: None, + } + } +} + +fn utc_timestamp( + time: &DateTime, + serializer: S, +) -> Result { + serializer.serialize_str(&time.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true)) +} + +pub(super) fn complete<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + let result_type = ResultType::deserialize(deserializer)?; + if result_type.is_complete() { + Ok(result_type) + } else { + Err(serde::de::Error::custom( + "expected a complete Events result", + )) + } +} + +/// One page of a peer's catalog. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct ListEventsResult { + #[serde(default, deserialize_with = "complete")] + pub(super) result_type: ResultType, + /// Catalog entries on this page. + #[cfg_attr(feature = "client", serde(deserialize_with = "read_catalog"))] + pub events: Vec, + /// Opaque catalog cursor; absent at the last page. + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Optional result metadata. + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +#[cfg(feature = "client")] +fn read_catalog<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Ok(Vec::::deserialize(deserializer)? + .into_iter() + .filter_map(|item| { + let name = item + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + match serde_json::from_value::(item) { + Ok(descriptor) => { + if let Err(reason) = + crate::transport::common::mcp_headers::validate_param_header_annotations( + &descriptor.input_schema, + ) + { + tracing::warn!(event = %name, "invalid x-mcp-header annotations: {reason}"); + None + } else { + Some(descriptor) + } + } + Err(_) => { + tracing::warn!(event = %name, "ignoring malformed event descriptor"); + None + } + } + }) + .collect()) +} + +/// Arguments for a one-shot cursor-based event read. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct PollParams { + /// Event type to read. + pub name: String, + /// Subscription arguments; absence means an empty object. + #[serde(skip_serializing_if = "Option::is_none")] + pub arguments: Option, + /// Saved replay position; absence starts at the current head. + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + /// Optional replay age limit, in milliseconds. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_age_ms: Option, + /// Optional positive cap on returned occurrences. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_events: Option, +} + +impl PollParams { + /// Start from the current head with empty arguments and server defaults. + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + arguments: None, + cursor: None, + max_age_ms: None, + max_events: None, + } + } +} + +pub(super) const DEFAULT_POLL_MS: u64 = 30_000; +fn default_poll_ms() -> u64 { + DEFAULT_POLL_MS +} + +/// One page of events and its checkpoint. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct PollResult { + #[serde(default, deserialize_with = "complete")] + pub(super) result_type: ResultType, + /// Occurrences in delivery order. An unparseable occurrence rejects the + /// entire page, including its checkpoint. + pub events: Vec, + /// Checkpoint to persist after consuming this page, if supplied. + #[serde(skip_serializing_if = "Option::is_none")] + pub cursor: Option, + /// Whether replay advanced across a gap. + #[serde(default)] + pub truncated: bool, + /// Whether more work remains after this page. + #[serde(default)] + pub has_more: bool, + /// Suggested delay after draining the backlog, in milliseconds. + #[serde(default = "default_poll_ms")] + pub next_poll_ms: u64, + /// Optional result metadata. + #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")] + pub meta: Option, +} + +const NOT_FOUND: ErrorCode = ErrorCode(-32023); +const FORBIDDEN: ErrorCode = ErrorCode(-32024); +const RESOURCE_EXHAUSTED: ErrorCode = ErrorCode(-32025); +const UNSUPPORTED: ErrorCode = ErrorCode(-32026); + +/// Local, remote, or transport failure from an Events operation. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum EventsError { + /// Events or the requested method is unavailable. + #[error("Events method unavailable")] + MethodNotFound, + /// Invalid request parameters or event data. + #[error("{0}")] + InvalidParams(String), + /// Routing headers do not match the request body. + #[error("{0}")] + HeaderMismatch(String), + /// The event type or subscription does not exist. + #[error("event or subscription not found")] + NotFound { + /// Optional discriminator (`event` or `subscription`). + kind: Option, + }, + /// The caller is not authorized. + #[error("Events access forbidden")] + Forbidden { + /// Optional safe-to-expose reason. + reason: Option, + }, + /// A source or server reached a fixed limit. + #[error("Events resource limit exceeded: {limit}")] + ResourceExhausted { + /// Name of the limited resource. + limit: String, + /// Maximum supported value, if available. + max: Option, + }, + /// An operation or schema is not supported. + #[error("unsupported Events feature: {feature}")] + Unsupported { + /// Wire feature or schema that is unsupported. + feature: String, + /// Requested value, if available. + value: Option, + /// Optional machine-readable reason. + reason: Option, + }, + /// Preserve the original JSON-RPC error. + #[error("{0}")] + Remote(Box), + /// Failure in the client service or transport. + #[cfg(feature = "client")] + #[error(transparent)] + Service(Box), + /// The peer sent the wrong result family or malformed contents. + #[cfg(feature = "client")] + #[error("invalid Events response")] + UnexpectedResponse, +} + +impl From for ErrorData { + fn from(error: EventsError) -> Self { + let message = error.to_string(); + let (code, data) = match error { + EventsError::Remote(error) => return *error, + EventsError::MethodNotFound => (ErrorCode::METHOD_NOT_FOUND, None), + EventsError::InvalidParams(_) => (ErrorCode::INVALID_PARAMS, None), + EventsError::HeaderMismatch(_) => (ErrorCode::HEADER_MISMATCH, None), + EventsError::NotFound { kind } => (NOT_FOUND, kind.map(|kind| json!({ "kind": kind }))), + EventsError::Forbidden { reason } => { + (FORBIDDEN, reason.map(|reason| json!({ "reason": reason }))) + } + EventsError::ResourceExhausted { limit, max } => ( + RESOURCE_EXHAUSTED, + Some(max.map_or_else( + || json!({ "limit": limit }), + |max| json!({ "limit": limit, "max": max }), + )), + ), + EventsError::Unsupported { + feature, + value, + reason, + } => { + let mut data = JsonObject::new(); + data.insert("feature".into(), Value::String(feature)); + if let Some(value) = value { + data.insert("value".into(), value); + } + if let Some(reason) = reason { + data.insert("reason".into(), Value::String(reason)); + } + (UNSUPPORTED, Some(Value::Object(data))) + } + #[cfg(feature = "client")] + _ => (ErrorCode::INTERNAL_ERROR, None), + }; + Self::new(code, message, data) + } +} + +impl From for EventsError { + fn from(error: ErrorData) -> Self { + let get = |key| error.data.as_ref().and_then(|data| data.get(key)); + let string = |key| get(key).and_then(Value::as_str).map(str::to_owned); + match error.code { + ErrorCode::METHOD_NOT_FOUND => Self::MethodNotFound, + ErrorCode::INVALID_PARAMS => Self::InvalidParams(error.message.into_owned()), + ErrorCode::HEADER_MISMATCH => Self::HeaderMismatch(error.message.into_owned()), + NOT_FOUND => Self::NotFound { + kind: string("kind"), + }, + FORBIDDEN => Self::Forbidden { + reason: string("reason"), + }, + RESOURCE_EXHAUSTED => match string("limit") { + Some(limit) => Self::ResourceExhausted { + limit, + max: get("max").and_then(Value::as_u64), + }, + None => Self::Remote(Box::new(error)), + }, + UNSUPPORTED => match string("feature") { + Some(feature) => Self::Unsupported { + feature, + value: get("value").cloned(), + reason: string("reason"), + }, + None => Self::Remote(Box::new(error)), + }, + _ => Self::Remote(Box::new(error)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cursor_defaults_and_completion() { + let params: PollParams = + serde_json::from_value(json!({"name":"event","cursor":null})).unwrap(); + assert!(params.cursor.is_none()); + assert!( + serde_json::to_value(params) + .unwrap() + .get("cursor") + .is_none() + ); + let result: PollResult = serde_json::from_value(json!({ + "resultType":"complete","events":[],"cursor":null + })) + .unwrap(); + assert_eq!( + serde_json::to_value(result).unwrap(), + json!({ + "resultType":"complete","events":[],"truncated":false,"hasMore":false,"nextPollMs":30000 + }) + ); + assert!( + serde_json::from_value::(json!({"events":[]})) + .unwrap() + .result_type + .is_complete() + ); + assert!( + serde_json::from_value::(json!({"events":[]})) + .unwrap() + .result_type + .is_complete() + ); + assert!( + serde_json::from_value::(json!({"events":[],"resultType":"task"})).is_err() + ); + assert!( + serde_json::from_value::(json!({ + "resultType":"complete","events":[],"hasMore":null + })) + .is_err() + ); + } + + #[test] + fn catalog_requires_object_schemas_and_ignores_unknown_modes() { + let descriptor: EventDescriptor = serde_json::from_value(json!({ + "name":"x","delivery":["future","poll"],"inputSchema":{},"payloadSchema":{} + })) + .unwrap(); + assert_eq!(descriptor.delivery, [DeliveryMode::Poll]); + assert_eq!(serde_json::to_value(descriptor).unwrap()["description"], ""); + for value in [ + json!({"name":"x","delivery":[],"inputSchema":{},"payloadSchema":{}}), + json!({"name":"x","delivery":["poll"],"inputSchema":false,"payloadSchema":{}}), + json!({"name":"x","delivery":["poll"],"inputSchema":{}}), + ] { + assert!(serde_json::from_value::(value).is_err()); + } + } + + #[cfg(feature = "client")] + #[test] + fn malformed_timestamp_rejects_the_page_and_its_checkpoint() { + let occurrence = + |id, timestamp| json!({"eventId": id,"name":"x","timestamp":timestamp,"data":{}}); + let result = serde_json::from_value::(json!({ + "resultType":"complete","cursor":"resume","events":[ + occurrence("iso-basic","20261124T120000Z"), occurrence("good","2026-11-24T12:00:00Z") + ] + })); + assert!( + result.is_err(), + "must not expose a cursor past an unparsed occurrence: {result:?}" + ); + } + + #[test] + fn errors_preserve_codes_and_data() { + for (code, data) in [ + (NOT_FOUND, json!({"kind":"event"})), + (FORBIDDEN, json!({"reason":"revoked"})), + (RESOURCE_EXHAUSTED, json!({"limit":"eventBytes","max":5})), + ( + UNSUPPORTED, + json!({"feature":"inputSchema","reason":"schema_changed"}), + ), + (ErrorCode(-32085), json!([5, 2])), + ] { + let original = ErrorData::new(code, "error", Some(data.clone())); + let decoded = ErrorData::from(EventsError::from(original)); + assert_eq!(decoded.code, code); + assert_eq!(decoded.data, Some(data)); + } + let invalid = ErrorData::new(ErrorCode::INVALID_PARAMS, "invalid request", None); + assert_eq!(EventsError::from(invalid).to_string(), "invalid request"); + } +} diff --git a/crates/rmcp/src/handler/server.rs b/crates/rmcp/src/handler/server.rs index 46f87b1a4..7f6374969 100644 --- a/crates/rmcp/src/handler/server.rs +++ b/crates/rmcp/src/handler/server.rs @@ -135,11 +135,34 @@ impl Service for H { ClientRequest::InitializeRequest(request) => self .initialize(request.params, context) .await - .map(ServerResult::InitializeResult), - ClientRequest::DiscoverRequest(_request) => self - .discover(context) - .await - .map(ServerResult::DiscoverResult), + .map(|response| { + #[cfg(feature = "events")] + let response = { + let mut response = response; + crate::events::server::set_advertisement( + self.events(), + &mut response.capabilities, + false, + ); + response + }; + ServerResult::InitializeResult(response) + }), + ClientRequest::DiscoverRequest(_request) => { + self.discover(context).await.map(|response| { + #[cfg(feature = "events")] + let response = { + let mut response = response; + crate::events::server::set_advertisement( + self.events(), + &mut response.capabilities, + is_2026_07_28_or_later && requires_request_metadata, + ); + response + }; + ServerResult::DiscoverResult(response) + }) + } ClientRequest::PingRequest(_request) => { if !legacy_request { Err(McpError::method_not_found::()) @@ -180,12 +203,38 @@ impl Service for H { Err(McpError::method_not_found::()) } else { let requested = request.params.notifications; - let Some(candidate) = self.accepted_subscription_filter(&requested) else { + let candidate = self.accepted_subscription_filter(&requested); + #[cfg(feature = "events")] + let events = self.events(); + #[cfg(feature = "events")] + let (candidate, watcher) = { + let mut candidate = candidate; + let mut watcher = None; + if let Some(events) = events + && is_2026_07_28_or_later + && requested.events_list_changed == Some(true) + { + candidate.get_or_insert_default().events_list_changed = Some(true); + watcher = Some((events, events.revision())); + } + (candidate, watcher) + }; + let Some(candidate) = candidate else { return Err( McpError::method_not_found::(), ); }; let server_info = self.get_info(); + #[cfg(feature = "events")] + let server_info = { + let mut info = server_info; + crate::events::server::set_advertisement( + events, + &mut info.capabilities, + is_2026_07_28_or_later, + ); + info + }; let advertised = requested.supported_by(&server_info.capabilities); let handler_accepted = requested.intersection(&candidate); let accepted = handler_accepted.intersection(&advertised); @@ -206,7 +255,22 @@ impl Service for H { SubscriptionContext::establish(context, requested, accepted).await?; // The 2026-07-28 schema defines a final result for graceful // server teardown; explicit stdio cancellation remains a notification. - self.listen(subscription).await.map(|()| { + #[cfg(feature = "events")] + let listener = if let Some((events, revision)) = watcher { + let sink = subscription.sink().clone(); + let listener = self.listen(subscription); + tokio::pin!(listener); + tokio::select! { + biased; + result = &mut listener => result, + () = events.notify(revision, sink) => listener.await, + } + } else { + self.listen(subscription).await + }; + #[cfg(not(feature = "events"))] + let listener = self.listen(subscription).await; + listener.map(|()| { let mut result = SubscriptionsListenResult::complete(subscription_id); result.meta.set_server_info(server_implementation); ServerResult::SubscriptionsListenResult(result) @@ -251,10 +315,24 @@ impl Service for H { .list_tools(request.params, context) .await .map(ServerResult::ListToolsResult), - ClientRequest::CustomRequest(request) => self - .on_custom_request(request, context) - .await - .map(ServerResult::CustomResult), + ClientRequest::CustomRequest(request) => { + #[cfg(feature = "events")] + if request.method.starts_with("events/") + && let Some(events) = self.events() + { + if !is_2026_07_28_or_later || !requires_request_metadata { + return Err(crate::events::wire::EventsError::MethodNotFound.into()); + } + return events + .dispatch(request, context) + .await + .map(ServerResult::CustomResult) + .map_err(Into::into); + } + self.on_custom_request(request, context) + .await + .map(ServerResult::CustomResult) + } ClientRequest::GetTaskRequest(request) => { validate_tasks_capability::(self, &context)?; self.get_task(request.params, context) @@ -539,6 +617,9 @@ macro_rules! server_handler_methods { /// intersects the returned filter with both `requested` and the notification /// capabilities advertised by [`Self::get_info`] before acknowledging it. /// Categories that were not requested or advertised are always removed. + /// When `Self::events` installs the SDK Events runtime, it owns + /// `events_list_changed`: it accepts the category when requested on a + /// supported revision, even when this method returns `None`. fn accepted_subscription_filter( &self, requested: &SubscriptionFilter, @@ -635,6 +716,18 @@ macro_rules! server_handler_methods { fn get_tool(&self, _name: &str) -> Option { None } + + /// Install the Events Beta runtime for modern discovery and dispatch. + /// + /// `Some` hands `events/*` to the SDK instead of `on_custom_request`. + /// The SDK generates the capability in modern `server/discover` only + /// and rejects legacy Events requests with JSON-RPC `-32601`. + /// `None` leaves custom dispatch and capability advertisement alone. + #[cfg(feature = "events")] + fn events(&self) -> Option<&crate::events::server::EventsServer> { + None + } + fn on_custom_request( &self, request: CustomRequest, @@ -917,6 +1010,11 @@ macro_rules! impl_server_handler_for_wrapper { (**self).get_tool(name) } + #[cfg(feature = "events")] + fn events(&self) -> Option<&crate::events::server::EventsServer> { + (**self).events() + } + fn on_custom_request( &self, request: CustomRequest, diff --git a/crates/rmcp/src/handler/server/router.rs b/crates/rmcp/src/handler/server/router.rs index c49c40894..817d5ce65 100644 --- a/crates/rmcp/src/handler/server/router.rs +++ b/crates/rmcp/src/handler/server/router.rs @@ -222,13 +222,13 @@ mod tests { router.tool_router.disable_route("my_tool"); assert!(matches!( - recv_notification(&mut rx).await, + recv_notification(&mut rx.messages).await, ServerNotification::ToolListChangedNotification(_) )); router.tool_router.enable_route("my_tool"); assert!(matches!( - recv_notification(&mut rx).await, + recv_notification(&mut rx.messages).await, ServerNotification::ToolListChangedNotification(_) )); } diff --git a/crates/rmcp/src/lib.rs b/crates/rmcp/src/lib.rs index 3be6616ed..1c6107167 100644 --- a/crates/rmcp/src/lib.rs +++ b/crates/rmcp/src/lib.rs @@ -5,6 +5,9 @@ mod error; pub use error::{ErrorData, RmcpError}; +#[cfg(feature = "events")] +pub mod events; + /// Basic data types in MCP specification pub mod model; #[cfg(any(feature = "client", feature = "server"))] diff --git a/crates/rmcp/src/model.rs b/crates/rmcp/src/model.rs index 624c80b4b..2f184e83d 100644 --- a/crates/rmcp/src/model.rs +++ b/crates/rmcp/src/model.rs @@ -1148,7 +1148,7 @@ pub type CancelledNotification = /// /// This preserves the raw `method` name and `params` payload so handlers can /// deserialize them into domain-specific types. -#[derive(Debug, Clone)] +#[derive(Clone, Debug)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")] pub struct CustomNotification { @@ -1184,7 +1184,8 @@ impl CustomNotification { /// /// This preserves the raw `method` name and `params` payload so handlers can /// deserialize them into domain-specific types. -#[derive(Debug, Clone)] +#[derive(Clone)] +#[cfg_attr(not(feature = "events"), derive(Debug))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")] pub struct CustomRequest { @@ -1198,6 +1199,32 @@ pub struct CustomRequest { pub extensions: Extensions, } +#[cfg(feature = "events")] +impl std::fmt::Debug for CustomRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut debug = f.debug_struct("CustomRequest"); + debug.field("method", &self.method); + // A raw JSON-RPC subscribe still carries the signing key in params. + if self.method == "events/subscribe" { + return debug.field("params", &"").finish_non_exhaustive(); + } + debug + .field("params", &self.params) + .field("extensions", &self.extensions) + .finish() + } +} + +#[cfg(all(test, feature = "events"))] +#[test] +fn events_subscribe_debug_redacts_params() { + let params = Some(serde_json::json!({"delivery":{"secret":"whsec_fixture"}})); + let subscribe = CustomRequest::new("events/subscribe", params.clone()); + assert!(!format!("{subscribe:?}").contains("whsec_fixture")); + let unrelated = CustomRequest::new("custom", params); + assert!(format!("{unrelated:?}").contains("whsec_fixture")); +} + impl CustomRequest { pub fn new(method: impl Into, params: Option) -> Self { Self { @@ -2279,6 +2306,10 @@ pub struct SubscriptionFilter { #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(with = "bool"))] pub resources_list_changed: Option, + #[cfg(feature = "events")] + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(feature = "schemars", schemars(with = "bool"))] + pub events_list_changed: Option, #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "schemars", schemars(with = "Vec"))] pub resource_subscriptions: Option>, @@ -2320,6 +2351,10 @@ impl SubscriptionFilter { resources_list_changed: (self.resources_list_changed == Some(true) && other.resources_list_changed == Some(true)) .then_some(true), + #[cfg(feature = "events")] + events_list_changed: (self.events_list_changed == Some(true) + && other.events_list_changed == Some(true)) + .then_some(true), resource_subscriptions, } } @@ -2330,6 +2365,8 @@ impl SubscriptionFilter { (self.tools_list_changed, other.tools_list_changed), (self.prompts_list_changed, other.prompts_list_changed), (self.resources_list_changed, other.resources_list_changed), + #[cfg(feature = "events")] + (self.events_list_changed, other.events_list_changed), ] .into_iter() .all(|(accepted, requested)| accepted != Some(true) || requested == Some(true)); @@ -2365,6 +2402,10 @@ impl SubscriptionFilter { .as_ref() .is_some_and(|resources| resources.list_changed == Some(true))) .then_some(true), + #[cfg(feature = "events")] + events_list_changed: (self.events_list_changed == Some(true) + && crate::events::advertises_list_changes(capabilities)) + .then_some(true), resource_subscriptions: capabilities .resources .as_ref() @@ -2383,6 +2424,13 @@ pub struct SubscriptionFilterBuilder { } impl SubscriptionFilterBuilder { + /// Opt in to `notifications/events/list_changed` from an Events server. + #[cfg(feature = "events")] + pub fn events_list_changed(mut self) -> Self { + self.filter.events_list_changed = Some(true); + self + } + /// Opt in to `notifications/tools/list_changed`. pub fn tools_list_changed(mut self) -> Self { self.filter.tools_list_changed = Some(true); diff --git a/crates/rmcp/src/service.rs b/crates/rmcp/src/service.rs index 4090005e3..e33c26470 100644 --- a/crates/rmcp/src/service.rs +++ b/crates/rmcp/src/service.rs @@ -177,6 +177,10 @@ pub trait ServiceRole: std::fmt::Debug + Send + Sync + 'static + Copy + Clone { None } #[doc(hidden)] + fn outbound_subscription_id(_notification: &Self::Not) -> Option { + None + } + #[doc(hidden)] fn peer_cancels_subscriptions(_peer: &Peer) -> bool { false } @@ -784,10 +788,11 @@ pub(crate) struct ClientRequestMetadata { /// To create a cancellable request, call [`Peer::send_request_with_option`]. pub struct Peer { tx: mpsc::Sender>, + deferred_cancellations: mpsc::UnboundedSender>, request_id_provider: Arc, progress_token_provider: Arc, progress_timeout_watchers: ProgressTimeoutWatchers, - info: Arc>>>, + peer_info: Arc>>>, client_request_metadata: Arc>, inline_protocol_version: Arc>, subscription_channels: Arc>>, @@ -802,10 +807,11 @@ where fn clone(&self) -> Peer { Self { tx: self.tx.clone(), + deferred_cancellations: self.deferred_cancellations.clone(), request_id_provider: self.request_id_provider.clone(), progress_token_provider: self.progress_token_provider.clone(), progress_timeout_watchers: self.progress_timeout_watchers.clone(), - info: self.info.clone(), + peer_info: self.peer_info.clone(), client_request_metadata: self.client_request_metadata.clone(), inline_protocol_version: self.inline_protocol_version.clone(), subscription_channels: self.subscription_channels.clone(), @@ -824,7 +830,10 @@ impl std::fmt::Debug for Peer { } } -type ProxyOutbound = mpsc::Receiver>; +pub(crate) struct ProxyOutbound { + pub(crate) messages: mpsc::Receiver>, + deferred_cancellations: mpsc::UnboundedReceiver>, +} #[derive(Debug, Default)] #[non_exhaustive] @@ -875,20 +884,25 @@ impl Peer { peer_info: Option, ) -> (Peer, ProxyOutbound) { let (tx, rx) = mpsc::channel(Self::CLIENT_CHANNEL_BUFFER_SIZE); + let (deferred_cancellations, cancellation_rx) = mpsc::unbounded_channel(); ( Self { tx, + deferred_cancellations, request_id_provider, progress_token_provider: Arc::new(AtomicU32ProgressTokenProvider::default()), progress_timeout_watchers: Default::default(), - info: Arc::new(std::sync::RwLock::new(peer_info.map(Arc::new))), + peer_info: Arc::new(std::sync::RwLock::new(peer_info.map(Arc::new))), client_request_metadata: Default::default(), inline_protocol_version: Default::default(), subscription_channels: Default::default(), #[cfg(feature = "client")] response_cache: Default::default(), }, - rx, + ProxyOutbound { + messages: rx, + deferred_cancellations: cancellation_rx, + }, ) } pub async fn send_notification(&self, notification: R::Not) -> Result<(), ServiceError> { @@ -952,6 +966,14 @@ impl Peer { request .get_meta_mut() .set_progress_token(progress_token.clone()); + // Reserve capacity before registering anything. Once either route is + // installed, enqueue the request without yielding so a dropped opening + // future cannot leave state behind without returning a handle. + let permit = self + .tx + .reserve() + .await + .map_err(|_| ServiceError::TransportClosed)?; let (responder, receiver) = tokio::sync::oneshot::channel(); let progress_reset_rx = if options.reset_timeout_on_progress && options.timeout.is_some() { let (sender, receiver) = mpsc::channel(1); @@ -967,25 +989,11 @@ impl Peer { self.subscription_channels_write() .insert(id.clone(), channel); } - if self - .tx - .send(PeerSinkMessage::Request { - request, - id: id.clone(), - responder, - }) - .await - .is_err() - { - if progress_reset_rx.is_some() { - self.progress_timeout_watchers - .write() - .await - .remove(&progress_token); - } - self.unregister_subscription(&id); - return Err(ServiceError::TransportClosed); - } + permit.send(PeerSinkMessage::Request { + request, + id: id.clone(), + responder, + }); Ok(RequestHandle { id, rx: receiver, @@ -1022,6 +1030,16 @@ impl Peer { self.subscription_channels_write().remove(id); } + #[cfg(all(test, feature = "events", feature = "client", feature = "server"))] + pub(crate) async fn reserve_outbound_capacity(&self) -> impl Drop + '_ { + self.tx.reserve_many(self.tx.max_capacity()).await.unwrap() + } + + #[cfg(all(test, feature = "events", feature = "client", feature = "server"))] + pub(crate) fn has_subscription_channels(&self) -> bool { + !self.subscription_channels_read().is_empty() + } + fn subscription_channels_read( &self, ) -> std::sync::RwLockReadGuard<'_, SubscriptionChannelMap> { @@ -1051,10 +1069,22 @@ impl Peer { extensions: Default::default(), }; let (responder, _receiver) = tokio::sync::oneshot::channel(); - let _ = self.tx.try_send(PeerSinkMessage::Notification { + let message = PeerSinkMessage::Notification { notification: notification.into(), responder, - }); + }; + match self.tx.try_send(message) { + Ok(()) => {} + Err(mpsc::error::TrySendError::Full(message)) => { + // Only in-flight requests reach this queue, at most once each. + if self.deferred_cancellations.send(message).is_err() { + tracing::debug!("dropping cancellation: service closed"); + } + } + Err(mpsc::error::TrySendError::Closed(_)) => { + tracing::debug!("dropping cancellation: service closed"); + } + } } async fn notify_progress_timeout_watcher(&self, progress_token: &ProgressToken) { @@ -1082,12 +1112,15 @@ impl Peer { /// Snapshot of the peer's handshake info. pub fn peer_info(&self) -> Option> { - self.info.read().expect("peer info lock poisoned").clone() + self.peer_info + .read() + .expect("peer info lock poisoned") + .clone() } /// Stores the peer's handshake info, overwriting any previous value. pub fn set_peer_info(&self, info: R::PeerInfo) { - *self.info.write().expect("peer info lock poisoned") = Some(Arc::new(info)); + *self.peer_info.write().expect("peer info lock poisoned") = Some(Arc::new(info)); } #[cfg(feature = "client")] @@ -1384,7 +1417,7 @@ where /// Without the `local` feature this is `tokio::spawn` (requires `Future: Send + 'static`). /// With `local` it uses `tokio::task::spawn_local` (requires only `Future: 'static`). #[cfg(not(feature = "local"))] -fn spawn_service_task(future: F) -> tokio::task::JoinHandle +pub(crate) fn spawn_service_task(future: F) -> tokio::task::JoinHandle where F: Future + Send + 'static, F::Output: Send + 'static, @@ -1393,7 +1426,7 @@ where } #[cfg(feature = "local")] -fn spawn_service_task(future: F) -> tokio::task::JoinHandle +pub(crate) fn spawn_service_task(future: F) -> tokio::task::JoinHandle where F: Future + 'static, F::Output: 'static, @@ -1401,6 +1434,19 @@ where tokio::task::spawn_local(future) } +/// Forward deferred cancellations in order, waiting fairly for outbound capacity. +async fn drain_deferred_cancellations( + tx: &mpsc::Sender>, + mut rx: mpsc::UnboundedReceiver>, +) { + while let Some(message) = rx.recv().await { + if tx.send(message).await.is_err() { + tracing::debug!("dropping deferred cancellation: service closed"); + break; + } + } +} + /// Run the service loop over `transport`. /// /// `initial_messages` are messages the caller already read from `transport` @@ -1412,7 +1458,7 @@ fn serve_inner( service: S, transport: T, peer: Peer, - mut peer_rx: tokio::sync::mpsc::Receiver>, + outbound: ProxyOutbound, initial_messages: VecDeque>, ct: CancellationToken, ) -> RunningService @@ -1445,6 +1491,12 @@ where let peer_return: Peer = peer.clone(); let current_span = tracing::Span::current(); let handle = spawn_service_task(async move { + let ProxyOutbound { + messages: mut peer_rx, + deferred_cancellations, + } = outbound; + let mut cancellation_drain = + Box::pin(drain_deferred_cancellations(&peer.tx, deferred_cancellations)); let mut transport = transport.into_transport(); let mut batch_messages = initial_messages; let mut send_task_set = tokio::task::JoinSet::::new(); @@ -1498,6 +1550,7 @@ where continue } } + _ = &mut cancellation_drain => break QuitReason::Closed, m = send_task_set.join_next(), if !send_task_set.is_empty() => { let Some(result) = m else { continue @@ -1603,6 +1656,14 @@ where notification, responder, }) => { + // Drop queued subscription frames after cancellation. + if let Some(id) = R::outbound_subscription_id(¬ification) + && !local_ct_pool.contains_key(&id) + { + tracing::debug!(%id, "dropping fenced subscription notification: no live local request"); + let _ = responder.send(Ok(())); + continue; + } // catch cancellation notification let mut cancellation_param = None; let notification = match notification.try_into() { @@ -1826,6 +1887,10 @@ where } }; + // No more outbound requests or cancellations will be forwarded. + drop(cancellation_drain); + drop(peer_rx); + // Drain in-flight handler responses before closing the transport. // When stdin EOF or cancellation arrives, spawned handler tasks may still // be finishing. We need to: @@ -1894,6 +1959,218 @@ where } } +#[cfg(all(test, feature = "client"))] +mod outbound_backpressure_tests { + use super::*; + use crate::model::{ + SubscriptionFilter, SubscriptionsListenRequest, SubscriptionsListenRequestParams, + ToolListChangedNotification, + }; + + #[tokio::test(start_paused = true)] + async fn deferred_cancellations_drain_in_order_after_a_full_queue() { + let (peer, outbound) = + Peer::::new(Arc::new(AtomicU32Provider::default()), None); + let ProxyOutbound { + mut messages, + deferred_cancellations, + } = outbound; + let mut handles = Vec::new(); + for _ in 0..64 { + let request = SubscriptionsListenRequest::new(SubscriptionsListenRequestParams::new( + SubscriptionFilter::default(), + )); + let handle = peer + .send_request_with_option(request.into(), PeerRequestOptions::no_options()) + .await + .unwrap(); + handles.push(handle); + } + + let reserved = peer.tx.reserve_many(peer.tx.capacity()).await.unwrap(); + for handle in &handles { + peer.try_cancel_request(handle.id.clone(), None); + } + assert_eq!(deferred_cancellations.len(), handles.len()); + + let mut drain = std::pin::pin!(drain_deferred_cancellations( + &peer.tx, + deferred_cancellations + )); + assert!(futures::poll!(&mut drain).is_pending()); + drop(reserved); + + let receive = async { + for handle in &handles { + let expected = &handle.id; + let Some(PeerSinkMessage::Request { id, .. }) = messages.recv().await else { + panic!("expected queued request {expected} before any cancellation"); + }; + assert_eq!(&id, expected); + } + for handle in handles { + let expected = handle.id; + let Some(PeerSinkMessage::Notification { notification, .. }) = + messages.recv().await + else { + panic!("expected deferred cancellation for {expected}"); + }; + let notification: CancelledNotification = notification.try_into().unwrap(); + assert_eq!(notification.params.request_id, Some(expected)); + } + }; + tokio::time::timeout(Duration::from_secs(5), async { + tokio::select! { + () = receive => {} + () = &mut drain => panic!("cancellation drain exited early"), + } + }) + .await + .expect("deferred cancellations did not drain"); + } + + #[tokio::test] + async fn dropped_listen_open_under_backpressure_leaves_no_registration() { + let (peer, _outbound) = + Peer::::new(Arc::new(AtomicU32Provider::default()), None); + let reserved = peer.tx.reserve_many(peer.tx.max_capacity()).await.unwrap(); + let request = SubscriptionsListenRequest::new(SubscriptionsListenRequestParams::new( + SubscriptionFilter::default(), + )); + let mut opening = Box::pin(peer.send_subscription_request( + request.into(), + PeerRequestOptions::with_timeout(Duration::from_secs(1)).reset_timeout_on_progress(), + 1, + )); + assert!(futures::poll!(&mut opening).is_pending()); + drop(opening); + drop(reserved); + + let mut late: ServerNotification = ToolListChangedNotification { + method: Default::default(), + extensions: Default::default(), + } + .into(); + late.get_meta_mut() + .set_subscription_id(RequestId::Number(0)); + let id = late.get_meta().subscription_id().expect("correlated frame"); + assert!( + peer.subscription_sender(&id).is_none(), + "late notification still has a subscription route for {id}" + ); + assert!(peer.subscription_channels_read().is_empty()); + assert!(peer.progress_timeout_watchers.read().await.is_empty()); + } + + #[cfg(all(feature = "server", feature = "transport-io"))] + async fn listen_pair( + cancelled: CancellationToken, + ) -> ( + RunningService, + Subscription, + tokio::task::JoinHandle<()>, + ) { + use crate::{ClientLifecycleMode, ClientServiceExt, ServerHandler}; + + struct ListenServer(CancellationToken); + + impl ServerHandler for ListenServer { + fn accepted_subscription_filter( + &self, + requested: &SubscriptionFilter, + ) -> Option { + Some(requested.clone()) + } + + async fn listen(&self, context: SubscriptionContext) -> Result<(), McpError> { + context.cancelled().await; + self.0.cancel(); + Ok(()) + } + } + + let (server_io, client_io) = tokio::io::duplex(4096); + let server = tokio::task::spawn_local(async move { + ListenServer(cancelled) + .serve(server_io) + .await + .unwrap() + .waiting() + .await + .unwrap(); + }); + let client = tokio::time::timeout( + Duration::from_secs(5), + ().serve_with_lifecycle( + client_io, + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28], + }, + ), + ) + .await + .expect("stdio startup timed out") + .unwrap(); + let subscription = tokio::time::timeout( + Duration::from_secs(5), + client.listen(SubscriptionFilter::default()), + ) + .await + .expect("listen acknowledgment timed out") + .unwrap(); + (client, subscription, server) + } + + #[cfg(all(feature = "server", feature = "transport-io"))] + #[tokio::test(start_paused = true)] + async fn dropped_listen_under_backpressure_cancels_stdio_handler() { + tokio::task::LocalSet::new() + .run_until(async { + let cancelled = CancellationToken::new(); + let (client, subscription, server) = listen_pair(cancelled.clone()).await; + let reserved = client + .tx + .reserve_many(client.tx.max_capacity()) + .await + .unwrap(); + assert!(!cancelled.is_cancelled()); + + // Saturate capacity through the entire drop, even if the service + // loop runs. Drop outside the runtime as a synchronous caller may. + std::thread::spawn(move || drop(subscription)) + .join() + .unwrap(); + drop(reserved); + + tokio::time::timeout(Duration::from_secs(5), cancelled.cancelled()) + .await + .expect("dropping the listen did not cancel the stdio handler"); + client.cancel().await.unwrap(); + server.await.unwrap(); + }) + .await; + } + + #[cfg(all(feature = "server", feature = "transport-io"))] + #[test] + fn dropping_listen_after_runtime_shutdown_does_not_panic() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .start_paused(true) + .build() + .unwrap(); + let local = tokio::task::LocalSet::new(); + let (client, subscription, _server) = + local.block_on(&runtime, listen_pair(CancellationToken::new())); + drop(local); + drop(runtime); + + assert!(client.tx.is_closed()); + drop(subscription); + drop(client); + } +} + #[cfg(all(test, feature = "server"))] mod sep2260_marker_tests { use std::sync::Arc; @@ -1917,7 +2194,8 @@ mod sep2260_marker_tests { Some(id) => ORIGINATING_REQUEST.scope(id, send).await.unwrap(), None => send.await.unwrap(), }; - let PeerSinkMessage::Request { request, .. } = rx.recv().await.expect("sink message") + let PeerSinkMessage::Request { request, .. } = + rx.messages.recv().await.expect("sink message") else { panic!("expected a request sink message"); }; diff --git a/crates/rmcp/src/service/client.rs b/crates/rmcp/src/service/client.rs index 655d350d9..722eee498 100644 --- a/crates/rmcp/src/service/client.rs +++ b/crates/rmcp/src/service/client.rs @@ -678,6 +678,12 @@ impl Subscription { .resource_subscriptions .as_ref() .is_some_and(|uris| uris.contains(&update.params.uri)), + #[cfg(feature = "events")] + ServerNotification::CustomNotification(notification) + if notification.method == crate::events::LIST_CHANGED => + { + self.acknowledged.events_list_changed == Some(true) + } ServerNotification::SubscriptionsAcknowledgedNotification(_) | ServerNotification::CancelledNotification(_) | ServerNotification::ProgressNotification(_) diff --git a/crates/rmcp/src/service/server.rs b/crates/rmcp/src/service/server.rs index 4e62de63d..1d9484cbf 100644 --- a/crates/rmcp/src/service/server.rs +++ b/crates/rmcp/src/service/server.rs @@ -51,6 +51,10 @@ impl ServiceRole for RoleServer { } } + fn outbound_subscription_id(notification: &Self::Not) -> Option { + notification.get_meta().subscription_id() + } + fn enforce_outbound_request(peer: &Peer) -> Result<(), ServiceError> { // Same order as `RequestContext::protocol_version`: the version the // current request names wins. Outside a handler, fall back to the version @@ -238,6 +242,16 @@ impl SubscriptionSink { "notifications/tasks", )); } + #[cfg(feature = "events")] + ServerNotification::CustomNotification(notification) + if notification.method == crate::events::LIST_CHANGED => + { + if self.accepted.events_list_changed != Some(true) { + return Err(SubscriptionSendError::NotificationNotAccepted( + crate::events::LIST_CHANGED, + )); + } + } ServerNotification::CustomNotification(_) => { return Err(SubscriptionSendError::UnsupportedNotification( "custom notification", @@ -252,6 +266,14 @@ impl SubscriptionSink { Ok(()) } + #[cfg(feature = "events")] + pub(crate) async fn notify_events_list_changed(&self) -> Result<(), SubscriptionSendError> { + self.send(ServerNotification::CustomNotification( + crate::model::CustomNotification::new(crate::events::LIST_CHANGED, None), + )) + .await + } + /// Send `notifications/tools/list_changed`. /// /// # Errors diff --git a/crates/rmcp/src/transport/common.rs b/crates/rmcp/src/transport/common.rs index ffa00e4da..3aa2882a3 100644 --- a/crates/rmcp/src/transport/common.rs +++ b/crates/rmcp/src/transport/common.rs @@ -3,7 +3,11 @@ pub mod server_side_http; pub mod http_header; -#[cfg(any(feature = "client-side-sse", feature = "server-side-http"))] +#[cfg(any( + feature = "client-side-sse", + feature = "server-side-http", + all(feature = "events", any(feature = "server", feature = "client")), +))] pub mod mcp_headers; #[cfg(any( diff --git a/crates/rmcp/src/transport/common/mcp_headers.rs b/crates/rmcp/src/transport/common/mcp_headers.rs index 98828841a..976132325 100644 --- a/crates/rmcp/src/transport/common/mcp_headers.rs +++ b/crates/rmcp/src/transport/common/mcp_headers.rs @@ -11,6 +11,7 @@ use serde_json::Value; +#[cfg(any(feature = "client-side-sse", feature = "server-side-http"))] use super::http_header::{ BASE64_HEADER_PREFIX, BASE64_HEADER_SUFFIX, HEADER_MCP_METHOD, HEADER_MCP_NAME, HEADER_MCP_PARAM_PREFIX, @@ -77,7 +78,7 @@ fn requires_base64(value: &str) -> bool { } /// RFC 9110 §5.6.2 token character. -#[cfg(feature = "client-side-sse")] +#[cfg(any(feature = "client-side-sse", feature = "events"))] fn is_tchar(c: char) -> bool { c.is_ascii_alphanumeric() || matches!( @@ -159,7 +160,7 @@ fn value_at<'a>(arguments: &'a Value, path: &[&str]) -> Option<&'a Value> { /// applied only to primitive (`string`/`integer`/`boolean`) properties reached /// from the root through `properties` keys alone. Returns the offending reason /// on the first violation. -#[cfg(feature = "client-side-sse")] +#[cfg(any(feature = "client-side-sse", feature = "events"))] pub(crate) fn validate_param_header_annotations(input_schema: &JsonObject) -> Result<(), String> { if input_schema.contains_key("x-mcp-header") { return Err("x-mcp-header must annotate a property, not the schema root".to_owned()); @@ -203,7 +204,7 @@ pub(crate) fn validate_param_header_annotations(input_schema: &JsonObject) -> Re /// /// `on_chain` says whether `schema` is the root or a property reached from it /// through `properties` keys alone. -#[cfg(feature = "client-side-sse")] +#[cfg(any(feature = "client-side-sse", feature = "events"))] fn has_off_chain_annotation(schema: &JsonObject, on_chain: bool) -> bool { schema.iter().any(|(key, value)| match key.as_str() { "x-mcp-header" => !on_chain, @@ -218,7 +219,7 @@ fn has_off_chain_annotation(schema: &JsonObject, on_chain: bool) -> bool { } /// Like [`has_off_chain_annotation`] for each value of a name-to-schema map. -#[cfg(feature = "client-side-sse")] +#[cfg(any(feature = "client-side-sse", feature = "events"))] fn schema_map_has_off_chain_annotation(map: &Value, on_chain: bool) -> bool { map.as_object().is_some_and(|map| { map.values() @@ -226,7 +227,7 @@ fn schema_map_has_off_chain_annotation(map: &Value, on_chain: bool) -> bool { }) } -#[cfg(feature = "client-side-sse")] +#[cfg(any(feature = "client-side-sse", feature = "events"))] fn subschema_has_off_chain_annotation(value: &Value, on_chain: bool) -> bool { match value { Value::Object(schema) => has_off_chain_annotation(schema, on_chain), @@ -275,6 +276,15 @@ fn decode_header_value(value: &str) -> Option { pub(crate) fn standard_request_headers( request: &Value, tool_schema: Option<&JsonObject>, +) -> Vec<(http::HeaderName, http::HeaderValue)> { + request_headers(request, tool_schema, None) +} + +#[cfg(feature = "client-side-sse")] +pub(crate) fn request_headers( + request: &Value, + schema: Option<&JsonObject>, + routing_name: Option<&str>, ) -> Vec<(http::HeaderName, http::HeaderValue)> { use http::{HeaderName, HeaderValue}; @@ -294,13 +304,13 @@ pub(crate) fn standard_request_headers( }; push(HEADER_MCP_METHOD, method); - if let Some(name) = extract_name(method, params) { - push(HEADER_MCP_NAME, &encode_header_value(&name)); + let core_name = extract_name(method, params); + if let Some(name) = routing_name.or(core_name.as_deref()) { + push(HEADER_MCP_NAME, &encode_header_value(name)); } - if method == "tools/call" - && let (Some(schema), Some(arguments)) = - (tool_schema, params.and_then(|p| p.get("arguments"))) + if (method == "tools/call" || routing_name.is_some()) + && let (Some(schema), Some(arguments)) = (schema, params.and_then(|p| p.get("arguments"))) { for (path, header) in param_header_annotations(schema) { let Some(arg) = value_at(arguments, &path) else { @@ -340,7 +350,24 @@ pub(crate) fn validate_request_headers( Some(_) => {} } - if let Some(expected) = extract_name(method, params) { + validate_routing_headers( + headers, + method, + params, + extract_name(method, params).as_deref(), + tool_schema.filter(|_| method == "tools/call"), + ) +} + +#[cfg(feature = "server-side-http")] +pub(crate) fn validate_routing_headers( + headers: &http::HeaderMap, + method: &str, + params: Option<&Value>, + name: Option<&str>, + schema: Option<&JsonObject>, +) -> Result<(), String> { + if let Some(expected) = name { match header_str(headers, HEADER_MCP_NAME)? { None => return Err(format!("missing required Mcp-Name header for `{method}`")), Some(raw) => { @@ -355,16 +382,14 @@ pub(crate) fn validate_request_headers( } } - if method == "tools/call" - && let Some(schema) = tool_schema - { + if let Some(schema) = schema { let arguments = params.and_then(|p| p.get("arguments")); for (path, header) in param_header_annotations(schema) { let prop = path.join("."); let full = format!("{HEADER_MCP_PARAM_PREFIX}{header}"); let header_value = header_str(headers, &full)?; let arg = arguments.and_then(|a| value_at(a, &path)); - let body_value = arg.filter(|v| !v.is_null()).and_then(primitive_to_string); + let body_value = arg.and_then(primitive_to_string); match (header_value, body_value) { (None, None) => {} diff --git a/crates/rmcp/src/transport/streamable_http_client.rs b/crates/rmcp/src/transport/streamable_http_client.rs index b0db48f29..c5ea1b4e4 100644 --- a/crates/rmcp/src/transport/streamable_http_client.rs +++ b/crates/rmcp/src/transport/streamable_http_client.rs @@ -54,6 +54,28 @@ fn build_request_headers( if *version >= ProtocolVersion::STANDARD_HEADERS && let Ok(value) = serde_json::to_value(message) { + #[cfg(all(feature = "events", feature = "client"))] + if let ClientJsonRpcMessage::Request(request) = message + && let crate::model::ClientRequest::CustomRequest(custom) = &request.request + && let Some(schema) = custom + .extensions + .get::() + { + headers.retain(|name, _| { + name.as_str() != "mcp-name" && !name.as_str().starts_with("mcp-param-") + }); + let name = custom + .params + .as_ref() + .and_then(|params| params.get("name")) + .and_then(Value::as_str); + headers.extend(mcp_headers::request_headers( + &value, + schema.0.as_deref(), + name, + )); + return headers; + } let schema = value .get("method") .and_then(Value::as_str) diff --git a/crates/rmcp/src/transport/streamable_http_server/session/local.rs b/crates/rmcp/src/transport/streamable_http_server/session/local.rs index a3e6d19f4..3dc2d4fb7 100644 --- a/crates/rmcp/src/transport/streamable_http_server/session/local.rs +++ b/crates/rmcp/src/transport/streamable_http_server/session/local.rs @@ -38,6 +38,9 @@ pub struct LocalSessionManager { impl LocalSessionManager { /// Configure this session manager to use a shared event store. + /// + /// Modern long-lived requests such as `subscriptions/listen` are never + /// persisted and are cancelled when the client disconnects. pub fn with_event_store(mut self, event_store: Arc) -> Self { self.event_store = Some(event_store); self diff --git a/crates/rmcp/src/transport/streamable_http_server/session/never.rs b/crates/rmcp/src/transport/streamable_http_server/session/never.rs index d83031c37..640943f70 100644 --- a/crates/rmcp/src/transport/streamable_http_server/session/never.rs +++ b/crates/rmcp/src/transport/streamable_http_server/session/never.rs @@ -22,6 +22,9 @@ pub struct NeverSessionManager { impl NeverSessionManager { /// Configure resumable SSE storage without enabling sessions. + /// + /// Modern long-lived requests such as `subscriptions/listen` are never + /// persisted and are cancelled when the client disconnects. pub fn with_event_store(mut self, event_store: Arc) -> Self { self.event_store = Some(event_store); self diff --git a/crates/rmcp/src/transport/streamable_http_server/session/store.rs b/crates/rmcp/src/transport/streamable_http_server/session/store.rs index 8b656201c..1c07555d2 100644 --- a/crates/rmcp/src/transport/streamable_http_server/session/store.rs +++ b/crates/rmcp/src/transport/streamable_http_server/session/store.rs @@ -24,6 +24,9 @@ pub type EventStoreError = Box; /// server instances. Event IDs must be globally unique across all streams, and /// events must be committed before [`EventStore::store_event`] returns so the /// returned ID is safe to send to a client. +/// +/// Modern `subscriptions/listen` and SDK `events/stream` requests are not +/// persisted and are cancelled on disconnect. #[async_trait::async_trait] pub trait EventStore: Send + Sync + 'static { /// Persist an event and return the opaque ID clients should receive. diff --git a/crates/rmcp/src/transport/streamable_http_server/tower.rs b/crates/rmcp/src/transport/streamable_http_server/tower.rs index 35f0ecf13..1e7ccc2ad 100644 --- a/crates/rmcp/src/transport/streamable_http_server/tower.rs +++ b/crates/rmcp/src/transport/streamable_http_server/tower.rs @@ -25,10 +25,11 @@ use super::session::{ use crate::{ RoleServer, model::{ - ClientCapabilities, ClientJsonRpcMessage, ClientNotification, ClientRequest, ErrorCode, - ErrorData, GetExtensions, GetMeta, Implementation, InitializeRequest, + ClientCapabilities, ClientJsonRpcMessage, ClientNotification, ClientRequest, ConstString, + ErrorCode, ErrorData, GetExtensions, GetMeta, Implementation, InitializeRequest, InitializeRequestParams, InitializedNotification, JsonObject, JsonRpcError, ProtocolVersion, RequestId, ServerConfig, ServerJsonRpcMessage, ServerResult, + SubscriptionsListenRequestMethod, }, service::{ NotificationContext, RequestContext, Service, negotiate_protocol_version, @@ -475,6 +476,12 @@ fn message_has_per_request_protocol_version(message: &ClientJsonRpcMessage) -> b } } +/// Identifies connection-bound requests: do not persist their SSE events, +/// send priming events or event IDs, and cancel them on response drop. +fn is_long_lived_request(method: &str) -> bool { + method == SubscriptionsListenRequestMethod::VALUE +} + struct NegotiatingStatelessHttpService(S); impl> Service for NegotiatingStatelessHttpService { @@ -1640,8 +1647,11 @@ where first: Option, receiver: tokio::sync::mpsc::Receiver, request_ct: CancellationToken, + long_lived: bool, ) -> BoxResponse { - if let Some(event_store) = self.session_manager.event_store() { + // Long-lived requests are bound to this connection. Do not prime or + // store their SSE frames, and cancel them when the response is dropped. + if !long_lived && let Some(event_store) = self.session_manager.event_store() { let stream = self.persisted_stateless_stream(first, receiver, request_ct, event_store); sse_stream_response( stream, @@ -1670,6 +1680,12 @@ where mut request: crate::model::JsonRpcRequest, parts: http::request::Parts, ) -> HttpResult { + let method = request.request.method(); + #[cfg(feature = "events")] + let sdk_events_stream = method == crate::events::STREAM && service.events().is_some(); + #[cfg(not(feature = "events"))] + let sdk_events_stream = false; + let long_lived = is_long_lived_request(method) || sdk_events_stream; let request_meta_malformed = !request .request .get_meta() @@ -1720,7 +1736,11 @@ where ServerJsonRpcMessage::Response(_) | ServerJsonRpcMessage::Error(_) ); let status = jsonrpc_http_status(&first, request_meta_malformed); - if terminal && (self.config.json_response || status != http::StatusCode::OK) { + if terminal + && (self.config.json_response + || status != http::StatusCode::OK + || (sdk_events_stream && matches!(&first, ServerJsonRpcMessage::Error(_)))) + { // This message is the whole reply, so `receiver` is dropped here and // anything the handler emits afterwards is undeliverable. Cancel it so // a still-running handler stops instead of running on unobserved: its @@ -1731,7 +1751,7 @@ where return jsonrpc_message_response(first, status); } - Ok(self.stateless_sse_response(Some(first), receiver, request_ct)) + Ok(self.stateless_sse_response(Some(first), receiver, request_ct, long_lived)) } /// Looks up `name`'s input schema for SEP-2243 `Mcp-Param-*` validation. @@ -2440,6 +2460,9 @@ where // on service created let _ = service.waiting().await; }); + // This path cannot serve a long-lived listen: ServerHandler + // rejects legacy `subscriptions/listen` with -32601. Both + // SSE branches below can therefore pass `long_lived = false`. if self.config.json_response { // Prefer JSON for a terminal first message. If the handler // emits an intermediate notification or request, preserve @@ -2482,10 +2505,15 @@ where .body(Full::new(Bytes::from(body)).boxed()) .expect("valid response")) } else { - Ok(self.stateless_sse_response(Some(message), receiver, request_ct)) + Ok(self.stateless_sse_response( + Some(message), + receiver, + request_ct, + false, + )) } } else { - Ok(self.stateless_sse_response(None, receiver, request_ct)) + Ok(self.stateless_sse_response(None, receiver, request_ct, false)) } } ClientJsonRpcMessage::Notification(_notification) => { @@ -2572,8 +2600,8 @@ pin_project! { /// Cancels an unpersisted stateless request when its response is dropped. /// /// Persisted requests keep running so another connection can resume them. - /// Without an event store, dropping the stream fires the request's - /// cancellation token. Natural completion disarms the guard. + /// Dropping an unpersisted stream fires the request's cancellation token. + /// Natural completion disarms the guard. struct CancelOnDisconnect { #[pin] inner: S, diff --git a/crates/rmcp/tests/common/events_webhook.rs b/crates/rmcp/tests/common/events_webhook.rs new file mode 100644 index 000000000..07e2565ee --- /dev/null +++ b/crates/rmcp/tests/common/events_webhook.rs @@ -0,0 +1,780 @@ +use std::{convert::Infallible, sync::atomic::AtomicBool}; + +use axum::body::{Body, Bytes, to_bytes}; +use http::{HeaderMap, Request, Response, StatusCode}; +use hyper::{body::Incoming, server::conn::http1, service::service_fn}; +use hyper_util::rt::TokioIo; +use rmcp::events::{ + server::WebhookEgress, + webhook::{ + WebhookMessage, WebhookOptions, WebhookSecret, WebhookSubscription, WebhookTtl, + challenge_response, verify_webhook, + }, +}; +use tokio::sync::{mpsc, oneshot}; +use tokio_rustls::{ + TlsAcceptor, + rustls::{ + self, + pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}, + }, +}; + +use super::*; + +// Regenerate in the fixture directory with OpenSSL 3.6 (zsh/bash): +// openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj '/CN=rmcp webhook fixture CA' -keyout ca.key.pem -out ca.csr +// openssl x509 -req -in ca.csr -signkey ca.key.pem -not_before 20200101000000Z -not_after 20500101000000Z -out ca.pem -extfile <(printf '%s\n' 'basicConstraints=critical,CA:TRUE' 'keyUsage=critical,keyCertSign,cRLSign') +// openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj '/CN=localhost' -keyout server.key.pem -out server.csr +// openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key.pem -not_before 20260501000000Z -not_after 20280723000000Z -out server.pem -extfile <(printf '%s\n' 'basicConstraints=critical,CA:FALSE' 'keyUsage=critical,digitalSignature' 'extendedKeyUsage=serverAuth' 'subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1') +// Checked-in expiry (UTC): CA 2050-01-01; leaf 2028-07-23. +const CA: &[u8] = include_bytes!("../fixtures/events-webhook/ca.pem"); +const KEY: &[u8] = include_bytes!("../fixtures/events-webhook/server.key.pem"); +const CERT: &[u8] = include_bytes!("../fixtures/events-webhook/server.pem"); + +struct Post { + path: String, + headers: HeaderMap, + body: Bytes, + reply: oneshot::Sender>, +} + +impl Post { + fn verify(&self, secret: &WebhookSecret) -> Result { + Ok(verify_webhook( + &self.headers, + &self.body, + std::slice::from_ref(secret), + chrono::Utc::now(), + )? + .message) + } + fn check(&self, secret: &WebhookSecret) -> WebhookMessage { + self.verify(secret).unwrap() + } + fn respond(self, status: StatusCode) { + let mut response = Response::new(Body::empty()); + *response.status_mut() = status; + self.reply.send(response).unwrap(); + } + fn echo(self, secret: &WebhookSecret) { + let WebhookMessage::Verification { challenge } = self.check(secret) else { + panic!("application delivery before verification"); + }; + assert!( + self.headers["webhook-id"] + .to_str() + .unwrap() + .starts_with("msg_verification_") + ); + self.reply + .send(Response::new(Body::from( + serde_json::to_vec(&challenge_response(&challenge)).unwrap(), + ))) + .unwrap(); + } +} + +async fn receive(posts: &mut mpsc::Receiver) -> Post { + tokio::time::timeout(Duration::from_secs(8), posts.recv()) + .await + .expect("callback timed out") + .expect("callback channel closed") +} + +async fn receiver() -> (String, mpsc::Receiver, tokio::task::JoinHandle<()>) { + let (tx, rx) = mpsc::channel(16); + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let tls = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![CertificateDer::from_pem_slice(CERT).unwrap()], + PrivateKeyDer::from_pem_slice(KEY).unwrap(), + ) + .unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("https://{}/hook", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { + let tls = TlsAcceptor::from(Arc::new(tls)); + let mut connections = tokio::task::JoinSet::new(); + loop { + let (socket, _) = tokio::select! { + _ = connections.join_next(), if !connections.is_empty() => continue, + incoming = listener.accept() => incoming.unwrap(), + }; + let (tls, tx) = (tls.clone(), tx.clone()); + connections.spawn(async move { + let Ok(stream) = tls.accept(socket).await else { + return; + }; + let service = service_fn(move |request: Request| { + let tx = tx.clone(); + async move { + assert_eq!(request.method(), "POST"); + let (parts, body) = request.into_parts(); + assert_eq!(&parts.headers["content-type"], "application/json"); + let body = to_bytes(Body::new(body), 256 * 1024).await.unwrap(); + let (reply, response) = oneshot::channel(); + let post = Post { + path: parts.uri.path().into(), + headers: parts.headers, + body, + reply, + }; + let _ = tx.send(post).await; + Ok::<_, Infallible>( + response + .await + .unwrap_or_else(|_| Response::new(Body::empty())), + ) + } + }); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), service) + .await; + }); + } + }); + (url, rx, task) +} + +fn configured_egress(allow_loopback: bool) -> WebhookEgress { + let mut egress = WebhookEgress::default(); + if allow_loopback { + egress + .additional_allowed_networks + .push(("127.0.0.1".parse().unwrap(), 32)); + } + egress + .additional_root_certificates + .push(CertificateDer::from_pem_slice(CA).unwrap().to_vec()); + egress +} + +fn runtime(authenticated: bool, allow_loopback: bool) -> EventsServer { + EventsServer::new() + .with_webhooks( + move |extensions| { + (authenticated + && extensions + .get::() + .and_then(|parts| parts.extensions.get::()) + .is_some()) + .then(|| "fixture-tenant".into()) + }, + configured_egress(allow_loopback), + ) + .unwrap() +} + +fn descriptor() -> Descriptor { + #[derive(schemars::JsonSchema, serde::Deserialize)] + struct Arguments { + #[serde(rename = "region")] + #[schemars(extend("x-mcp-header" = "Region"))] + _region: String, + } + Descriptor::typed::("source", "", [DeliveryMode::Webhook]) +} + +fn args() -> Option { + Some(serde_json::from_value(json!({"region": "test"})).unwrap()) +} + +async fn activate( + api: &EventsClient, + posts: &mut mpsc::Receiver, + options: &WebhookOptions, + before_echo: impl FnOnce(), +) -> WebhookSubscription { + let request = subscribe(api, options.clone()); + tokio::pin!(request); + let post = tokio::select! { + result = &mut request => panic!("subscribe completed before challenge: {result:?}"), + post = receive(posts) => post, + }; + before_echo(); + post.echo(&options.secret); + request.await.unwrap() +} + +async fn subscribe( + api: &EventsClient, + options: WebhookOptions, +) -> Result { + api.subscribe_webhook("source", args(), options).await +} + +async fn access( + runtime: EventsServer, +) -> ( + EventsClient, + CancellationToken, + tokio::task::JoinHandle<()>, + rmcp::service::RunningService, +) { + let (url, stop, server) = server(App(Some(runtime), false)).await; + let peer = connect(url).await; + (EventsClient::new(peer.peer().clone()), stop, server, peer) +} + +async fn close( + peer: rmcp::service::RunningService, + stop: CancellationToken, + server: tokio::task::JoinHandle<()>, +) { + peer.cancel().await.unwrap(); + stop.cancel(); + server.await.unwrap(); +} + +async fn refresh_until( + api: &EventsClient, + options: &WebhookOptions, + predicate: impl Fn(&rmcp::events::webhook::WebhookSubscription) -> bool, +) -> WebhookSubscription { + let grant = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let grant = subscribe(api, options.clone()).await.unwrap(); + if predicate(&grant) { + return grant; + } + tokio::task::yield_now().await; + } + }) + .await; + grant.expect("refresh condition not reached") +} + +#[tokio::test] +async fn authenticated_delivery_rotation_watermark_skip_and_removal() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let auth = Arc::new(AtomicUsize::new(0)); + let authorizations = auth.clone(); + let emit = runtime + .register_emit(descriptor().authorize(move |ctx, params, mode| { + assert_eq!(mode, DeliveryMode::Webhook); + assert_eq!(params["region"], "test"); + let parts = ctx.extensions.get::().unwrap(); + assert_eq!(parts.headers["mcp-name"], "source"); + assert_eq!(parts.headers["mcp-param-region"], "test"); + authorizations.fetch_add(1, Ordering::SeqCst); + std::future::ready(Ok(())) + })) + .unwrap(); + let (api, stop, service, peer) = access(runtime.clone()).await; + assert_eq!( + api.list_page(None).await.unwrap().events[0].delivery, + [DeliveryMode::Webhook] + ); + let mut managed = SubscriptionOptions::default(); + managed.mode = Some(DeliveryMode::Webhook); + assert!(matches!( + api.subscribe("source", args(), managed).await, + Err(EventsError::Unsupported { value: Some(mode), .. }) if mode == "webhook" + )); + assert!(matches!( + api.subscribe("source", args(), SubscriptionOptions::default()) + .await, + Err(EventsError::Unsupported { value: None, .. }) + )); + let secret = WebhookSecret::generate(); + let mut options = WebhookOptions::new(&url, secret.clone()); + options.ttl = WebhookTtl::NoExpiry; + let grant = activate(&api, &mut posts, &options, || { + assert_eq!(auth.load(Ordering::SeqCst), 1); + }) + .await; + assert!(grant.refresh_before.unwrap() > chrono::Utc::now()); + assert!(grant.refresh_before.unwrap() < chrono::Utc::now() + Duration::from_secs(3600)); + let initial = grant.cursor.clone().unwrap(); + let new = WebhookSecret::generate(); + options.secret = new.clone(); + options.cursor = Some("must not reposition live grants".into()); + let refreshed = subscribe(&api, options.clone()).await.unwrap(); + assert_eq!(refreshed.id, grant.id); + assert_eq!(refreshed.cursor.as_deref(), Some(initial.as_str())); + assert!(refreshed.delivery_status.unwrap().active); + + for id in ["first", "second"] { + emit.emit(Some(id.into()), chrono::Utc::now(), JsonObject::new()) + .unwrap(); + } + let (first, second) = { + let a = receive(&mut posts).await; + let b = receive(&mut posts).await; + let WebhookMessage::Occurrence(event) = a.check(&secret) else { + panic!("event expected") + }; + if event.event_id == "first" { + (a, b) + } else { + (b, a) + } + }; + for (id, post) in [("first", &first), ("second", &second)] { + assert_eq!(post.headers["x-mcp-subscription-id"], grant.id); + assert_ne!(post.headers["webhook-id"], id); + for key in [&secret, &new] { + assert!( + matches!(post.check(key), WebhookMessage::Occurrence(event) if event.event_id == id && event.cursor.as_deref() == Some(initial.as_str())) + ); + } + } + second.respond(StatusCode::OK); + let result = refresh_until(&api, &options, |grant| { + grant + .delivery_status + .as_ref() + .unwrap() + .last_delivery_at + .is_some() + }) + .await; + assert_eq!(result.cursor.as_deref(), Some(initial.as_str())); + first.respond(StatusCode::GONE); + let result = refresh_until(&api, &options, |grant| { + grant.cursor.as_deref() != Some(initial.as_str()) + }) + .await; + assert_eq!( + result.delivery_status.unwrap().last_error.as_deref(), + Some("http_4xx") + ); + emit.emit( + Some("too-large-at-receiver".into()), + chrono::Utc::now(), + JsonObject::new(), + ) + .unwrap(); + let rejected = receive(&mut posts).await; + assert!( + matches!(rejected.check(&new), WebhookMessage::Occurrence(event) if event.event_id == "too-large-at-receiver") + ); + rejected.respond(StatusCode::PAYLOAD_TOO_LARGE); + let at = chrono::Utc::now(); + let mut oversized = rmcp::events::wire::EventOccurrence::new( + "oversized", + "source", + at, + serde_json::from_value(json!({"large": ""})).unwrap(), + ); + let padding = 256 * 1024 - serde_json::to_vec(&oversized).unwrap().len(); + oversized + .data + .insert("large".into(), json!("x".repeat(padding))); + // The occurrence fits the producer's budget, but the delivery's + // non-null watermark enlarges its JSON body. + emit.emit(Some(oversized.event_id), at, oversized.data) + .unwrap(); + let gap = receive(&mut posts).await; + assert!( + gap.headers["webhook-id"] + .to_str() + .unwrap() + .starts_with("msg_gap_") + ); + assert!(matches!(gap.check(&new), WebhookMessage::Gap { .. })); + gap.respond(StatusCode::OK); + let result = refresh_until(&api, &options, |grant| grant.truncated).await; + assert_ne!(result.cursor.as_deref(), Some(initial.as_str())); + + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(61)).await; + tokio::time::resume(); + emit.emit( + Some("rotated".into()), + chrono::Utc::now(), + JsonObject::new(), + ) + .unwrap(); + let rotated = receive(&mut posts).await; + assert!( + matches!(rotated.check(&new), WebhookMessage::Occurrence(event) if event.event_id == "rotated") + ); + assert!(rotated.verify(&secret).is_err()); + rotated.respond(StatusCode::OK); + + api.unsubscribe_webhook("source", args(), &url) + .await + .unwrap(); + assert!( + matches!(api.unsubscribe_webhook("source", args(), &url).await, Err(EventsError::NotFound { kind }) if kind.as_deref() == Some("subscription")) + ); + let again = subscribe(&api, WebhookOptions::new(&url, new.clone())) + .await + .unwrap(); + assert_eq!(again.id, grant.id); + runtime.remove("source").unwrap(); + let terminated = receive(&mut posts).await; + assert!( + matches!(terminated.check(&new), WebhookMessage::Terminated { error } if matches!(EventsError::from(error.clone()), EventsError::NotFound { kind } if kind.as_deref() == Some("event"))) + ); + terminated.respond(StatusCode::OK); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn egress_requires_auth_tls_and_consent_and_never_follows_redirects() { + let (url, mut posts, callback) = receiver().await; + for (authenticated, allowed, denied, code) in [ + (false, true, false, -32024), + (true, true, true, -32024), + (true, false, false, -32027), + ] { + let runtime = runtime(authenticated, allowed); + let _emit = runtime + .register_emit(descriptor().authorize(move |_, _, _| async move { + if denied { + Err(EventsError::Forbidden { reason: None }) + } else { + Ok(()) + } + })) + .unwrap(); + let (api, stop, service, peer) = access(runtime).await; + let err = subscribe(&api, WebhookOptions::new(&url, WebhookSecret::generate())) + .await + .unwrap_err(); + assert_eq!(rmcp::ErrorData::from(err).code.0, code); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + } + + let runtime = runtime(true, true); + let _emit = runtime.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(runtime).await; + let secret = WebhookSecret::generate(); + let http = url.replacen("https", "http", 1); + assert!(matches!( + subscribe(&api, WebhookOptions::new(http, secret.clone())).await, + Err(EventsError::InvalidParams(_)) + )); + let (result, ()) = tokio::join!( + subscribe(&api, WebhookOptions::new(&url, secret.clone())), + async { + let post = receive(&mut posts).await; + assert_eq!(post.path, "/hook"); + assert!(matches!( + post.check(&secret), + WebhookMessage::Verification { .. } + )); + let redirect = Response::builder() + .status(StatusCode::TEMPORARY_REDIRECT) + .header("location", url.replace("/hook", "/redirected")) + .body(Body::from("endpoint-private")) + .unwrap(); + post.reply.send(redirect).unwrap(); + } + ); + let error = rmcp::ErrorData::from(result.unwrap_err()); + assert_eq!(error.code.0, -32027); + assert_eq!(error.data, Some(json!({"reason":"challenge_failed"}))); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn concurrent_subscribes_share_one_verification() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let _first = runtime.register_emit(descriptor()).unwrap(); + let entered = Arc::new(tokio::sync::Notify::new()); + let _second = runtime + .register_emit( + Descriptor::typed::("other", "", [DeliveryMode::Webhook]) + .authorize({ + let entered = entered.clone(); + move |_, _, _| { + entered.notify_one(); + std::future::ready(Ok(())) + } + }), + ) + .unwrap(); + let (api, stop, service, peer) = access(runtime).await; + let options = WebhookOptions::new(url, WebhookSecret::generate()); + let first = subscribe(&api, options.clone()); + tokio::pin!(first); + let post = tokio::select! { + result = &mut first => panic!("first subscribe finished before verification: {result:?}"), + post = receive(&mut posts) => post, + }; + let second = api.subscribe_webhook("other", None, options.clone()); + tokio::pin!(second); + tokio::select! { + result = &mut second => panic!("second subscribe finished before verification: {result:?}"), + result = tokio::time::timeout(Duration::from_secs(3), entered.notified()) => result.unwrap(), + } + post.echo(&options.secret); + let (first, second) = tokio::join!(first, second); + assert_ne!(first.unwrap().id, second.unwrap().id); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn callback_and_rpc_timeouts_have_distinct_errors() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let _emit = runtime.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(runtime.clone()).await; + let options = WebhookOptions::new(url, WebhookSecret::generate()); + let request = subscribe(&api, options.clone()); + tokio::pin!(request); + let post = tokio::select! { + result = &mut request => panic!("subscribe finished before verification: {result:?}"), + post = receive(&mut posts) => post, + }; + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(5)).await; + tokio::time::resume(); + let err = rmcp::ErrorData::from(request.await.unwrap_err()); + assert_eq!(err.code.0, -32027); + assert_eq!(err.data, Some(json!({"reason":"timeout"}))); + drop(post); + + let entered = Arc::new(tokio::sync::Notify::new()); + runtime + .replace( + descriptor().authorize({ + let entered = entered.clone(); + move |_, _, _| { + entered.notify_one(); + std::future::pending() + } + }), + Replacement::Additive, + ) + .unwrap(); + let request = subscribe(&api, options); + tokio::pin!(request); + tokio::select! { + result = &mut request => panic!("subscribe finished during authorization: {result:?}"), + result = tokio::time::timeout(Duration::from_secs(3), entered.notified()) => result.unwrap(), + } + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(12)).await; + tokio::time::resume(); + let err = rmcp::ErrorData::from(request.await.unwrap_err()); + assert_eq!(err.code.0, -32603); + assert!(err.data.is_none()); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn configured_dns_and_tls_trust_are_required() { + let (literal, mut posts, callback) = receiver().await; + let hostname = literal.replace("127.0.0.1", "localhost"); + let denied = runtime(true, false); + let _emit = denied.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(denied).await; + let error = subscribe( + &api, + WebhookOptions::new(&hostname, WebhookSecret::generate()), + ) + .await + .unwrap_err(); + let error = rmcp::ErrorData::from(error); + assert_eq!(error.code.0, -32027); + assert_eq!(error.data, Some(json!({"reason":"connection_refused"}))); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + + let mut no_root = configured_egress(true); + no_root.additional_root_certificates.clear(); + let untrusted = EventsServer::new() + .with_webhooks(|_| Some("fixture".into()), no_root) + .unwrap(); + let _emit = untrusted.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(untrusted).await; + let error = subscribe( + &api, + WebhookOptions::new(&hostname, WebhookSecret::generate()), + ) + .await + .unwrap_err(); + assert_eq!( + rmcp::ErrorData::from(error).data, + Some(json!({"reason":"tls_error"})) + ); + assert!(posts.try_recv().is_err()); + close(peer, stop, service).await; + + let trusted = runtime(true, true); + let _emit = trusted.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(trusted).await; + let options = WebhookOptions::new(&hostname, WebhookSecret::generate()); + activate(&api, &mut posts, &options, || {}).await; + api.unsubscribe_webhook("source", args(), &hostname) + .await + .unwrap(); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn revocation_on_refresh_terminates_the_grant() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let allowed = Arc::new(AtomicBool::new(true)); + let on_request = allowed.clone(); + let _emit = runtime + .register_emit(descriptor().authorize(move |_, _, _| { + std::future::ready(if on_request.load(Ordering::SeqCst) { + Ok(()) + } else { + Err(EventsError::Forbidden { + reason: Some("revoked".into()), + }) + }) + })) + .unwrap(); + let (api, stop, service, peer) = access(runtime).await; + let options = WebhookOptions::new(url, WebhookSecret::generate()); + activate(&api, &mut posts, &options, || {}).await; + allowed.store(false, Ordering::SeqCst); + assert!(matches!( + subscribe(&api, options.clone()).await, + Err(EventsError::Forbidden { reason }) if reason.as_deref() == Some("revoked") + )); + let post = receive(&mut posts).await; + assert!(matches!( + post.check(&options.secret), + WebhookMessage::Terminated { error } if error.code.0 == -32024 && error.data == Some(json!({"reason":"revoked"})) + )); + // Keep the old worker's termination POST in flight during the fresh subscribe. + allowed.store(true, Ordering::SeqCst); + let fresh = subscribe(&api, options).await.unwrap(); + assert!(fresh.delivery_status.is_none()); + post.respond(StatusCode::OK); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn unrelated_changes_do_not_restart_webhook_authorization_or_stall_retries() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let emit = runtime.register_emit(descriptor()).unwrap(); + let (api, stop, service, peer) = access(runtime.clone()).await; + let options = WebhookOptions::new(url, WebhookSecret::generate()); + activate(&api, &mut posts, &options, || {}).await; + emit.emit(Some("retry".into()), chrono::Utc::now(), JsonObject::new()) + .unwrap(); + let post = receive(&mut posts).await; + let message = post.headers["webhook-id"].clone(); + + let calls = Arc::new(AtomicUsize::new(0)); + let entered = Arc::new(tokio::sync::Notify::new()); + runtime + .replace( + descriptor().authorize({ + let (calls, entered) = (calls.clone(), entered.clone()); + move |_, _, _| { + calls.fetch_add(1, Ordering::SeqCst); + entered.notify_one(); + std::future::pending() + } + }), + Replacement::Additive, + ) + .unwrap(); + tokio::time::timeout(Duration::from_secs(3), entered.notified()) + .await + .unwrap(); + let _unrelated = runtime + .register_emit(Descriptor::typed::( + "unrelated", + "", + [DeliveryMode::Webhook], + )) + .unwrap(); + post.respond(StatusCode::SERVICE_UNAVAILABLE); + let retry = receive(&mut posts).await; + assert_eq!(retry.headers["webhook-id"], message); + assert_eq!(calls.load(Ordering::SeqCst), 1); + retry.respond(StatusCode::OK); + close(peer, stop, service).await; + callback.abort(); +} + +#[tokio::test] +async fn retry_preserves_message_and_expiry_cancels_worker() { + let (url, mut posts, callback) = receiver().await; + let runtime = runtime(true, true); + let (seen_tx, mut seen_rx) = mpsc::channel(8); + runtime + .register_check(descriptor(), move |ctx, _, query| { + let seen = seen_tx.clone(); + async move { + match query.cursor.as_deref() { + None => { + let mut batch = CheckedBatch::new("head"); + batch.next_poll_ms = Some(1); + Ok(batch) + } + Some("head") => { + let mut batch = CheckedBatch::new("one"); + batch.next_poll_ms = Some(1); + batch.events.push(rmcp::events::wire::EventOccurrence::new( + "upstream", + "source", + chrono::Utc::now(), + JsonObject::new(), + )); + Ok(batch) + } + _ => { + let _ = seen.try_send(ctx.ct.clone()); + std::future::pending().await + } + } + } + }) + .unwrap(); + let (api, stop, service, peer) = access(runtime).await; + let secret = WebhookSecret::generate(); + let mut opts = WebhookOptions::new(url, secret.clone()); + opts.ttl = WebhookTtl::Milliseconds(20_000); + let grant = activate(&api, &mut posts, &opts, || {}).await; + assert_eq!(grant.cursor.as_deref(), Some("head")); + let first = receive(&mut posts).await; + let id = first.headers["webhook-id"].clone(); + let timestamp = first.headers["webhook-timestamp"].clone(); + let signature = first.headers["webhook-signature"].clone(); + let body = first.body.clone(); + first.respond(StatusCode::SERVICE_UNAVAILABLE); + let retry = receive(&mut posts).await; + assert_eq!(retry.headers["webhook-id"], id); + assert_ne!(retry.headers["webhook-timestamp"], timestamp); + assert_ne!(retry.headers["webhook-signature"], signature); + assert_eq!(retry.body, body); + assert!( + matches!(retry.check(&secret), WebhookMessage::Occurrence(event) if event.event_id == "upstream") + ); + retry.respond(StatusCode::OK); + let token = tokio::time::timeout(Duration::from_secs(6), seen_rx.recv()) + .await + .unwrap() + .unwrap(); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(20)).await; + tokio::time::timeout(Duration::from_secs(6), token.cancelled()) + .await + .unwrap(); + tokio::time::resume(); + assert!( + matches!(api.unsubscribe_webhook("source", args(), &opts.url).await, Err(EventsError::NotFound { kind }) if kind.as_deref() == Some("subscription")) + ); + close(peer, stop, service).await; + callback.abort(); +} diff --git a/crates/rmcp/tests/fixtures/events-webhook/ca.pem b/crates/rmcp/tests/fixtures/events-webhook/ca.pem new file mode 100644 index 000000000..b26c1d2ef --- /dev/null +++ b/crates/rmcp/tests/fixtures/events-webhook/ca.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE----- +MIIBbDCCARGgAwIBAgIUPX2o5Gr9FO91a/CpghMDp1nuG+wwCgYIKoZIzj0EAwIw +IjEgMB4GA1UEAwwXcm1jcCB3ZWJob29rIGZpeHR1cmUgQ0EwIBcNMjAwMTAxMDAw +MDAwWhgPMjA1MDAxMDEwMDAwMDBaMCIxIDAeBgNVBAMMF3JtY3Agd2ViaG9vayBm +aXh0dXJlIENBMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUQoUeLUxGsLe22+/ +7uHfgepG+S5e2ACWGy2N706gFBwtVLfkdWSfm6dwk14/lMCpf/sTZX+wJ0zwM86/ +WcUr9qMjMCEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZI +zj0EAwIDSQAwRgIhALqlsjCXtm2FVwdKMN3tp46rLabeA/G5Tvs9LGQCMTcgAiEA +mh9nW5sCpPh84NYdwEDCKUo3kXE7GfkLJAfVfGyUVOs= +-----END CERTIFICATE----- diff --git a/crates/rmcp/tests/fixtures/events-webhook/server.key.pem b/crates/rmcp/tests/fixtures/events-webhook/server.key.pem new file mode 100644 index 000000000..83ffca844 --- /dev/null +++ b/crates/rmcp/tests/fixtures/events-webhook/server.key.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg4FSE9MhFkdFsmm7P +lWHGF/HabfVo58/awlGmE78rAyahRANCAARTx49H8UAzUJowQ9hvvzfZRofLn1oY +DECf5sZVfeiqbWoC1U95qB+tnZ+ruX1UAgDyk3DhHwssdSPPKrEB/qI+ +-----END PRIVATE KEY----- diff --git a/crates/rmcp/tests/fixtures/events-webhook/server.pem b/crates/rmcp/tests/fixtures/events-webhook/server.pem new file mode 100644 index 000000000..32fd7328b --- /dev/null +++ b/crates/rmcp/tests/fixtures/events-webhook/server.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBmzCCAUGgAwIBAgIUfeTvIq1yROtltuVy902UK9s1V5gwCgYIKoZIzj0EAwIw +IjEgMB4GA1UEAwwXcm1jcCB3ZWJob29rIGZpeHR1cmUgQ0EwHhcNMjYwNTAxMDAw +MDAwWhcNMjgwNzIzMDAwMDAwWjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcq +hkjOPQIBBggqhkjOPQMBBwNCAARTx49H8UAzUJowQ9hvvzfZRofLn1oYDECf5sZV +feiqbWoC1U95qB+tnZ+ruX1UAgDyk3DhHwssdSPPKrEB/qI+o2MwYTAMBgNVHRMB +Af8EAjAAMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATAsBgNV +HREEJTAjgglsb2NhbGhvc3SHBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEwCgYIKoZI +zj0EAwIDSAAwRQIgMtd3f7zb496/A0x6R5/ZC8phNcRQq/mxqNUAXtd4AhECIQCL +RNDriawzw3gvDReBgJ2KCwgM3C9KkDOpVAr9u4i3wg== +-----END CERTIFICATE----- diff --git a/crates/rmcp/tests/test_deserialization.rs b/crates/rmcp/tests/test_deserialization.rs index 92c806317..c343764ec 100644 --- a/crates/rmcp/tests/test_deserialization.rs +++ b/crates/rmcp/tests/test_deserialization.rs @@ -123,6 +123,45 @@ mod untagged_server_result { assert_eq!(result.0, payload); } + #[test] + fn events_completion_envelopes_keep_their_json_values() { + let complete = json!({ "resultType": "complete" }); + let cases = [ + ( + "list", + json!(1), + json!({ "resultType": "complete", "events": [], "nextCursor": "page" }), + ), + ( + "poll", + json!(1), + json!({ "resultType": "complete", "events": [], "cursor": null }), + ), + ( + "subscribe", + json!(1), + json!({ "resultType": "complete", "id": "sub_1", "refreshBefore": null }), + ), + ("unsubscribe", json!(1), complete), + ( + "stream", + json!("event-1"), + json!({ "resultType": "complete", "_meta": { "io.modelcontextprotocol/subscriptionId": "event-1" } }), + ), + ]; + for (method, id, result) in cases { + let envelope = json!({ "jsonrpc": "2.0", "id": id, "result": result }); + match (method, parse_result(envelope.clone())) { + ("list" | "poll" | "subscribe", ServerResult::CustomResult(_)) + | ("unsubscribe", ServerResult::TaskAckResult(_)) + | ("stream", ServerResult::SubscriptionsListenResult(_)) => {} + (_, other) => panic!("unexpected {method} result: {other:?}"), + } + let parsed: ServerJsonRpcMessage = serde_json::from_value(envelope.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), envelope); + } + } + #[test] fn call_tool_result_with_meta_deserializes_to_correct_variant() { let result = parse_result(wrap_response(json!({ diff --git a/crates/rmcp/tests/test_events.rs b/crates/rmcp/tests/test_events.rs new file mode 100644 index 000000000..0bf6129ea --- /dev/null +++ b/crates/rmcp/tests/test_events.rs @@ -0,0 +1,1703 @@ +#![cfg(all(feature = "events", feature = "server", feature = "client"))] + +use std::{ + borrow::Cow, + future::{pending, ready}, + sync::Arc, + time::Duration, +}; + +use chrono::Utc; +use futures::StreamExt; +use rmcp::{ + ClientLifecycleMode, ClientServiceExt, ErrorData, RoleClient, ServerHandler, ServiceError, + ServiceExt, + events::{ + client::{EventUpdate, EventsClient, SubscriptionOptions}, + server::{CheckQuery, CheckedBatch, Descriptor, EventsServer, Replacement}, + wire::{DeliveryMode, EventDescriptor, EventOccurrence, EventsError, PollParams}, + }, + model::{ + ClientConfig, ClientRequest, CustomRequest, CustomResult, ErrorCode, GetMeta, JsonObject, + ProtocolVersion, ServerConfig, ServerNotification, ServerResult, SubscriptionFilter, + }, + service::{PeerRequestOptions, RunningService, SubscriptionContext, SubscriptionSendError}, +}; +use serde_json::{Value, json}; + +const EXTENSION: &str = "io.modelcontextprotocol/events"; +type EventContext = rmcp::service::RequestContext; + +fn raw_descriptor( + name: &str, + mode: DeliveryMode, + input: JsonObject, + payload: JsonObject, +) -> Descriptor { + Descriptor::raw( + EventDescriptor::new(name, "", vec![mode], input.into(), payload.into()), + |_| Ok(()), + ) +} + +fn object(value: Value) -> JsonObject { + value.as_object().unwrap().clone() +} + +fn descriptor(name: &str) -> Descriptor { + Descriptor::typed::(name, "test event", [DeliveryMode::Poll]) +} + +fn register(runtime: &EventsServer, name: &str) { + runtime + .register_check(descriptor(name), |_, _, _| { + ready(Ok(CheckedBatch::new("head"))) + }) + .unwrap(); +} + +#[derive(Clone, Default)] +struct App { + events: Option, + app_settings: Option, + custom: bool, + change_during_listen: bool, +} + +impl ServerHandler for App { + fn events(&self) -> Option<&EventsServer> { + self.events.as_ref() + } + + fn get_info(&self) -> ServerConfig { + let mut info = ServerConfig::default(); + let extensions = info.capabilities.extensions.get_or_insert_default(); + extensions.insert("fixture/another-extension".into(), JsonObject::new()); + if let Some(settings) = &self.app_settings { + extensions.insert(EXTENSION.into(), settings.clone()); + } + info + } + + fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> { + Cow::Borrowed(&[ProtocolVersion::V_2026_07_28, ProtocolVersion::V_2025_11_25]) + } + + async fn on_custom_request( + &self, + request: CustomRequest, + _: EventContext, + ) -> Result { + if self.custom { + Ok(CustomResult(json!({"fromApp": request.method}))) + } else { + Err(ErrorData::new( + ErrorCode::METHOD_NOT_FOUND, + request.method, + None, + )) + } + } + + fn accepted_subscription_filter( + &self, + requested: &SubscriptionFilter, + ) -> Option { + if self.events.is_some() { + // The SDK still honors its own category. + None + } else { + assert_eq!(requested.events_list_changed, Some(true)); + Some(requested.clone()) + } + } + + async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> { + assert!(matches!( + context + .sink() + .send(ServerNotification::CustomNotification( + rmcp::model::CustomNotification::new("notifications/events/other", None), + )) + .await, + Err(SubscriptionSendError::UnsupportedNotification( + "custom notification" + )) + )); + if self.change_during_listen { + let runtime = self.events.as_ref().unwrap(); + // The ack has been sent; the runtime watcher has not been polled. + register(runtime, "new-a"); + register(runtime, "new-b"); + } + context.cancelled().await; + Ok(()) + } +} + +async fn exchange( + app: impl ServerHandler, + mode: ClientLifecycleMode, +) -> RunningService { + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + let server = async move { app.serve(server_io).await.unwrap().waiting().await }; + #[cfg(feature = "local")] + tokio::task::spawn_local(server); + #[cfg(not(feature = "local"))] + tokio::spawn(server); + ClientConfig::default() + .serve_with_lifecycle(client_io, mode) + .await + .unwrap() +} + +fn modern() -> ClientLifecycleMode { + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28], + } +} + +async fn call( + client: &rmcp::Peer, + method: &str, + params: Option, +) -> Result { + client + .send_request(ClientRequest::CustomRequest(CustomRequest::new( + method, params, + ))) + .await +} + +macro_rules! events_test { + ($name:ident, $body:block) => { + events_test!($name, 5, $body); + }; + ($name:ident, $seconds:expr, $body:block) => { + #[tokio::test(start_paused = true)] + async fn $name() { + tokio::task::LocalSet::new() + .run_until(tokio::time::timeout(Duration::from_secs($seconds), async $body)) + .await.expect("duplex exchange made no progress"); + } + } +} + +const SUBSCRIPTION_ID: &str = "io.modelcontextprotocol/subscriptionId"; + +fn push_descriptor(name: &str) -> Descriptor { + Descriptor::typed::(name, "", [DeliveryMode::Push, DeliveryMode::Poll]) +} + +struct Wire { + lines: tokio::io::Lines>>, + write: tokio::io::WriteHalf, +} + +impl Wire { + async fn connect(runtime: EventsServer) -> Self { + use tokio::io::AsyncBufReadExt; + let (server, client) = tokio::io::duplex(64 * 1024); + tokio::task::spawn_local(async move { + let app = App { + events: Some(runtime), + ..Default::default() + }; + app.serve(server).await.unwrap().waiting().await.unwrap(); + }); + let (read, write) = tokio::io::split(client); + let mut wire = Self { + lines: tokio::io::BufReader::new(read).lines(), + write, + }; + wire.request( + json!("discover"), + "server/discover", + json!({ + "protocolVersions":["2026-07-28"] + }), + ) + .await; + let result = wire.receive().await; + assert!(result["result"].is_object(), "{result}"); + wire + } + + async fn request(&mut self, id: Value, method: &str, mut params: Value) { + params["_meta"] = json!({ + "io.modelcontextprotocol/protocolVersion":"2026-07-28", + "io.modelcontextprotocol/clientInfo":{"name":"wire","version":"1"}, + "io.modelcontextprotocol/clientCapabilities":{} + }); + self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) + .await; + } + + async fn send(&mut self, message: Value) { + use tokio::io::AsyncWriteExt; + self.write + .write_all(format!("{message}\n").as_bytes()) + .await + .unwrap(); + } + + async fn receive(&mut self) -> Value { + serde_json::from_str(&self.lines.next_line().await.unwrap().unwrap()).unwrap() + } + + async fn frame(&mut self, id: Value, method: &str) -> Value { + let message = self.receive().await; + assert_eq!( + message["method"], + format!("notifications/events/{method}"), + "{message}" + ); + assert_eq!(message["params"]["_meta"][SUBSCRIPTION_ID], id); + message["params"].clone() + } +} + +events_test!(push_stdio_isolates_streams_and_fences_final_after_cancel, { + let runtime = EventsServer::new(); + let first = runtime.register_emit(push_descriptor("first")).unwrap(); + let second = runtime.register_emit(push_descriptor("second")).unwrap(); + let mut wire = Wire::connect(runtime.clone()).await; + wire.request( + json!("one"), + "events/stream", + json!({"name":"first", "heartbeatMs":0}), + ) + .await; + let one = wire.frame(json!("one"), "active").await; + assert_eq!(one["heartbeatMs"], 1_000); + wire.request( + json!(2), + "events/stream", + json!({"name":"second","heartbeatMs":90_000}), + ) + .await; + let two = wire.frame(json!(2), "active").await; + assert_eq!(two["heartbeatMs"], 30_000); + assert_ne!(one["cursor"], two["cursor"]); + wire.request(json!(3), "events/list", json!({})).await; + let unary = wire.receive().await; + assert_eq!(unary["id"], 3); + assert_eq!(unary["result"]["events"].as_array().unwrap().len(), 2); + + first + .emit(Some("a".into()), Utc::now(), JsonObject::new()) + .unwrap(); + let event = wire.frame(json!("one"), "event").await; + assert_eq!(event["eventId"], "a"); + assert_ne!(event["cursor"], one["cursor"]); + second + .emit(Some("b".into()), Utc::now(), JsonObject::new()) + .unwrap(); + assert_eq!(wire.frame(json!(2), "event").await["eventId"], "b"); + assert_eq!( + wire.frame(json!("one"), "heartbeat").await["cursor"], + event["cursor"] + ); + + wire.send( + json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"one"}}), + ) + .await; + wire.request(json!(4), "events/list", json!({})).await; + let unary = wire.receive().await; + assert_eq!(unary["id"], 4); + assert_eq!(unary["result"]["events"].as_array().unwrap().len(), 2); + first + .emit(Some("discarded".into()), Utc::now(), JsonObject::new()) + .unwrap(); + second + .emit(Some("continued".into()), Utc::now(), JsonObject::new()) + .unwrap(); + assert_eq!(wire.frame(json!(2), "event").await["eventId"], "continued"); + runtime.remove("second").unwrap(); + let terminated = wire.frame(json!(2), "terminated").await; + assert_eq!(terminated["error"]["code"], -32023); + assert_eq!(terminated["error"]["data"], json!({"kind":"event"})); + assert_eq!( + wire.receive().await, + json!({ + "jsonrpc":"2.0","id":2,"result":{"resultType":"complete","_meta":{SUBSCRIPTION_ID:2}} + }) + ); +}); + +events_test!(push_gap_precedes_replay_and_regrants_heartbeat, { + let runtime = EventsServer::new(); + let emit = runtime.register_emit(push_descriptor("source")).unwrap(); + let mut wire = Wire::connect(runtime).await; + let now = Utc::now(); + wire.request(json!(1), "events/stream", json!({"name":"source"})) + .await; + let start = wire.frame(json!(1), "active").await["cursor"].clone(); + for (id, timestamp) in [ + ("a", now), + ("old", now - chrono::TimeDelta::days(1)), + ("b", now), + ] { + emit.emit(Some(id.into()), timestamp, JsonObject::new()) + .unwrap(); + assert_eq!(wire.frame(json!(1), "event").await["eventId"], id); + } + wire.request( + json!(2), + "events/stream", + json!({ + "name":"source", "cursor": start, "maxAgeMs": 10_000, "heartbeatMs":1234 + }), + ) + .await; + let active = wire.frame(json!(2), "active").await; + assert_eq!(active["truncated"], false); + assert_eq!(active["cursor"], start); + let a = wire.frame(json!(2), "event").await; + assert_eq!(a["eventId"], "a"); + let gap = wire.frame(json!(2), "active").await; + assert_eq!(gap["truncated"], true); + assert_eq!(gap["heartbeatMs"], 1234); + assert_ne!(gap["cursor"], a["cursor"]); + assert_eq!(wire.frame(json!(2), "event").await["eventId"], "b"); +}); + +events_test!( + push_recoverable_check_failure_then_authorization_revocation, + 35, + { + use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}, + }; + let runtime = EventsServer::new(); + let revoke = Arc::new(AtomicBool::new(false)); + let checks = Arc::new(AtomicUsize::new(0)); + runtime + .register_check( + push_descriptor("source").authorize({ + let revoke = revoke.clone(); + move |_, _, mode| { + assert_eq!(mode, DeliveryMode::Push); + ready(if revoke.load(SeqCst) { + Err(EventsError::Forbidden { + reason: Some("database policy".into()), + }) + } else { + Ok(()) + }) + } + }), + move |_, _, query| { + let mut batch = CheckedBatch::new("head"); + batch.next_poll_ms = Some(1_000); + ready(match checks.fetch_add(1, SeqCst) { + 0 => Ok(batch), + 1 => Err(EventsError::Remote(Box::new(ErrorData::internal_error( + "fetch unavailable", + None, + )))), + 2 => { + assert_eq!(query.cursor.as_deref(), Some("head")); + batch.end = "recovered".into(); + batch.next_poll_ms = Some(60_000); + batch.events.push(EventOccurrence::new( + "recovered", + "source", + Utc::now(), + JsonObject::new(), + )); + Ok(batch) + } + _ => panic!("read must not run after revocation"), + }) + }, + ) + .unwrap(); + let mut wire = Wire::connect(runtime).await; + let start = tokio::time::Instant::now(); + wire.request(json!(1), "events/stream", json!({"name":"source"})) + .await; + wire.frame(json!(1), "active").await; + assert_eq!(wire.frame(json!(1), "error").await["error"]["code"], -32603); + assert_eq!(wire.frame(json!(1), "event").await["eventId"], "recovered"); + revoke.store(true, SeqCst); + let final_notice = wire.frame(json!(1), "terminated").await; + assert_eq!(start.elapsed(), Duration::from_secs(30)); + assert_eq!(final_notice["error"]["code"], -32024); + assert_eq!( + final_notice["error"]["data"], + json!({"reason":"database policy"}) + ); + assert_eq!(wire.receive().await["result"]["_meta"][SUBSCRIPTION_ID], 1); + } +); + +events_test!(push_age_floor_ends_after_immediate_backlog_drain, { + use std::sync::{Arc, Mutex}; + let runtime = EventsServer::new(); + let reads = Arc::new(Mutex::new(Vec::new())); + runtime + .register_check(push_descriptor("source"), { + let reads = reads.clone(); + move |_, _, query| { + reads + .lock() + .unwrap() + .push((tokio::time::Instant::now(), query.age_floor.is_some())); + let mut page = CheckedBatch::new("1"); + page.next_poll_ms = Some(1_000); + match query.cursor.as_deref() { + Some("0") => page.has_more = true, + Some("1") => { + page.end = "2".into(); + page.events.push(EventOccurrence::new( + "replay", + "source", + Utc::now(), + JsonObject::new(), + )); + } + Some("2") => { + page.end = "3".into(); + page.events.push(EventOccurrence::new( + "live", + "source", + Utc::now() - chrono::TimeDelta::days(1), + JsonObject::new(), + )); + } + other => panic!("unexpected cursor {other:?}"), + } + ready(Ok(page)) + } + }) + .unwrap(); + let mut wire = Wire::connect(runtime).await; + wire.request( + json!(1), + "events/stream", + json!({"name":"source","cursor":"0","maxAgeMs":5_000}), + ) + .await; + assert_eq!(wire.frame(json!(1), "active").await["cursor"], "1"); + assert_eq!(wire.frame(json!(1), "event").await["eventId"], "replay"); + assert_eq!(wire.frame(json!(1), "event").await["eventId"], "live"); + let reads = reads.lock().unwrap(); + assert_eq!( + reads.iter().map(|(_, floor)| *floor).collect::>(), + [true, true, false] + ); + assert_eq!(reads[0].0, reads[1].0); + assert_eq!(reads[2].0 - reads[1].0, Duration::from_secs(1)); +}); + +events_test!(push_heartbeats_and_terminates_during_pending_read, { + let runtime = EventsServer::new(); + let entered = Arc::new(tokio::sync::Notify::new()); + runtime + .register_check(push_descriptor("source"), { + let entered = entered.clone(); + move |_, _, query| { + let entered = entered.clone(); + async move { + if query.cursor.is_some() { + entered.notify_one(); + return pending().await; + } + let mut page = CheckedBatch::new("head"); + page.next_poll_ms = Some(1_000); + Ok(page) + } + } + }) + .unwrap(); + let mut wire = Wire::connect(runtime.clone()).await; + wire.request( + json!(1), + "events/stream", + json!({"name":"source","heartbeatMs":1000}), + ) + .await; + wire.frame(json!(1), "active").await; + entered.notified().await; + assert_eq!(wire.frame(json!(1), "heartbeat").await["cursor"], "head"); + runtime.remove("source").unwrap(); + assert_eq!( + wire.frame(json!(1), "terminated").await["error"]["code"], + -32023 + ); +}); + +events_test!(push_replacement, { + let mode = DeliveryMode::Push; + let changed = object(json!({"type":"object","required":["new"]})); + for (schema, expected) in [ + (JsonObject::new(), "payloadSchema"), + (changed, "inputSchema"), + ] { + let runtime = EventsServer::new(); + let source = || raw_descriptor("source", mode, JsonObject::new(), JsonObject::new()); + let emit = runtime.register_emit(source()).unwrap(); + let mut wire = Wire::connect(runtime.clone()).await; + wire.request(json!(1), "events/poll", json!({"name":"source"})) + .await; + let response = wire.receive().await; + assert_eq!(response["error"]["code"], -32026); + assert_eq!( + response["error"]["data"], + json!({"feature":"deliveryMode","value":"poll"}) + ); + wire.request(json!(2), "events/stream", json!({"name":"source"})) + .await; + wire.frame(json!(2), "active").await; + runtime.replace(source(), Replacement::Additive).unwrap(); + emit.emit(Some("still-open".into()), Utc::now(), JsonObject::new()) + .unwrap(); + assert_eq!(wire.frame(json!(2), "event").await["eventId"], "still-open"); + runtime + .replace( + raw_descriptor("source", mode, schema, object(json!({"type":"object"}))), + Replacement::Breaking, + ) + .unwrap(); + let terminated = wire.frame(json!(2), "terminated").await; + assert_eq!(terminated["error"]["code"], -32026); + assert_eq!( + terminated["error"]["data"], + json!({"feature":expected,"reason":"schema_changed"}) + ); + assert_eq!(wire.receive().await["result"]["_meta"][SUBSCRIPTION_ID], 2); + } +}); + +events_test!(stdio_eof_ends_delivery_at_the_last_checkpoint, { + use tokio::io::AsyncBufReadExt; + let (server_io, client_io) = tokio::io::duplex(64 * 1024); + let stop = tokio_util::sync::CancellationToken::new(); + let task = tokio::task::spawn_local({ + let stop = stop.clone(); + async move { + let (read, write) = tokio::io::split(server_io); + let mut wire = Wire { + lines: tokio::io::BufReader::new(read).lines(), + write, + }; + let discover = wire.receive().await; + assert_eq!(discover["method"], "server/discover"); + wire.send(json!({"jsonrpc":"2.0","id":discover["id"],"result":{ + "resultType":"complete","ttlMs":0,"cacheScope":"private", + "supportedVersions":["2026-07-28"],"capabilities":{"extensions":{EXTENSION:{}}} + }})) + .await; + let catalog = wire.receive().await; + assert_eq!(catalog["method"], "events/list"); + wire.send(json!({"jsonrpc":"2.0","id":catalog["id"],"result":{ + "resultType":"complete","events":[ + {"name":"source","delivery":["push"],"inputSchema":{},"payloadSchema":{}} + ] + }})) + .await; + let stream = wire.receive().await; + assert_eq!(stream["method"], "events/stream"); + wire.send( + json!({"jsonrpc":"2.0","method":"notifications/events/active","params":{ + "cursor":"head","heartbeatMs":30_000,"_meta":{SUBSCRIPTION_ID:stream["id"]} + }}), + ) + .await; + stop.cancelled().await; + drop(wire); + } + }); + let client = ClientConfig::default() + .serve_with_lifecycle(client_io, modern()) + .await + .unwrap(); + let api = EventsClient::new(client.peer().clone()); + let mut events = api + .subscribe("source", None, Default::default()) + .await + .unwrap(); + let Some(EventUpdate::Checkpoint(saved)) = events.next().await else { + panic!("missing activation"); + }; + stop.cancel(); + task.await.unwrap(); + client.waiting().await.unwrap(); + assert_eq!(saved, "head"); + assert!(matches!(events.next().await, Some(EventUpdate::Terminated( + EventsError::Service(error), + )) if matches!(*error, ServiceError::TransportClosed))); + assert!(events.next().await.is_none()); +}); + +events_test!( + push_heartbeats_track_quiet_progress_without_skipping_partial_check_batch, + { + let runtime = EventsServer::new(); + runtime + .register_check(push_descriptor("source"), |_, _, query| async move { + let sample = |id| EventOccurrence::new(id, "source", Utc::now(), JsonObject::new()); + let mut batch = CheckedBatch::new("batch-end"); + batch.next_poll_ms = Some(1_000); + match query.cursor.as_deref() { + Some("saved") => { + let mut event = sample("a"); + event.meta = Some(object( + json!({SUBSCRIPTION_ID:"wrong", "otherExtension":true}), + )); + batch.events.push(event); + batch.events.push(sample("b")); + } + Some("batch-end") => batch.end = "quiet-progress".into(), + Some("quiet-progress") => return std::future::pending().await, + other => panic!("unexpected cursor {other:?}"), + } + Ok(batch) + }) + .unwrap(); + let mut wire = Wire::connect(runtime).await; + wire.request( + json!(1), + "events/stream", + json!({ + "name":"source","cursor":"saved","heartbeatMs":1_500 + }), + ) + .await; + assert_eq!(wire.frame(json!(1), "active").await["cursor"], "saved"); + let first = wire.frame(json!(1), "event").await; + assert_eq!(first["eventId"], "a"); + assert_eq!(first["cursor"], "saved"); + assert_eq!(first["_meta"]["otherExtension"], true); + let second = wire.frame(json!(1), "event").await; + assert_eq!(second["eventId"], "b"); + assert_eq!(second["cursor"], "batch-end"); + assert_eq!( + wire.frame(json!(1), "heartbeat").await["cursor"], + "quiet-progress" + ); + assert_eq!( + wire.frame(json!(1), "heartbeat").await["cursor"], + "quiet-progress" + ); + } +); + +#[tokio::test(start_paused = true)] +async fn push_activation_is_bounded_without_pre_activation_frames() { + tokio::task::LocalSet::new().run_until(async { + let runtime = EventsServer::new(); + for (name, delay) in [("slow", 9), ("late", 11)] { + runtime.register_check(push_descriptor(name), move |_, _, _| async move { + tokio::time::sleep(Duration::from_secs(delay)).await; + Ok(CheckedBatch::new("head")) + }).unwrap(); + } + let mut wire = Wire::connect(runtime).await; + let before = tokio::time::Instant::now(); + wire.request(json!(1), "events/stream", json!({"name":"slow"})).await; + assert_eq!(wire.frame(json!(1), "active").await["cursor"], "head"); + assert_eq!(before.elapsed(), Duration::from_secs(9)); + wire.send(json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}})).await; + let before = tokio::time::Instant::now(); + wire.request(json!(2), "events/stream", json!({"name":"late"})).await; + let error = wire.receive().await; + assert_eq!(error["id"], 2); + assert_eq!(error["error"]["code"], -32603); + assert_eq!(before.elapsed(), Duration::from_secs(10)); + }).await; +} + +events_test!(managed_poll_drains_progress_then_observes_floor, { + use std::sync::{Arc, Mutex}; + let clock = Arc::new(Mutex::new(Vec::new())); + let runtime = EventsServer::new(); + runtime + .register_check(push_descriptor("source"), { + let clock = clock.clone(); + move |_, _, query| { + clock.lock().unwrap().push(tokio::time::Instant::now()); + let mut batch = CheckedBatch::new("p0"); + batch.next_poll_ms = Some(0); + match query.cursor.as_deref() { + None => {} + Some("p0") => { + batch.end = "p1".into(); + batch.has_more = true; + } + Some("p1") => { + batch.end = "p2".into(); + batch.events.push(EventOccurrence::new( + "a", + "source", + Utc::now(), + JsonObject::new(), + )); + batch.events.push(EventOccurrence::new( + "b", + "source", + Utc::now(), + JsonObject::new(), + )); + } + Some("p2") => batch.end = "p3".into(), + other => panic!("unexpected cursor {other:?}"), + } + ready(Ok(batch)) + } + }) + .unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..Default::default() + }, + modern(), + ) + .await; + let client_api = EventsClient::new(client.peer().clone()); + let mut options = SubscriptionOptions::default(); + options.mode = Some(DeliveryMode::Poll); + let mut events = client_api.subscribe("source", None, options).await.unwrap(); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "p0")); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "p1")); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "a") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "b") + ); + assert_eq!(clock.lock().unwrap().len(), 3); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "p2")); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "p3")); + let at = clock.lock().unwrap(); + assert_eq!(at[1] - at[0], Duration::from_secs(1)); + assert_eq!(at[2], at[1]); + assert_eq!(at[3] - at[2], Duration::from_secs(1)); +}); + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Scenario { + Watchdog, + Overflow, + ClosingPush, + PushActivation, + Poll, +} + +#[derive(Clone)] +struct ScriptedPeer { + scenario: Scenario, + calls: std::sync::Arc>>, + go: Arc, + sent: Arc, + opens: Arc>>, +} + +impl ScriptedPeer { + fn new(scenario: Scenario) -> Self { + Self { + scenario, + calls: Default::default(), + go: Default::default(), + sent: Default::default(), + opens: Default::default(), + } + } +} + +impl ServerHandler for ScriptedPeer { + fn get_info(&self) -> ServerConfig { + let mut info = ServerConfig::default(); + info.capabilities + .extensions + .get_or_insert_default() + .insert(EXTENSION.into(), JsonObject::new()); + info + } + + async fn on_custom_request( + &self, + request: CustomRequest, + ctx: EventContext, + ) -> Result { + if request.method == "events/list" { + let delivery = if self.scenario == Scenario::Poll { + json!(["poll"]) + } else { + json!(["push", "poll"]) + }; + return Ok(CustomResult(json!({"resultType":"complete","events":[ + {"name":"source","delivery":delivery,"inputSchema":{},"payloadSchema":{}} + ]}))); + } + assert_eq!( + request.method, + if self.scenario == Scenario::Poll { + "events/poll" + } else { + "events/stream" + } + ); + let params = request.params.unwrap(); + let call = { + let mut calls = self.calls.lock().unwrap(); + calls.push((tokio::time::Instant::now(), params.clone())); + calls.len() + }; + let problem = |code, message| ErrorData::new(ErrorCode(code), message, None); + match (self.scenario, call) { + (Scenario::PushActivation | Scenario::Poll, 1) => std::future::pending().await, + (Scenario::PushActivation | Scenario::Poll, 2) => Err(problem(-32603, "transient")), + (Scenario::PushActivation, 3) => Err(problem(-32024, "denied")), + (Scenario::Poll, 3..=5) => Ok(CustomResult(json!({ + "resultType":"complete", "events":[], "cursor": if call == 5 { "next" } else { "head" }, + "hasMore":true, "nextPollMs":999_999 + }))), + (Scenario::Poll, 6) => Err(problem(-32023, "removed")), + (Scenario::Watchdog | Scenario::Overflow, _) => { + let cursor = params["cursor"].clone(); + self.opens + .lock() + .unwrap() + .push((ctx.id.clone(), cursor.clone())); + let start = if call == 1 { json!("head") } else { cursor }; + Self::send(&ctx, "active", json!({"cursor":start, "heartbeatMs":1_000})).await; + match (self.scenario, call) { + (Scenario::Overflow, 1) => { + self.go.notified().await; + for index in 0..70 { + Self::event(&ctx, &format!("event{index}"), &format!("pos{index}")) + .await; + } + self.sent.notify_one(); + } + (Scenario::Overflow, _) => { + Self::event(&ctx, "after-reconnect", "reconnected").await + } + _ => { + Self::event(&ctx, "a", "a-end").await; + if call > 1 { + Self::event(&ctx, "b", "b-end").await; + } + } + } + ctx.ct.cancelled().await; + Err(problem(-32603, "cancelled")) + } + (Scenario::ClosingPush, 1..=2) => { + Self::send( + &ctx, + "active", + json!({"cursor":"head","heartbeatMs":30_000}), + ) + .await; + Ok(CustomResult( + json!({"resultType":"complete","_meta":{SUBSCRIPTION_ID:ctx.id}}), + )) + } + (Scenario::ClosingPush, 3) => { + Self::send(&ctx, "unknown", json!({})).await; + Self::send( + &ctx, + "active", + json!({"cursor":"fresh","truncated":true,"heartbeatMs":30_000}), + ) + .await; + Self::send( + &ctx, + "error", + json!({"error":{"code":-32603,"message":"recoverable"}}), + ) + .await; + let mut notification = rmcp::model::CustomNotification::new( + "notifications/events/event", + Some(json!({ + "eventId":"live","name":"source","timestamp":"2026-07-28T00:00:00Z","data":{}, "cursor":"latest" + })), + ); + notification + .get_meta_mut() + .set_subscription_id(ctx.id.clone()); + notification + .get_meta_mut() + .0 + .0 + .insert("app".into(), json!("visible")); + ctx.peer + .send_notification(ServerNotification::CustomNotification(notification)) + .await + .unwrap(); + Self::send( + &ctx, + "terminated", + json!({"error":{"code":-32024,"message":"denied"}}), + ) + .await; + ctx.ct.cancelled().await; + Err(problem(-32603, "cancelled")) + } + _ => panic!("unexpected delivery request {call}"), + } + } +} + +events_test!( + bare_push_completion_reconnects_with_backoff_and_yields_gap_and_error, + { + let fixture = ScriptedPeer::new(Scenario::ClosingPush); + let client = exchange(fixture.clone(), modern()).await; + let api = EventsClient::new(client.peer().clone()); + let mut options = SubscriptionOptions::default(); + options.max_age_ms = Some(5_000); + let mut events = api.subscribe("source", None, options).await.unwrap(); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + for _ in 0..2 { + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Service(error))) + if matches!(*error, ServiceError::TransportClosed)) + ); + } + assert!(matches!(events.next().await, Some(EventUpdate::Gap))); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "fresh") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Remote(error))) if error.code == ErrorCode::INTERNAL_ERROR) + ); + let Some(EventUpdate::Occurrence(event)) = events.next().await else { + panic!("missing occurrence"); + }; + assert_eq!(event.meta, Some(object(json!({"app":"visible"})))); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "latest") + ); + assert!(matches!( + events.next().await, + Some(EventUpdate::Terminated(EventsError::Forbidden { .. })) + )); + assert!(events.next().await.is_none()); + let calls = fixture.calls.lock().unwrap(); + assert_eq!(calls.len(), 3); + assert!((250..500).contains(&(calls[1].0 - calls[0].0).as_millis())); + assert!((500..1000).contains(&(calls[2].0 - calls[1].0).as_millis())); + assert!( + calls[1..] + .iter() + .all(|(_, params)| params["cursor"] == "head") + ); + assert!(calls.iter().all(|(_, params)| params["maxAgeMs"] == 5_000)); + } +); + +events_test!(push_activation_deadline_and_retry_classifier, 20, { + let client = exchange(ScriptedPeer::new(Scenario::PushActivation), modern()).await; + let api = EventsClient::new(client.peer().clone()); + let mut events = api + .subscribe("source", None, Default::default()) + .await + .unwrap(); + let start = tokio::time::Instant::now(); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Service(error))) + if matches!(*error, ServiceError::Timeout { timeout } if timeout == Duration::from_secs(15))) + ); + assert_eq!(start.elapsed(), Duration::from_secs(15)); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Remote(error))) + if error.code == ErrorCode::INTERNAL_ERROR) + ); + assert!(matches!( + events.next().await, + Some(EventUpdate::Terminated(EventsError::Forbidden { .. })) + )); + assert!(events.next().await.is_none()); +}); + +events_test!(managed_poll_retries_times_out_and_falls_back_to_poll, 22, { + let fixture = ScriptedPeer::new(Scenario::Poll); + let client = exchange(fixture.clone(), modern()).await; + let api = EventsClient::new(client.peer().clone()); + let mut forced = SubscriptionOptions::default(); + forced.mode = Some(DeliveryMode::Push); + assert!(matches!(api.subscribe("source", None, forced).await, + Err(EventsError::Unsupported { value: Some(value), .. }) if value == "push")); + let mut options = SubscriptionOptions::default(); + options.cursor = Some("saved".into()); + options.max_age_ms = Some(5_000); + let mut events = api.subscribe("source", None, options).await.unwrap(); + let start = tokio::time::Instant::now(); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Service(error))) + if matches!(*error, ServiceError::Timeout { timeout } if timeout == Duration::from_secs(15))) + ); + assert_eq!(start.elapsed(), Duration::from_secs(15)); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Remote(error))) + if error.code == ErrorCode::INTERNAL_ERROR) + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "next") + ); + assert!(matches!( + events.next().await, + Some(EventUpdate::Terminated(EventsError::NotFound { .. })) + )); + assert!(events.next().await.is_none()); + let calls = fixture.calls.lock().unwrap(); + assert_eq!(calls.len(), 6); + assert_eq!(calls[2].0, calls[3].0); + assert_eq!(calls[4].0 - calls[3].0, Duration::from_secs(1)); + assert_eq!(calls[4].0, calls[5].0); + assert!( + calls[..3] + .iter() + .all(|(_, params)| params["maxAgeMs"] == 5_000) + ); + assert!( + calls[3..] + .iter() + .all(|(_, params)| params["maxAgeMs"].is_null()) + ); +}); + +impl ScriptedPeer { + async fn send(context: &EventContext, method: &str, params: Value) { + let mut note = rmcp::model::CustomNotification::new( + format!("notifications/events/{method}"), + Some(params), + ); + note.get_meta_mut().set_subscription_id(context.id.clone()); + context + .peer + .send_notification(ServerNotification::CustomNotification(note)) + .await + .unwrap(); + } + + async fn event(context: &EventContext, id: &str, cursor: &str) { + Self::send( + context, + "event", + json!({ + "eventId": id, "name": "source", "timestamp":"2026-07-28T00:00:00Z", + "data": {}, "cursor": cursor + }), + ) + .await; + } +} + +events_test!(push_watchdog_reconnects_from_last_checkpoint, { + let script = ScriptedPeer::new(Scenario::Watchdog); + let client = exchange(script.clone(), modern()).await; + let client_api = EventsClient::new(client.peer().clone()); + let mut events = client_api + .subscribe("source", None, SubscriptionOptions::default()) + .await + .unwrap(); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "a") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "a-end") + ); + let before = tokio::time::Instant::now(); + assert!( + matches!(events.next().await, Some(EventUpdate::RecoverableError(EventsError::Service(e))) + if matches!(*e, ServiceError::Timeout { timeout } if timeout == Duration::from_secs(3))) + ); + assert_eq!(before.elapsed(), Duration::from_secs(3)); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "a") + ); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "b") + ); + let opens = script.opens.lock().unwrap(); + assert_eq!(opens.len(), 2); + assert_ne!(opens[0].0, opens[1].0); + assert!(opens[0].1.is_null()); + assert_eq!(opens[1].1, "a-end"); +}); + +events_test!( + push_overflow_is_observable_and_resumes_after_only_consumed_frames, + { + let script = ScriptedPeer::new(Scenario::Overflow); + let client = exchange(script.clone(), modern()).await; + let client_api = EventsClient::new(client.peer().clone()); + let mut events = client_api + .subscribe("source", None, SubscriptionOptions::default()) + .await + .unwrap(); + assert!( + matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + script.go.notify_one(); + script.sent.notified().await; + // The catalog reply crosses the ordered duplex input after the flood. + assert_eq!(client_api.list_page(None).await.unwrap().events.len(), 1); + let mut last = String::from("head"); + loop { + match events.next().await.unwrap() { + EventUpdate::Checkpoint(cursor) => last = cursor, + EventUpdate::Occurrence(_) => {} + EventUpdate::RecoverableError(EventsError::Service(error)) => { + assert!(matches!( + *error, + ServiceError::SubscriptionLagged { capacity: 64 } + )); + break; + } + other => panic!("expected observable overflow, got {other:?}"), + } + } + assert_ne!(last, "pos69"); + assert!( + matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "after-reconnect") + ); + assert_eq!(script.opens.lock().unwrap()[1].1, last); + } +); + +events_test!( + emit_byte_eviction_breaking_replacement_and_reregistration, + { + let runtime = EventsServer::new(); + let emit = runtime + .register_emit(raw_descriptor( + "emit", + DeliveryMode::Poll, + JsonObject::new(), + JsonObject::new(), + )) + .unwrap(); + let client = exchange( + App { + events: Some(runtime.clone()), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let mut poll = PollParams::new("emit"); + poll.cursor = events.poll(poll.clone()).await.unwrap().cursor; + for index in 1..=3 { + emit.emit( + Some(index.to_string()), + Utc::now(), + object(json!({"blob":"x".repeat(100 * 1024)})), + ) + .unwrap(); + } + let gap = events.poll(poll.clone()).await.unwrap(); + assert!(gap.truncated && gap.has_more && gap.events.is_empty()); + poll.cursor = gap.cursor; + let batch = events.poll(poll.clone()).await.unwrap(); + assert_eq!( + batch + .events + .iter() + .map(|event| event.event_id.as_str()) + .collect::>(), + ["2", "3"] + ); + poll.cursor = batch.cursor; + let input = object(json!({"type":"object"})); + runtime + .replace( + raw_descriptor("emit", DeliveryMode::Poll, input.clone(), JsonObject::new()), + Replacement::Breaking, + ) + .unwrap(); + assert!(events.poll(poll.clone()).await.unwrap().truncated); + poll.cursor = events.poll(PollParams::new("emit")).await.unwrap().cursor; + runtime + .replace( + raw_descriptor( + "emit", + DeliveryMode::Poll, + input, + object(json!({"type":"object"})), + ), + Replacement::Breaking, + ) + .unwrap(); + assert!(events.poll(poll.clone()).await.unwrap().truncated); + runtime.remove("emit").unwrap(); + assert!(matches!( + events.poll(poll.clone()).await, + Err(EventsError::NotFound { .. }) + )); + assert!(matches!( + emit.emit(None, Utc::now(), JsonObject::new()), + Err(EventsError::NotFound { .. }) + )); + let new = runtime.register_emit(descriptor("emit")).unwrap(); + assert!(matches!( + emit.emit(None, Utc::now(), JsonObject::new()), + Err(EventsError::NotFound { .. }) + )); + new.emit(Some("new".into()), Utc::now(), JsonObject::new()) + .unwrap(); + let gap = events.poll(poll.clone()).await.unwrap(); + assert!(gap.truncated && gap.has_more); + poll.cursor = gap.cursor; + assert_eq!(events.poll(poll).await.unwrap().events[0].event_id, "new"); + client.cancel().await.unwrap(); + } +); + +events_test!(emit_filter_advances_cursor, { + let runtime = EventsServer::new(); + let selected = descriptor("emit").matches(|_, event, _| event.event_id != "filtered"); + assert!(matches!( + runtime.register_check(selected.clone(), |_, _, _| ready(Ok(CheckedBatch::new( + "head" + )))), + Err(EventsError::InvalidParams(_)) + )); + let emit = runtime.register_emit(selected).unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let mut poll = PollParams::new("emit"); + poll.cursor = events.poll(poll.clone()).await.unwrap().cursor; + emit.emit(Some("filtered".into()), Utc::now(), JsonObject::new()) + .unwrap(); + let quiet = events.poll(poll.clone()).await.unwrap(); + assert!(quiet.events.is_empty()); + assert_ne!(quiet.cursor, poll.cursor); + poll.cursor = quiet.cursor; + emit.emit(Some("kept".into()), Utc::now(), JsonObject::new()) + .unwrap(); + let result = events.poll(poll).await.unwrap(); + assert_eq!(result.events[0].event_id, "kept"); + client.cancel().await.unwrap(); +}); + +events_test!(oversized_emit_does_not_advance_replay, { + let runtime = EventsServer::new(); + let emit = runtime.register_emit(descriptor("emit")).unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let mut poll = PollParams::new("emit"); + poll.cursor = events.poll(poll.clone()).await.unwrap().cursor; + emit.emit(Some("kept".into()), Utc::now(), JsonObject::new()) + .unwrap(); + assert!(matches!( + emit.emit(None, Utc::now(), object(json!({"blob":"x".repeat(256 * 1024 + 1)}))), + Err(EventsError::ResourceExhausted { limit, max: Some(262_144) }) if limit == "eventBytes" + )); + let result = events.poll(poll.clone()).await.unwrap(); + assert_eq!(result.events[0].event_id, "kept"); + assert_ne!(result.cursor, poll.cursor); + client.cancel().await.unwrap(); +}); + +events_test!( + emit_age_gap_never_skips_earlier_items_and_count_limit_evicts, + { + let runtime = EventsServer::new(); + let emit = runtime.register_emit(descriptor("emit")).unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let mut poll = PollParams::new("emit"); + poll.cursor = events.poll(poll.clone()).await.unwrap().cursor; + let initial = poll.cursor.clone(); + let now = Utc::now(); + for (id, time) in [ + ("first", now), + ("old", now - chrono::TimeDelta::hours(2)), + ("last", now), + ] { + emit.emit(Some(id.into()), time, JsonObject::new()).unwrap(); + } + poll.max_age_ms = Some(3_600_000); + poll.max_events = Some(1); + let first = events.poll(poll.clone()).await.unwrap(); + assert_eq!(first.events[0].event_id, "first"); + assert!(first.has_more && !first.truncated); + poll.cursor = first.cursor; + let gap = events.poll(poll.clone()).await.unwrap(); + assert!(gap.events.is_empty() && gap.truncated && gap.has_more); + poll.cursor = gap.cursor; + assert_eq!( + events.poll(poll.clone()).await.unwrap().events[0].event_id, + "last" + ); + for i in 0..260 { + emit.emit(Some(format!("ring-{i}")), now, JsonObject::new()) + .unwrap(); + } + poll.cursor = initial; + let gap = events.poll(poll.clone()).await.unwrap(); + assert!(gap.truncated && gap.has_more); + poll.cursor = gap.cursor; + assert_eq!( + events.poll(poll).await.unwrap().events[0].event_id, + "ring-4" + ); + client.cancel().await.unwrap(); + } +); + +events_test!(runtime_off_preserves_app_advertisement_and_handlers, { + let client = exchange( + App { + custom: true, + app_settings: Some(object(json!({"listChanged":true,"app":"owned"}))), + ..App::default() + }, + modern(), + ) + .await; + let info = client.peer_info().unwrap(); + assert_eq!( + info.capabilities.extensions.as_ref().unwrap()[EXTENSION]["app"], + "owned" + ); + assert!(matches!(call(&client, "events/list", None).await.unwrap(), + ServerResult::CustomResult(result) if result.0["fromApp"] == "events/list")); + let mut stream = client + .listen(SubscriptionFilter::builder().events_list_changed().build()) + .await + .unwrap(); + assert_eq!(stream.acknowledged().events_list_changed, Some(true)); + stream.cancel().await.unwrap(); + client.cancel().await.unwrap(); + let client = exchange( + App { + app_settings: Some(JsonObject::new()), + ..App::default() + }, + modern(), + ) + .await; + let mut stream = client + .listen(SubscriptionFilter::builder().events_list_changed().build()) + .await + .unwrap(); + assert_eq!(stream.acknowledged().events_list_changed, None); + stream.cancel().await.unwrap(); + client.cancel().await.unwrap(); +}); + +events_test!( + installed_runtime_only_uses_modern_discovery_and_reserved_methods, + { + let runtime = EventsServer::new(); + register(&runtime, "a"); + for mode in [ + ClientLifecycleMode::Initialize, + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2025_11_25], + }, + ] { + let client = exchange( + App { + events: Some(runtime.clone()), + custom: true, + app_settings: Some(JsonObject::new()), + ..App::default() + }, + mode, + ) + .await; + let info = client.peer_info().unwrap(); + assert!( + !info + .capabilities + .extensions + .as_ref() + .unwrap() + .contains_key(EXTENSION) + ); + assert!( + matches!(call(&client, "events/list", None).await, Err(ServiceError::McpError(error)) if error.code == ErrorCode::METHOD_NOT_FOUND) + ); + client.cancel().await.unwrap(); + } + let client = exchange( + App { + events: Some(runtime.clone()), + custom: true, + ..App::default() + }, + modern(), + ) + .await; + for (method, code) in [ + ("events/foo", -32601), + ("events/subscribe", -32026), + ("events/unsubscribe", -32026), + ] { + assert!( + matches!(call(&client, method, Some(json!({"name":"a"}))).await, Err(ServiceError::McpError(error)) if error.code.0 == code) + ); + } + assert!( + matches!(call(&client, "fixture/method", None).await.unwrap(), ServerResult::CustomResult(result) if result.0["fromApp"] == "fixture/method") + ); + runtime.remove("a").unwrap(); + assert!( + matches!(call(&client, "events/poll", Some(json!({"name":"a"}))).await, + Err(ServiceError::McpError(error)) if error.code.0 == -32023) + ); + client.cancel().await.unwrap(); + } +); + +events_test!(catalog_change_before_watcher, { + let runtime = EventsServer::new(); + for index in (0..40).rev() { + register(&runtime, &format!("{index:02}")); + } + let client = exchange( + App { + events: Some(runtime), + change_during_listen: true, + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let page = events.list_page(None).await.unwrap(); + assert!(page.next_cursor.is_none()); + assert_eq!( + page.events + .iter() + .map(|event| event.name.clone()) + .collect::>(), + (0..40) + .map(|index| format!("{index:02}")) + .collect::>() + ); + assert!(matches!( + events.list_page(Some("garbage")).await, + Err(EventsError::InvalidParams(_)) + )); + let mut stream = client + .listen( + SubscriptionFilter::builder() + .events_list_changed() + .tools_list_changed() + .build(), + ) + .await + .unwrap(); + assert_eq!(stream.acknowledged().events_list_changed, Some(true)); + assert_eq!(stream.acknowledged().tools_list_changed, None); + let notice = stream.next().await.unwrap().unwrap(); + assert!( + matches!(notice, ServerNotification::CustomNotification(ref n) if n.method == "notifications/events/list_changed") + ); + assert_eq!( + notice.get_meta().subscription_id().as_ref(), + Some(stream.id()) + ); + assert!( + tokio::time::timeout(Duration::from_millis(1), stream.next()) + .await + .is_err(), + "revisions coalesce" + ); + stream.cancel().await.unwrap(); + client.cancel().await.unwrap(); +}); + +events_test!( + additive_replace_during_authorization_and_new_catalog_name, + { + let runtime = EventsServer::new(); + let registry = runtime.clone(); + runtime + .register_check( + descriptor("a").authorize(move |_, _, mode| { + assert_eq!(mode, DeliveryMode::Poll); + ready(registry.replace(descriptor("a"), Replacement::Additive)) + }), + |_, _, _| ready(Ok(CheckedBatch::new("head"))), + ) + .unwrap(); + let client = exchange( + App { + events: Some(runtime.clone()), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + assert_eq!( + events + .poll(PollParams::new("a")) + .await + .unwrap() + .cursor + .as_deref(), + Some("head") + ); + register(&runtime, "b"); + assert_eq!( + events + .poll(PollParams::new("b")) + .await + .unwrap() + .cursor + .as_deref(), + Some("head") + ); + client.cancel().await.unwrap(); + } +); + +events_test!(check_byte_cut_and_age_floor_including_large_unsigned_age, { + let runtime = EventsServer::new(); + let now = Utc::now(); + runtime + .register_check( + descriptor("a"), + move |ctx, args, query: CheckQuery| async move { + assert!(!ctx.ct.is_cancelled()); + assert_eq!(query.max_bytes, 256 * 1024); + if query.cursor.is_none() { + assert!(query.age_floor.is_none()); + return Ok(CheckedBatch::new("head")); + } + assert_eq!(query.age_floor.is_some(), args.contains_key("floor")); + let mut batch = CheckedBatch::new("3"); + let first = if query.cursor.as_deref() == Some("2") { + 3 + } else { + 1 + }; + for index in first..=3 { + let mut event = EventOccurrence::new( + index.to_string(), + "a", + now, + object(json!({"data":"x".repeat(100 * 1024)})), + ); + event.cursor = Some(index.to_string()); + batch.events.push(event); + } + Ok(batch) + }, + ) + .unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..App::default() + }, + modern(), + ) + .await; + let events = EventsClient::new(client.peer().clone()); + let mut poll = PollParams::new("a"); + poll.max_age_ms = Some(3_600_000); + poll.cursor = events.poll(poll.clone()).await.unwrap().cursor; + poll.arguments = Some(object(json!({"floor": true}))); + let cut = events.poll(poll.clone()).await.unwrap(); + assert_eq!(cut.events.len(), 2); + assert!(cut.events.iter().all(|event| event.cursor.is_none())); + assert_eq!(cut.cursor.as_deref(), Some("2")); + assert!(cut.has_more); + poll.cursor = cut.cursor; + poll.max_age_ms = Some(u64::MAX); + poll.arguments = None; + let last = events.poll(poll).await.unwrap(); + assert_eq!(last.events[0].event_id, "3"); + assert!(!last.has_more); + client.cancel().await.unwrap(); +}); + +events_test!(cancellation_drops_an_in_flight_check, { + struct OnDrop { + token: tokio_util::sync::CancellationToken, + observed: Arc, + } + impl Drop for OnDrop { + fn drop(&mut self) { + assert!(self.token.is_cancelled()); + self.observed.notify_one(); + } + } + let runtime = EventsServer::new(); + let entered = Arc::new(tokio::sync::Notify::new()); + let stopped = Arc::new(tokio::sync::Notify::new()); + runtime + .register_check(descriptor("a"), { + let (entered, stopped) = (entered.clone(), stopped.clone()); + move |ctx, _, _| { + let (entered, stopped) = (entered.clone(), stopped.clone()); + async move { + let _on_drop = OnDrop { + token: ctx.ct, + observed: stopped, + }; + entered.notify_one(); + pending::>().await + } + } + }) + .unwrap(); + let client = exchange( + App { + events: Some(runtime), + ..App::default() + }, + modern(), + ) + .await; + let request = CustomRequest::new("events/poll", Some(json!({"name":"a"}))); + let handle = client + .send_request_with_option( + ClientRequest::CustomRequest(request), + PeerRequestOptions::no_options(), + ) + .await + .unwrap(); + entered.notified().await; + handle + .cancel(Some("test cancellation".into())) + .await + .unwrap(); + stopped.notified().await; + client.cancel().await.unwrap(); +}); diff --git a/crates/rmcp/tests/test_events_http.rs b/crates/rmcp/tests/test_events_http.rs new file mode 100644 index 000000000..5970a7c69 --- /dev/null +++ b/crates/rmcp/tests/test_events_http.rs @@ -0,0 +1,938 @@ +#![cfg(all( + feature = "events", + feature = "server", + feature = "client", + feature = "transport-streamable-http-server", + feature = "transport-streamable-http-client-reqwest", + not(feature = "local"), +))] + +#[cfg(feature = "events-webhook")] +#[path = "common/events_webhook.rs"] +mod webhook; + +use std::{ + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use futures::StreamExt; +use rmcp::{ + ClientLifecycleMode, ClientServiceExt, ServerHandler, + events::{ + client::{EventUpdate, EventsClient, SubscriptionOptions}, + server::{CheckedBatch, Descriptor, EventsServer, Replacement}, + wire::{DeliveryMode, EventDescriptor, EventsError, PollParams}, + }, + model::{ClientConfig, JsonObject, ProtocolVersion}, + transport::{ + StreamableHttpClientTransport, + streamable_http_client::StreamableHttpClientTransportConfig, + streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, + session::{ + EventStore, EventStoreError, EventStream, ServerSseMessage, + local::LocalSessionManager, + }, + }, + }, +}; +use serde_json::{Value, json}; +use tokio_util::sync::CancellationToken; + +type EventContext = rmcp::service::RequestContext; + +#[derive(Clone)] +struct App(Option, bool); + +impl ServerHandler for App { + fn events(&self) -> Option<&EventsServer> { + self.0.as_ref() + } + + async fn on_custom_request( + &self, + request: rmcp::model::CustomRequest, + _: EventContext, + ) -> Result { + if self.1 { + if request + .params + .as_ref() + .is_some_and(|params| params["fail"] == true) + { + return Err(rmcp::ErrorData::internal_error("app-owned error", None)); + } + Ok(rmcp::model::CustomResult( + json!({"appMethod": request.method}), + )) + } else { + Err(rmcp::ErrorData::new( + rmcp::model::ErrorCode::METHOD_NOT_FOUND, + request.method, + None, + )) + } + } +} + +#[derive(Clone)] +struct Authenticated; + +fn input_schema(annotation: &str) -> Arc { + Arc::new( + json!({"type":"object","properties":{"region":{"type":"string","x-mcp-header":annotation}}}) + .as_object() + .unwrap() + .clone(), + ) +} + +fn descriptor(name: &str, annotation: &str) -> Descriptor { + Descriptor::raw( + EventDescriptor::new( + name, + "", + vec![DeliveryMode::Poll], + input_schema(annotation), + Arc::new(JsonObject::new()), + ), + |_| Ok(()), + ) +} + +async fn server(app: App) -> (String, CancellationToken, tokio::task::JoinHandle<()>) { + let ct = CancellationToken::new(); + let service: StreamableHttpService = StreamableHttpService::new( + move || Ok(app.clone()), + Default::default(), + StreamableHttpServerConfig::default() + .with_json_response(true) + .with_cancellation_token(ct.child_token()), + ); + let router = axum::Router::new() + .nest_service("/mcp", service) + .layer(axum::Extension(Authenticated)); + serve_router(router, ct).await +} + +async fn serve_router( + router: axum::Router, + ct: CancellationToken, +) -> (String, CancellationToken, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/mcp", listener.local_addr().unwrap()); + let stop = ct.clone(); + let task = tokio::spawn(async move { + axum::serve(listener, router) + .with_graceful_shutdown(stop.cancelled_owned()) + .await + .unwrap(); + }); + (url, ct, task) +} + +async fn raw( + url: &str, + method: &str, + params: Value, + headers: &[(&str, &str)], +) -> (reqwest::StatusCode, Value) { + let response = raw_post(url, method, params, headers).send().await.unwrap(); + let status = response.status(); + (status, response.json().await.unwrap()) +} + +fn raw_post( + url: &str, + method: &str, + params: Value, + headers: &[(&str, &str)], +) -> reqwest::RequestBuilder { + let mut params = params; + params["_meta"] = json!({ + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name":"fixture","version":"1"}, + "io.modelcontextprotocol/clientCapabilities": {} + }); + let mut request = reqwest::Client::new() + .post(url) + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", "2026-07-28") + .header("mcp-method", method) + .json(&json!({"jsonrpc":"2.0","id":"fixture","method":method,"params":params})); + for (key, value) in headers { + request = request.header(*key, *value); + } + request +} + +fn push_source(name: &str) -> Descriptor { + Descriptor::typed::(name, "", [DeliveryMode::Push]) +} + +async fn push_server( + app: App, + store: Option>, +) -> (String, CancellationToken, tokio::task::JoinHandle<()>) { + let ct = CancellationToken::new(); + let manager = LocalSessionManager::default(); + let manager = match store { + Some(store) => manager.with_event_store(store), + None => manager, + }; + let service = StreamableHttpService::new( + move || Ok(app.clone()), + Arc::new(manager), + StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_sse_retry(Some(Duration::from_secs(1))) + .with_cancellation_token(ct.child_token()), + ); + serve_router(axum::Router::new().nest_service("/mcp", service), ct).await +} + +#[tokio::test] +async fn push_first_error_is_json_without_changing_app_owned_stream_responses() { + tokio::time::timeout(Duration::from_secs(5), async { + let runtime = EventsServer::new(); + runtime + .register_check( + push_source("source") + .authorize(|_, _, _| async { Err(EventsError::Forbidden { reason: None }) }), + |_, _, _| async { panic!("unauthorized stream must not read source") }, + ) + .unwrap(); + let (url, stop, task) = push_server(App(Some(runtime), false), None).await; + for (name, code) in [("source", -32024), ("missing", -32023)] { + let response = raw_post( + &url, + "events/stream", + json!({"name":name}), + &[("mcp-name", name)], + ) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.headers()["content-type"], "application/json"); + let body: Value = response.json().await.unwrap(); + assert_eq!(body["error"]["code"], code); + } + stop.cancel(); + task.await.unwrap(); + + let (url, stop, task) = push_server(App(None, true), None).await; + let response = raw_post(&url, "events/stream", json!({"name":"custom"}), &[]) + .send() + .await + .unwrap(); + assert_eq!(response.headers()["content-type"], "text/event-stream"); + assert!( + response + .text() + .await + .unwrap() + .contains("\"appMethod\":\"events/stream\"") + ); + let response = raw_post( + &url, + "events/stream", + json!({"name":"custom", "fail":true}), + &[], + ) + .send() + .await + .unwrap(); + assert_eq!(response.headers()["content-type"], "text/event-stream"); + assert!(response.text().await.unwrap().contains("app-owned error")); + stop.cancel(); + task.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn concurrent_push_http_streams_release_unary_slots_and_cancel_independently() { + tokio::time::timeout(Duration::from_secs(5), async { + let runtime = EventsServer::new(); + let first = runtime.register_emit(push_source("first")).unwrap(); + let second = runtime.register_emit(push_source("second")).unwrap(); + let (url, stop, task) = push_server(App(Some(runtime), false), None).await; + let transport = StreamableHttpClientTransport::from_config( + StreamableHttpClientTransportConfig::with_uri(url).max_concurrent_requests(1), + ); + let client = ClientConfig::default().serve_with_lifecycle( + transport, ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28] + }, + ).await.unwrap(); + let api = EventsClient::new(client.peer().clone()); + let mut a = api.subscribe("first", None, SubscriptionOptions::default()).await.unwrap(); + let mut b = api.subscribe("second", None, SubscriptionOptions::default()).await.unwrap(); + let Some(EventUpdate::Checkpoint(a_start)) = a.next().await else { panic!("first activation"); }; + let Some(EventUpdate::Checkpoint(b_start)) = b.next().await else { panic!("second activation"); }; + assert_ne!(a_start, b_start); + assert_eq!(api.list_page(None).await.unwrap().events.len(), 2); + first.emit(Some("a".into()), chrono::Utc::now(), JsonObject::new()).unwrap(); + second.emit(Some("b".into()), chrono::Utc::now(), JsonObject::new()).unwrap(); + assert!(matches!(a.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "a")); + assert!(matches!(b.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "b")); + drop(a); + assert!(matches!(b.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor != b_start)); + second.emit(Some("continued".into()), chrono::Utc::now(), JsonObject::new()).unwrap(); + assert!(matches!(b.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "continued")); + assert_eq!(api.list_page(None).await.unwrap().events.len(), 2); + drop(b); + client.cancel().await.unwrap(); + stop.cancel(); + task.await.unwrap(); + }).await.unwrap(); +} + +#[derive(Default)] +struct CountingStore(AtomicUsize); + +#[async_trait::async_trait] +impl EventStore for CountingStore { + async fn store_event(&self, _: &str, _: &ServerSseMessage) -> Result { + Ok(self.0.fetch_add(1, Ordering::SeqCst).to_string()) + } + + async fn replay_events_after(&self, _: &str) -> Result { + panic!("push is never resumed in the EventStore") + } +} + +#[rstest::rstest] +#[case::active_without_store(false, true)] +#[case::active_with_store(true, true)] +#[case::activating_without_store(false, false)] +#[case::activating_with_store(true, false)] +#[tokio::test] +async fn abrupt_push_http_disconnect_cancels_source( + #[case] event_store: bool, + #[case] activate: bool, +) { + tokio::time::timeout(Duration::from_secs(5), async { + let runtime = EventsServer::new(); + let entered = Arc::new(tokio::sync::Notify::new()); + let dropped = CancellationToken::new(); + runtime + .register_check(push_source("source"), { + let entered = entered.clone(); + let dropped = dropped.clone(); + move |_, _, query| { + let entered = entered.clone(); + let dropped = dropped.clone(); + async move { + if activate && query.cursor.as_deref() == Some("seed") { + let mut batch = CheckedBatch::new("ready"); + batch.has_more = true; + return Ok(batch); + } + let _on_drop = dropped.drop_guard(); + entered.notify_one(); + std::future::pending().await + } + } + }) + .unwrap(); + let store = Arc::new(CountingStore::default()); + let events: Arc = store.clone(); + let (url, stop, task) = + push_server(App(Some(runtime), false), event_store.then_some(events)).await; + let request = raw_post( + &url, + "events/stream", + json!({"name":"source","cursor":"seed"}), + &[("mcp-name", "source")], + ); + if activate { + let mut response = request.send().await.unwrap(); + assert_eq!(response.headers()["content-type"], "text/event-stream"); + let mut data = Vec::new(); + while !data.windows(2).any(|w| w == b"\n\n") { + data.extend(response.chunk().await.unwrap().unwrap()); + } + let data = String::from_utf8(data).unwrap(); + assert!( + data.contains("\"method\":\"notifications/events/active\""), + "{data}" + ); + assert!( + !data + .lines() + .any(|line| line.starts_with("id:") || line.starts_with("retry:")), + "{data}" + ); + entered.notified().await; + drop(response); + } else { + let pending = tokio::spawn(request.send()); + entered.notified().await; + pending.abort(); + assert!(pending.await.unwrap_err().is_cancelled()); + } + dropped.cancelled().await; + assert_eq!(store.0.load(Ordering::SeqCst), 0); + stop.cancel(); + task.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn push_http_eof_reopens_with_events_cursor_and_fresh_request_id() { + use axum::{ + body::{Body, to_bytes}, + extract::Request, + http::Response, + middleware::{Next, from_fn}, + }; + + tokio::time::timeout(Duration::from_secs(5), async { + let runtime = EventsServer::new(); + runtime.register_emit(push_source("source")).unwrap(); + let ids = Arc::new(std::sync::Mutex::new(Vec::new())); + let capture = ids.clone(); + let middleware = from_fn(move |request: Request, next: Next| { + let capture = capture.clone(); + async move { + if request.headers().get("mcp-method").and_then(|header| header.to_str().ok()) != Some("events/stream") { + return next.run(request).await; + } + assert_eq!(request.method(), "POST"); + assert_eq!(request.headers()["mcp-name"], "source"); + assert!(!request.headers().contains_key("last-event-id")); + let body = to_bytes(request.into_body(), 8192).await.unwrap(); + let request: Value = serde_json::from_slice(&body).unwrap(); + let id = request["id"].clone(); + let cursor = request["params"]["cursor"].clone(); + let first = { + let mut seen = capture.lock().unwrap(); + seen.push((id.clone(), cursor)); + seen.len() == 1 + }; + let frame = |method: &str, mut params: Value| { + params["_meta"] = json!({"io.modelcontextprotocol/subscriptionId":id}); + let value = json!({ + "jsonrpc":"2.0","method":format!("notifications/events/{method}"),"params":params + }); + format!("data: {value}\n\n") + }; + let event = |event: &str, cursor: &str| frame("event", json!({ + "eventId":event, "name":"source", "timestamp":"2026-07-28T00:00:00Z", + "data":{}, "cursor":cursor + })); + let mut body = frame("active", json!({ + "cursor":if first {"head"} else {"cursor-a"}, "heartbeatMs":30_000 + })); + body += &event("a", "cursor-a"); + if !first { + body += &event("b", "cursor-b"); + body += &frame("terminated", json!({ + "error":{"code":-32024,"message":"Forbidden","data":{"reason":"revoked"}} + })); + } + Response::builder() + .header("content-type", "text/event-stream") + .body(Body::from(body)).unwrap() + } + }); + let stop = CancellationToken::new(); + let service: StreamableHttpService = StreamableHttpService::new( + move || Ok(App(Some(runtime.clone()), false)), + Default::default(), + StreamableHttpServerConfig::default() + .with_json_response(true) + .with_legacy_session_mode(false) + .with_cancellation_token(stop.child_token()), + ); + let router = axum::Router::new().nest_service("/mcp", service).layer(middleware); + let (url, stop, task) = serve_router(router, stop).await; + let client = connect(url).await; + let api = EventsClient::new(client.peer().clone()); + let mut events = api.subscribe("source", None, SubscriptionOptions::default()).await.unwrap(); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head")); + assert!(matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == "a")); + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "cursor-a")); + assert!(matches!(events.next().await, Some(EventUpdate::RecoverableError(_)))); + for id in ["a", "b"] { + assert!(matches!(events.next().await, Some(EventUpdate::Occurrence(event)) if event.event_id == id)); + } + assert!(matches!(events.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "cursor-b")); + assert!(matches!(events.next().await, Some(EventUpdate::Terminated(EventsError::Forbidden { reason: Some(reason) })) if reason == "revoked")); + assert!(events.next().await.is_none()); + { + let seen = ids.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert_ne!(seen[0].0, seen[1].0); + assert!(seen[0].1.is_null()); + assert_eq!(seen[1].1, "cursor-a"); + } + client.cancel().await.unwrap(); + stop.cancel(); + task.await.unwrap(); + }).await.unwrap(); +} + +#[tokio::test] +async fn headers_validate_and_client_relists_after_schema_replacement() { + use base64::{Engine, prelude::BASE64_STANDARD}; + + let runtime = EventsServer::new(); + let name = "é fixture"; + let region = " =?base64?hello?= "; + let name_header = format!("=?base64?{}?=", BASE64_STANDARD.encode(name)); + let region_header = format!("=?base64?{}?=", BASE64_STANDARD.encode(region)); + let reads = Arc::new(AtomicUsize::new(0)); + let checks = Arc::new(AtomicUsize::new(0)); + let authorize = { + let checks = checks.clone(); + move |context: EventContext, args: JsonObject, mode| { + assert_eq!(mode, DeliveryMode::Poll); + let parts = context + .extensions + .get::() + .unwrap(); + assert!(parts.extensions.get::().is_some()); + checks.fetch_add(1, Ordering::SeqCst); + std::future::ready(if args.contains_key("deny") { + Err(EventsError::Forbidden { + reason: Some("fixture denial".into()), + }) + } else { + Ok(()) + }) + } + }; + runtime + .register_check(descriptor(name, "Region").authorize(authorize.clone()), { + let reads = reads.clone(); + move |_, args: JsonObject, _| { + reads.fetch_add(1, Ordering::SeqCst); + std::future::ready(if args.contains_key("busy") { + Err(EventsError::ResourceExhausted { + limit: "checkBudget".into(), + max: Some(1), + }) + } else { + Ok(CheckedBatch::new("now")) + }) + } + }) + .unwrap(); + + let (url, stop, server) = server(App(Some(runtime.clone()), false)).await; + let args = json!({"name":name,"arguments":{"region":region},"cursor":null}); + let (status, response) = raw(&url, "events/poll", args.clone(), &[]).await; + assert_eq!(status, 400); + assert_eq!(response["error"]["code"], -32020); + for headers in [ + [ + ("mcp-name", "wrong"), + ("mcp-param-region", region_header.as_str()), + ], + [ + ("mcp-name", name_header.as_str()), + ("mcp-param-region", "wrong"), + ], + ] { + let (status, response) = raw(&url, "events/poll", args.clone(), &headers).await; + assert_eq!(status, 400); + assert_eq!(response["error"]["code"], -32020); + } + for method in [ + "events/poll", + "events/stream", + "events/subscribe", + "events/unsubscribe", + ] { + let (status, response) = + raw(&url, method, args.clone(), &[("mcp-name", &name_header)]).await; + assert_eq!(status, 400); + assert_eq!(response["error"]["code"], -32020); + } + let (status, response) = raw( + &url, + "events/poll", + args.clone(), + &[ + ("mcp-name", &name_header), + ("mcp-param-region", ®ion_header), + ("mcp-param-region", ®ion_header), + ], + ) + .await; + assert_eq!(status, 400); + assert_eq!(response["error"]["code"], -32020); + let mut deny = args.clone(); + deny["arguments"]["deny"] = json!(true); + let (status, response) = raw( + &url, + "events/poll", + deny, + &[ + ("mcp-name", &name_header), + ("mcp-param-region", ®ion_header), + ], + ) + .await; + assert_eq!(status, 200); + assert_eq!(response["error"]["code"], -32024); + assert_eq!(response["error"]["data"]["reason"], "fixture denial"); + assert_eq!(checks.load(Ordering::SeqCst), 1); + assert_eq!(reads.load(Ordering::SeqCst), 0); + let mut invalid_limit = args.clone(); + invalid_limit["maxEvents"] = json!(0); + let (status, response) = raw( + &url, + "events/poll", + invalid_limit, + &[ + ("mcp-name", &name_header), + ("mcp-param-region", ®ion_header), + ], + ) + .await; + assert_eq!(status, 200); + assert_eq!(response["error"]["code"], -32602); + let (status, response) = raw( + &url, + "events/stream", + args.clone(), + &[ + ("mcp-name", &name_header), + ("mcp-param-region", ®ion_header), + ], + ) + .await; + assert_eq!(status, 200); + assert_eq!(response["error"]["code"], -32026); + assert_eq!( + response["error"]["data"], + json!({"feature":"deliveryMode","value":"push"}) + ); + let (status, response) = raw( + &url, + "events/poll", + json!({"name":"missing"}), + &[("mcp-name", "missing")], + ) + .await; + assert_eq!(status, 200); + assert_eq!(response["error"]["code"], -32023); + assert_eq!(response["error"]["data"]["kind"], "event"); + let (status, response) = raw(&url, "events/list", json!({}), &[]).await; + assert_eq!(status, 200); + assert_eq!(response["result"]["events"][0]["name"], name); + + let client = connect(url.clone()).await; + let events = EventsClient::new(client.peer().clone()); + let mut params = PollParams::new(name); + params.arguments = Some(args["arguments"].as_object().unwrap().clone()); + assert_eq!( + events.poll(params.clone()).await.unwrap().cursor.as_deref(), + Some("now") + ); + runtime + .replace( + descriptor(name, "Updated").authorize(authorize), + Replacement::Additive, + ) + .unwrap(); + // The client's cached Region header cannot pass the second authorization + // unless it fetched the new descriptor and retried with Updated. + assert_eq!( + events.poll(params.clone()).await.unwrap().cursor.as_deref(), + Some("now") + ); + assert_eq!(reads.load(Ordering::SeqCst), 2); + assert_eq!(checks.load(Ordering::SeqCst), 3); + let (status, response) = raw( + &url, + "events/poll", + json!({"name": name, "arguments": {"busy": true}}), + &[("mcp-name", &name_header)], + ) + .await; + assert_eq!(status, 200); + assert_eq!(response["error"]["code"], -32025); + assert_eq!( + response["error"]["data"], + json!({"limit":"checkBudget","max":1}) + ); + assert!(matches!( + runtime.replace(descriptor(name, "not a token"), Replacement::Additive), + Err(EventsError::InvalidParams(_)) + )); + + client.cancel().await.unwrap(); + stop.cancel(); + server.await.unwrap(); +} + +#[tokio::test] +async fn push_reopens_after_relisting_changed_routing_headers() { + tokio::time::timeout(Duration::from_secs(5), async { + let runtime = EventsServer::new(); + let annotated = |annotation: &str| { + Descriptor::raw( + EventDescriptor::new( + "source", + "", + vec![DeliveryMode::Push], + input_schema(annotation), + Default::default(), + ), + |_| Ok(()), + ) + }; + runtime + .register_check(annotated("Region"), |_, _, _| async { + Ok(CheckedBatch::new("head")) + }) + .unwrap(); + let (url, stop, task) = push_server(App(Some(runtime.clone()), false), None).await; + let client = connect(url).await; + let api = EventsClient::new(client.peer().clone()); + let arguments = json!({"region":"test"}).as_object().unwrap().clone(); + let mut stream = api + .subscribe("source", Some(arguments.clone()), Default::default()) + .await + .unwrap(); + assert!( + matches!(stream.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + drop(stream); + runtime + .replace(annotated("Updated"), Replacement::Additive) + .unwrap(); + let mut stream = api + .subscribe("source", Some(arguments.clone()), Default::default()) + .await + .unwrap(); + assert!( + matches!(stream.next().await, Some(EventUpdate::Checkpoint(cursor)) if cursor == "head") + ); + + runtime + .replace(descriptor("source", "Updated"), Replacement::Breaking) + .unwrap(); + assert!(matches!(stream.next().await, Some(EventUpdate::Terminated( + EventsError::Unsupported { reason: Some(reason), .. } + )) if reason == "schema_changed")); + // The caller's cache must now know about the poll-only replacement. + let mut options = SubscriptionOptions::default(); + options.mode = Some(DeliveryMode::Push); + assert!( + matches!(api.subscribe("source", Some(arguments), options).await, + Err(EventsError::Unsupported { value: Some(value), .. }) if value == "push") + ); + client.cancel().await.unwrap(); + stop.cancel(); + task.await.unwrap(); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn paginated_catalog_excludes_invalid_annotations() { + use axum::{ + body::Bytes, + extract::State, + http::{HeaderMap, header}, + response::IntoResponse, + routing::post, + }; + #[derive(Default)] + struct Observed { + first: AtomicUsize, + next: AtomicUsize, + poll: AtomicUsize, + } + async fn serve( + State(observed): State>, + headers: HeaderMap, + bytes: Bytes, + ) -> impl IntoResponse { + let call: Value = serde_json::from_slice(&bytes).unwrap(); + let annotated = |name, header| { + json!({ + "name": name, "delivery":["poll"], "payloadSchema": {}, + "inputSchema":{"properties":{ + "count":{"type":"integer","x-mcp-header":header}, + "enabled":{"type":"boolean","x-mcp-header":"Enabled"}, + }} + }) + }; + let payload = match call["method"].as_str().unwrap() { + "server/discover" => json!({"result":{ + "resultType":"complete","ttlMs":0,"cacheScope":"private", + "supportedVersions":["2026-07-28"], "capabilities":{"extensions":{"io.modelcontextprotocol/events":{}}} + }}), + "events/list" => { + assert!(!headers.contains_key("mcp-name")); + if call["params"]["cursor"] == "next" { + observed.next.fetch_add(1, Ordering::SeqCst); + json!({"result":{"events":[annotated("valid","Count")]}}) + } else { + observed.first.fetch_add(1, Ordering::SeqCst); + json!({"result":{"events":[annotated("invalid","not a token")],"nextCursor":"next"}}) + } + } + "events/poll" => { + let attempt = observed.poll.fetch_add(1, Ordering::SeqCst); + assert_eq!(headers["mcp-name"], "valid"); + assert_eq!(headers["mcp-param-count"], "42"); + assert_eq!(headers["mcp-param-enabled"], "true"); + match attempt { + 0 => json!({"error":{"code":-32020,"message":"routing changed"}}), + 2 => json!({"result":{"resultType":"complete","cursor":"past-event","events":[ + {"eventId":"unparseable","name":"valid","timestamp":"20261124T120000Z","data":{}} + ]}}), + _ => json!({"result":{"resultType":"complete","events":[],"cursor":"head"}}), + } + } + other => panic!("unexpected fixture method {other}"), + }; + let mut response = json!({"jsonrpc":"2.0","id":call["id"]}); + response + .as_object_mut() + .unwrap() + .extend(payload.as_object().unwrap().clone()); + ( + [(header::CONTENT_TYPE, "application/json")], + response.to_string(), + ) + } + let observed = Arc::new(Observed::default()); + let router = axum::Router::new() + .route("/mcp", post(serve)) + .with_state(observed.clone()); + let (url, stop, task) = serve_router(router, CancellationToken::new()).await; + let client = connect(url).await; + let events = EventsClient::new(client.peer().clone()); + assert!(matches!( + events.poll(PollParams::new("invalid")).await, + Err(EventsError::NotFound { .. }) + )); + assert_eq!(observed.poll.load(Ordering::SeqCst), 0); + let mut params = PollParams::new("valid"); + params.arguments = json!({"count":42,"enabled":true}).as_object().cloned(); + events.poll(params.clone()).await.unwrap(); + assert_eq!(observed.poll.load(Ordering::SeqCst), 2); + assert_eq!(observed.first.load(Ordering::SeqCst), 2); + assert_eq!(observed.next.load(Ordering::SeqCst), 2); + assert!(matches!( + events.poll(params).await, + Err(EventsError::UnexpectedResponse) + )); + client.cancel().await.unwrap(); + stop.cancel(); + task.await.unwrap(); +} + +async fn connect(url: String) -> rmcp::service::RunningService { + ClientConfig::default() + .serve_with_lifecycle( + StreamableHttpClientTransport::from_config( + StreamableHttpClientTransportConfig::with_uri(url), + ), + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28], + }, + ) + .await + .unwrap() +} + +#[tokio::test] +async fn numeric_and_boolean_mirrors_round_trip_through_tower() { + let runtime = EventsServer::new(); + let schema = json!({"properties":{ + "count":{"type":"integer","x-mcp-header":"Count"}, + "enabled":{"type":"boolean","x-mcp-header":"Enabled"}, + }}); + let descriptor = Descriptor::raw( + EventDescriptor::new( + "counter", + "", + vec![DeliveryMode::Poll], + schema.as_object().unwrap().clone().into(), + Default::default(), + ), + |_| Ok(()), + ); + runtime + .register_check(descriptor, |_, _, _| { + std::future::ready(Ok(CheckedBatch::new("head"))) + }) + .unwrap(); + let (url, stop, task) = server(App(Some(runtime), false)).await; + let (status, result) = raw( + &url, + "events/poll", + json!({"name":"counter","arguments":{"count":42,"enabled":true}}), + &[ + ("mcp-name", "counter"), + ("mcp-param-count", "42"), + ("mcp-param-enabled", "true"), + ], + ) + .await; + assert_eq!(status, 200); + assert_eq!(result["result"]["cursor"], "head"); + let (status, result) = raw( + &url, + "events/poll", + json!({"name":"counter","arguments":{"count":42,"enabled":true}}), + &[ + ("mcp-name", "counter"), + ("mcp-param-count", "42.0"), + ("mcp-param-enabled", "true"), + ], + ) + .await; + assert_eq!(status, 400); + assert_eq!(result["error"]["code"], -32020); + let client = connect(url).await; + let mut params = PollParams::new("counter"); + params.arguments = json!({"count":42.0,"enabled":false}).as_object().cloned(); + assert_eq!( + EventsClient::new(client.peer().clone()) + .poll(params) + .await + .unwrap() + .cursor + .as_deref(), + Some("head") + ); + client.cancel().await.unwrap(); + stop.cancel(); + task.await.unwrap(); +} + +#[tokio::test] +async fn absent_runtime_is_method_not_found_over_modern_http() { + let (url, stop, task) = server(App(None, false)).await; + let (status, result) = raw(&url, "events/list", json!({}), &[]).await; + assert_eq!(status, 404); + assert_eq!(result["error"]["code"], -32601); + stop.cancel(); + task.await.unwrap(); + + let (url, stop, task) = server(App(None, true)).await; + let (status, result) = raw(&url, "events/poll", json!({"name":"app-owned"}), &[]).await; + assert_eq!(status, 200); + assert_eq!(result["result"]["appMethod"], "events/poll"); + stop.cancel(); + task.await.unwrap(); +} diff --git a/crates/rmcp/tests/test_message_schema.rs b/crates/rmcp/tests/test_message_schema.rs index 027a2cc86..f879a6481 100644 --- a/crates/rmcp/tests/test_message_schema.rs +++ b/crates/rmcp/tests/test_message_schema.rs @@ -17,6 +17,22 @@ mod tests { serde_json::from_str(actual).expect("Failed to parse actual schema as JSON"); let expected_json: serde_json::Value = serde_json::from_str(&expected).expect("Failed to parse expected schema as JSON"); + #[cfg(feature = "events")] + let expected_json = { + // Regenerate by running this test with `events` enabled, then + // copy the Events-only `definitions.SubscriptionFilter.properties` + // entries from the generated *_current.json into the overlay. + // Do not overwrite the feature-off snapshot with that output. + let mut expected = expected_json; + let overlay = include_str!("test_message_schema/events_subscription_filter.json"); + let map: serde_json::Map = + serde_json::from_str(overlay).expect("valid Events schema overlay"); + expected["definitions"]["SubscriptionFilter"]["properties"] + .as_object_mut() + .expect("subscription filter properties") + .extend(map); + expected + }; if actual_json == expected_json { println!("{} schema matches expected", name); @@ -36,12 +52,14 @@ mod tests { ); // UPDATE_SCHEMA=1 cargo test -p rmcp --test test_message_schema --features="server client schemars" - if std::env::var("UPDATE_SCHEMA").is_ok() { + if std::env::var("UPDATE_SCHEMA").is_ok() && !cfg!(feature = "events") { println!("UPDATE_SCHEMA is set, updating expected file"); std::fs::write(expected_file, actual).expect("Failed to update expected schema file"); println!("Updated {}", expected_file); } else { - println!("Set UPDATE_SCHEMA=1 to auto-update expected schemas"); + println!( + "Set UPDATE_SCHEMA=1 without `events` to update the core snapshots; update the Events overlay separately" + ); panic!("Schema validation failed"); } } diff --git a/crates/rmcp/tests/test_message_schema/events_subscription_filter.json b/crates/rmcp/tests/test_message_schema/events_subscription_filter.json new file mode 100644 index 000000000..3d7c4d575 --- /dev/null +++ b/crates/rmcp/tests/test_message_schema/events_subscription_filter.json @@ -0,0 +1,5 @@ +{ + "eventsListChanged": { + "type": "boolean" + } +} diff --git a/crates/rmcp/tests/test_streamable_http_event_store.rs b/crates/rmcp/tests/test_streamable_http_event_store.rs index 979ce7e66..6c984b575 100644 --- a/crates/rmcp/tests/test_streamable_http_event_store.rs +++ b/crates/rmcp/tests/test_streamable_http_event_store.rs @@ -12,16 +12,19 @@ use std::{ Arc, atomic::{AtomicU64, Ordering}, }, + time::Duration, }; use futures::StreamExt; +use http::{Request, StatusCode}; +use http_body_util::{BodyExt, Full}; use rmcp::{ ErrorData, ServerHandler, model::{ CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, - ProgressNotificationParam, ServerCapabilities, ServerConfig, + ProgressNotificationParam, ServerCapabilities, ServerConfig, SubscriptionFilter, }, - service::RequestContext, + service::{RequestContext, SubscriptionContext}, transport::streamable_http_server::{ StreamableHttpServerConfig, StreamableHttpService, session::{ @@ -32,6 +35,7 @@ use rmcp::{ }; use tokio::sync::RwLock; use tokio_util::sync::CancellationToken; +use tower_service::Service; #[derive(Clone, Default)] struct InMemorySessionStore(Arc>>); @@ -105,6 +109,110 @@ impl EventStore for InMemoryEventStore { } } +#[derive(Clone)] +struct ListenServer { + cancelled: CancellationToken, +} + +impl ServerHandler for ListenServer { + fn get_info(&self) -> ServerConfig { + ServerConfig::new( + ServerCapabilities::builder() + .enable_tools() + .enable_tool_list_changed() + .build(), + ) + } + + fn accepted_subscription_filter( + &self, + requested: &SubscriptionFilter, + ) -> Option { + Some(requested.clone()) + } + + async fn listen(&self, context: SubscriptionContext) -> Result<(), ErrorData> { + context.sink().notify_tool_list_changed().await.unwrap(); + context.cancelled().await; + self.cancelled.cancel(); + Ok(()) + } +} + +#[rstest::rstest] +#[case::sse(false)] +#[case::json(true)] +#[tokio::test] +async fn modern_listen_bypasses_event_store_and_cancels_on_disconnect( + #[case] json_response: bool, +) -> anyhow::Result<()> { + tokio::time::timeout(Duration::from_secs(5), async { + let event_store = Arc::new(InMemoryEventStore::default()); + let cancelled = CancellationToken::new(); + let handler = ListenServer { + cancelled: cancelled.clone(), + }; + let mut service = StreamableHttpService::new( + move || Ok(handler.clone()), + Arc::new(LocalSessionManager::default().with_event_store(event_store.clone())), + StreamableHttpServerConfig::default() + .with_json_response(json_response) + .with_sse_keep_alive(None) + .with_sse_retry(Some(Duration::from_secs(1))), + ); + let request = Request::post("/mcp") + .header("Host", "localhost") + .header("Content-Type", "application/json") + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", "2026-07-28") + .header("Mcp-Method", "subscriptions/listen") + .body(Full::new(bytes::Bytes::from_static( + br#"{ + "jsonrpc":"2.0", + "id":1, + "method":"subscriptions/listen", + "params":{ + "notifications":{"toolsListChanged":true}, + "_meta":{ + "io.modelcontextprotocol/protocolVersion":"2026-07-28", + "io.modelcontextprotocol/clientInfo":{"name":"test","version":"1.0"}, + "io.modelcontextprotocol/clientCapabilities":{} + } + } + }"#, + )))?; + let response = service.call(request).await?; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()["content-type"], "text/event-stream"); + assert!(!response.headers().contains_key("mcp-session-id")); + + let mut body = response.into_body(); + for method in [ + "notifications/subscriptions/acknowledged", + "notifications/tools/list_changed", + ] { + let data = body + .frame() + .await + .expect("listen stream is open")? + .into_data() + .expect("SSE data frame"); + let frame = std::str::from_utf8(&data)?; + assert!(frame.contains(method), "unexpected SSE frame: {frame}"); + assert!(!frame.lines().any(|line| line.starts_with("id:"))); + assert!(!frame.lines().any(|line| line.starts_with("retry:"))); + } + + // Dropping the Tower response body is the transport's disconnect signal. + assert!(!cancelled.is_cancelled()); + drop(body); + cancelled.cancelled().await; + assert!(event_store.events.read().await.is_empty()); + Ok(()) + }) + .await? +} + #[derive(Clone)] struct ProgressServer; diff --git a/crates/rmcp/tests/test_subscriptions.rs b/crates/rmcp/tests/test_subscriptions.rs index 735953007..6c5f4878e 100644 --- a/crates/rmcp/tests/test_subscriptions.rs +++ b/crates/rmcp/tests/test_subscriptions.rs @@ -18,17 +18,22 @@ use rmcp::{ ClientHandler, ClientServiceExt, ServerHandler, ServiceExt, model::{ ClientNotification, ClientRequest, DiscoverResult, GetMeta, Implementation, - NotificationMetaObject, PromptListChangedNotification, ProtocolVersion, ServerCapabilities, + ListToolsResult, NotificationMetaObject, PaginatedRequestParams, + PromptListChangedNotification, ProtocolVersion, RequestId, ServerCapabilities, ServerConfig, ServerNotification, ServerResult, SubscriptionFilter, SubscriptionsAcknowledgedNotification, SubscriptionsAcknowledgedNotificationParams, - SubscriptionsListenResult, + SubscriptionsListenResult, ToolListChangedNotification, }, service::{ NotificationContext, RequestContext, RoleClient, RoleServer, SubscriptionContext, SubscriptionEnd, SubscriptionSendError, SubscriptionSink, }, }; -use tokio::sync::{Mutex, Notify}; +use serde_json::json; +use tokio::{ + io::{AsyncBufReadExt, AsyncWriteExt, BufReader}, + sync::{Mutex, Notify}, +}; struct ToolsOnlyServer; @@ -362,6 +367,150 @@ impl ServerHandler for CancellationServer { } } +#[derive(Default)] +struct NotificationFenceServer { + send_active: Notify, +} + +fn correlated_tool_list_changed(id: i64) -> ServerNotification { + let mut notification = + ServerNotification::ToolListChangedNotification(ToolListChangedNotification { + method: Default::default(), + extensions: Default::default(), + }); + notification + .get_meta_mut() + .set_subscription_id(RequestId::Number(id)); + notification +} + +impl ServerHandler for NotificationFenceServer { + fn get_info(&self) -> ServerConfig { + ToolsOnlyServer.get_info() + } + + fn accepted_subscription_filter( + &self, + requested: &SubscriptionFilter, + ) -> Option { + Some(requested.clone()) + } + + async fn listen(&self, context: SubscriptionContext) -> Result<(), rmcp::ErrorData> { + if *context.sink().id() == RequestId::Number(1) { + // The serve loop removes the ID before it cancels this token. + context.cancelled().await; + let peer = &context.request_context().peer; + // Send through the peer, bypassing the sink's closed-state check, + // so the stale frame actually reaches the serve-loop queue. + peer.send_notification(correlated_tool_list_changed(1)) + .await + .unwrap(); + peer.notify_tool_list_changed().await.unwrap(); + self.send_active.notify_one(); + } else { + self.send_active.notified().await; + context.sink().notify_tool_list_changed().await.unwrap(); + } + Ok(()) + } + + async fn list_tools( + &self, + _request: Option, + context: RequestContext, + ) -> Result { + // The client has already received the normal listen response for ID 2. + context + .peer + .send_notification(correlated_tool_list_changed(2)) + .await + .unwrap(); + Ok(ListToolsResult::default()) + } +} + +#[rstest::rstest] +#[case::cancel_then_complete(true)] +#[case::complete_without_cancellation(false)] +#[tokio::test] +async fn stdio_fences_inactive_subscriptions(#[case] cancel_first: bool) -> anyhow::Result<()> { + tokio::time::timeout(Duration::from_secs(5), async { + let (server_io, client_io) = tokio::io::duplex(4096); + let server = tokio::spawn(async move { + let handler = NotificationFenceServer::default(); + if !cancel_first { + handler.send_active.notify_one(); + } + handler.serve(server_io).await?.waiting().await?; + anyhow::Ok(()) + }); + let (read, mut write) = tokio::io::split(client_io); + let mut read = BufReader::new(read).lines(); + let meta = json!({ + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": {"name":"test","version":"1.0"}, + "io.modelcontextprotocol/clientCapabilities": {} + }); + let send = |message: serde_json::Value| format!("{message}\n").into_bytes(); + let decoded = |line: Option| -> anyhow::Result { + Ok(serde_json::from_str(&line.expect("server frame"))?) + }; + const SUBSCRIPTION_ID: &str = "io.modelcontextprotocol/subscriptionId"; + + write + .write_all(&send(json!({ + "jsonrpc":"2.0", "id":0, "method":"server/discover", "params":{"_meta":meta} + }))) + .await?; + assert!(decoded(read.next_line().await?)?.get("result").is_some()); + + let listen_ids: &[_] = if cancel_first { &[1, 2] } else { &[2] }; + for &id in listen_ids { + write + .write_all(&send(json!({ + "jsonrpc":"2.0", "id":id, "method":"subscriptions/listen", + "params":{"_meta":meta, "notifications":{"toolsListChanged":true}} + }))) + .await?; + let ack = decoded(read.next_line().await?)?; + assert_eq!(ack["method"], "notifications/subscriptions/acknowledged"); + assert_eq!(ack["params"]["_meta"][SUBSCRIPTION_ID], id); + } + + if cancel_first { + write + .write_all(&send(json!({ + "jsonrpc":"2.0", "method":"notifications/cancelled", "params":{"requestId":1} + }))) + .await?; + let uncorrelated = decoded(read.next_line().await?)?; + assert_eq!(uncorrelated["method"], "notifications/tools/list_changed"); + assert!(uncorrelated["params"]["_meta"][SUBSCRIPTION_ID].is_null()); + } + let active = decoded(read.next_line().await?)?; + assert_eq!(active["method"], "notifications/tools/list_changed"); + assert_eq!(active["params"]["_meta"][SUBSCRIPTION_ID], 2); + let completed = decoded(read.next_line().await?)?; + assert_eq!(completed["id"], 2); + assert!(completed.get("result").is_some()); + + write + .write_all(&send(json!({ + "jsonrpc":"2.0", "id":3, "method":"tools/list", "params":{"_meta":meta} + }))) + .await?; + let tools = decoded(read.next_line().await?)?; + assert_eq!(tools["id"], 3, "expected tools/list response, got {tools}"); + assert_eq!(tools["result"]["tools"], json!([])); + + write.shutdown().await?; + server.await??; + Ok(()) + }) + .await? +} + #[derive(Clone)] struct AbruptServer { started: Arc, diff --git a/examples/clients/Cargo.toml b/examples/clients/Cargo.toml index a9d0761a5..2bee3039a 100644 --- a/examples/clients/Cargo.toml +++ b/examples/clients/Cargo.toml @@ -6,6 +6,14 @@ version = "0.1.5" edition = "2024" publish = false +[features] +events = ["rmcp/events"] + +[[example]] +name = "clients_events_stdio" +path = "src/events_stdio.rs" +required-features = ["events"] + [dependencies] rmcp = { workspace = true, features = [ "client", diff --git a/examples/clients/src/events_stdio.rs b/examples/clients/src/events_stdio.rs new file mode 100644 index 000000000..5ce416ed2 --- /dev/null +++ b/examples/clients/src/events_stdio.rs @@ -0,0 +1,52 @@ +//! Run with the path to the built `servers_events_stdio` executable. + +use futures::StreamExt; +use rmcp::{ + ClientLifecycleMode, ClientServiceExt, + events::{ + client::{EventUpdate, EventsClient, SubscriptionOptions}, + wire::PollParams, + }, + model::{ClientConfig, ProtocolVersion}, + transport::TokioChildProcess, +}; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> anyhow::Result<()> { + let executable = std::env::args_os().nth(1).ok_or_else(|| { + anyhow::anyhow!("usage: clients_events_stdio ") + })?; + let transport = TokioChildProcess::new(tokio::process::Command::new(executable))?; + let client = ClientConfig::default() + .serve_with_lifecycle( + transport, + ClientLifecycleMode::Discover { + preferred_versions: vec![ProtocolVersion::V_2026_07_28], + }, + ) + .await?; + let events = EventsClient::new(client.peer().clone()); + let page = events.list_page(None).await?; + for event in page.events { + println!("{}: {}", event.name, event.description); + } + let bootstrap = events.poll(PollParams::new("demo.sample")).await?; + let mut options = SubscriptionOptions::default(); + options.cursor = bootstrap.cursor; + // The descriptor advertises both modes; subscribe prefers push. + let mut subscription = events.subscribe("demo.sample", None, options).await?; + while let Some(update) = subscription.next().await { + match update { + EventUpdate::Occurrence(event) => println!("event {}", event.event_id), + EventUpdate::Checkpoint(cursor) => { + println!("checkpoint {cursor}"); + break; + } + EventUpdate::Terminated(error) => return Err(error.into()), + _ => {} + } + } + drop(subscription); + client.cancel().await?; + Ok(()) +} diff --git a/examples/servers/Cargo.toml b/examples/servers/Cargo.toml index 93bf90e8c..2080a4fe1 100644 --- a/examples/servers/Cargo.toml +++ b/examples/servers/Cargo.toml @@ -4,6 +4,9 @@ version = "0.1.5" edition = "2024" publish = false +[features] +events = ["rmcp/events"] + [dependencies] rmcp = { workspace = true, features = [ "server", @@ -128,3 +131,8 @@ path = "src/subscriptions_streamhttp.rs" [[example]] name = "servers_skills_stdio" path = "src/skills_stdio.rs" + +[[example]] +name = "servers_events_stdio" +path = "src/events_stdio.rs" +required-features = ["events"] diff --git a/examples/servers/src/events_stdio.rs b/examples/servers/src/events_stdio.rs new file mode 100644 index 000000000..98bef307b --- /dev/null +++ b/examples/servers/src/events_stdio.rs @@ -0,0 +1,58 @@ +//! An Events check source with one sample event. + +use std::{future::ready, sync::OnceLock}; + +use rmcp::{ + ServerHandler, ServiceExt, + events::{ + server::{CheckedBatch, Descriptor, EventsServer}, + wire::{DeliveryMode, EventOccurrence, EventsError}, + }, + model::JsonObject, + transport::stdio, +}; + +struct Server(EventsServer); + +impl ServerHandler for Server { + fn events(&self) -> Option<&EventsServer> { + Some(&self.0) + } +} + +#[tokio::main(flavor = "current_thread")] +async fn main() -> anyhow::Result<()> { + let server = EventsServer::new(); + let sample_time = OnceLock::new(); + server.register_check( + Descriptor::typed::( + "demo.sample", + "A sample generated by the first replay request", + [DeliveryMode::Poll, DeliveryMode::Push], + ), + move |_, _, query| { + let mut batch = CheckedBatch::new("1"); + match query.cursor.as_deref() { + None if sample_time.get().is_none() => batch.end = "0".into(), + None | Some("1") => {} + Some("0") => { + let time = *sample_time.get_or_init(chrono::Utc::now); + if query.age_floor.is_some_and(|floor| time < floor) { + batch.start = Some("1".into()); + } else { + batch.events.push(EventOccurrence::new( + "sample", + "demo.sample", + time, + JsonObject::new(), + )); + } + } + _ => return ready(Err(EventsError::InvalidParams("unknown cursor".into()))), + } + ready(Ok(batch)) + }, + )?; + Server(server).serve(stdio()).await?.waiting().await?; + Ok(()) +}