Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/rmcp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ features = [
"client",
"client-side-sse",
"elicitation",
"events",
"events-webhook",
"events-webhook-receiver",
"macros",
"request-state",
"reqwest",
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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"] }
Expand Down
3 changes: 3 additions & 0 deletions crates/rmcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
86 changes: 86 additions & 0 deletions crates/rmcp/src/events.rs
Original file line number Diff line number Diff line change
@@ -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::<JsonObject, JsonObject>("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<crate::model::JsonObject>,
#[serde(skip_serializing_if = "Option::is_none")]
cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
max_age_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
heartbeat_ms: Option<u64>,
}

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"
)
}
240 changes: 240 additions & 0 deletions crates/rmcp/src/events/client.rs
Original file line number Diff line number Diff line change
@@ -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<RoleClient>,
catalog: Arc<tokio::sync::Mutex<HashMap<String, CatalogEntry>>>,
}

#[derive(Clone)]
struct CatalogEntry {
delivery: Vec<DeliveryMode>,
input_schema: Arc<JsonObject>,
}

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<Arc<crate::model::JsonObject>>);

impl EventsClient {
/// Use a peer whose discovery result advertises Events.
pub fn new(peer: Peer<RoleClient>) -> 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<ListEventsResult, EventsError> {
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<ListEventsResult, EventsError> {
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<PollResult, EventsError> {
self.require_advertisement()?;
let body = encode_params(&params)?;
self.with_route(&params.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<ServerResult, EventsError> {
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<T, F: std::future::Future<Output = Result<T, EventsError>>>(
&self,
name: &str,
request: impl Fn(CatalogEntry) -> F,
) -> Result<T, EventsError> {
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<CatalogEntry, EventsError> {
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<HashMap<String, CatalogEntry>, 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<T: DeserializeOwned>(result: ServerResult) -> Result<T, EventsError> {
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<Value, EventsError> {
serde_json::to_value(params)
.map_err(|_| EventsError::InvalidParams("invalid Events parameters".into()))
}

fn route(method: &str, params: Value, schema: Arc<JsonObject>) -> 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"));
}
}
Loading