feat: add support for custom server notifications (#580)

https://github.com/modelcontextprotocol/rust-sdk/pull/556 introduced support for
custom client notifications, so this PR makes the complementary change, adding
support for custom server notifications.

MCP clients, particularly ones that offer "experimental" capabilities,
may wish to handle custom server notifications that are not part of the
standard MCP specification. This change introduces a new
`CustomServerNotification` type that allows a client to process
such custom notifications.

- introduces `CustomServerNotification` to carry arbitrary methods/params while
  still preserving meta/extensions; wires it into the `ServerNotification` union
  and `serde` so `params` can be decoded with `params_as`
- allows client handlers to receive custom notifications via a new
  `on_custom_notification` hook
- adds integration coverage that sends a custom server notification end-to-end
  and asserts the client sees the method and payload

Test:

```shell
cargo test -p rmcp --features client test_custom_server_notification_reaches_client
```
This commit is contained in:
Michael Bolin 2025-12-16 09:48:03 -08:00 • committed by GitHub
commit 2e3cc4a973
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 180 additions and 35 deletions

View file

@ -56,6 +56,9 @@ impl<H: ClientHandler> Service<RoleClient> for H {
ServerNotification::PromptListChangedNotification(_notification_no_param) => {
self.on_prompt_list_changed(context).await
}
ServerNotification::CustomNotification(notification) => {
self.on_custom_notification(notification, context).await
}
};
Ok(())
}
@ -166,6 +169,14 @@ pub trait ClientHandler: Sized + Send + Sync + 'static {
) -> impl Future<Output = ()> + Send + '_ {
std::future::ready(())
}
fn on_custom_notification(
&self,
notification: CustomNotification,
context: NotificationContext<RoleClient>,
) -> impl Future<Output = ()> + Send + '_ {
let _ = (notification, context);
std::future::ready(())
}
fn get_info(&self) -> ClientInfo {
ClientInfo::default()

View file

@ -90,7 +90,7 @@ impl<H: ServerHandler> Service<RoleServer> for H {
ClientNotification::RootsListChangedNotification(_notification) => {
self.on_roots_list_changed(context).await
}
ClientNotification::CustomClientNotification(notification) => {
ClientNotification::CustomNotification(notification) => {
self.on_custom_notification(notification, context).await
}
};
@ -230,7 +230,7 @@ pub trait ServerHandler: Sized + Send + Sync + 'static {
}
fn on_custom_notification(
&self,
notification: CustomClientNotification,
notification: CustomNotification,
context: NotificationContext<RoleServer>,
) -> impl Future<Output = ()> + Send + '_ {
let _ = (notification, context);

View file

@ -627,13 +627,13 @@ const_string!(CancelledNotificationMethod = "notifications/cancelled");
pub type CancelledNotification =
Notification<CancelledNotificationMethod, CancelledNotificationParam>;
/// A catch-all notification the client can use to send custom messages to a server.
/// A catch-all notification either side can use to send custom messages to its peer.
///
/// This preserves the raw `method` name and `params` payload so handlers can
/// deserialize them into domain-specific types.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CustomClientNotification {
pub struct CustomNotification {
pub method: String,
pub params: Option<Value>,
/// extensions will carry anything possible in the context, including [`Meta`]
@ -643,7 +643,7 @@ pub struct CustomClientNotification {
pub extensions: Extensions,
}
impl CustomClientNotification {
impl CustomNotification {
pub fn new(method: impl Into<String>, params: Option<Value>) -> Self {
Self {
method: method.into(),
@ -1786,7 +1786,7 @@ ts_union!(
| ProgressNotification
| InitializedNotification
| RootsListChangedNotification
| CustomClientNotification;
| CustomNotification;
);
ts_union!(
@ -1817,7 +1817,8 @@ ts_union!(
| ResourceUpdatedNotification
| ResourceListChangedNotification
| ToolListChangedNotification
| PromptListChangedNotification;
| PromptListChangedNotification
| CustomNotification;
);
ts_union!(
@ -1907,7 +1908,7 @@ mod tests {
serde_json::from_value(raw.clone()).expect("invalid notification");
match &message {
ClientJsonRpcMessage::Notification(JsonRpcNotification {
notification: ClientNotification::CustomClientNotification(notification),
notification: ClientNotification::CustomNotification(notification),
..
}) => {
assert_eq!(notification.method, "notifications/custom");
@ -1927,6 +1928,38 @@ mod tests {
assert_eq!(json, raw);
}
#[test]
fn test_custom_server_notification_roundtrip() {
let raw = json!( {
"jsonrpc": JsonRpcVersion2_0,
"method": "notifications/custom-server",
"params": {"hello": "world"},
});
let message: ServerJsonRpcMessage =
serde_json::from_value(raw.clone()).expect("invalid notification");
match &message {
ServerJsonRpcMessage::Notification(JsonRpcNotification {
notification: ServerNotification::CustomNotification(notification),
..
}) => {
assert_eq!(notification.method, "notifications/custom-server");
assert_eq!(
notification
.params
.as_ref()
.and_then(|p| p.get("hello"))
.expect("hello present"),
"world"
);
}
_ => panic!("Expected custom server notification"),
}
let json = serde_json::to_value(message).expect("valid json");
assert_eq!(json, raw);
}
#[test]
fn test_request_conversion() {
let raw = json!( {

View file

@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{
ClientNotification, ClientRequest, CustomClientNotification, Extensions, JsonObject,
JsonRpcMessage, NumberOrString, ProgressToken, ServerNotification, ServerRequest,
ClientNotification, ClientRequest, CustomNotification, Extensions, JsonObject, JsonRpcMessage,
NumberOrString, ProgressToken, ServerNotification, ServerRequest,
};
pub trait GetMeta {
@ -18,7 +18,7 @@ pub trait GetExtensions {
fn extensions_mut(&mut self) -> &mut Extensions;
}
impl GetExtensions for CustomClientNotification {
impl GetExtensions for CustomNotification {
fn extensions(&self) -> &Extensions {
&self.extensions
}
@ -27,7 +27,7 @@ impl GetExtensions for CustomClientNotification {
}
}
impl GetMeta for CustomClientNotification {
impl GetMeta for CustomNotification {
fn get_meta_mut(&mut self) -> &mut Meta {
self.extensions_mut().get_or_insert_default()
}
@ -104,7 +104,7 @@ variant_extension! {
ProgressNotification
InitializedNotification
RootsListChangedNotification
CustomClientNotification
CustomNotification
}
}
@ -117,6 +117,7 @@ variant_extension! {
ResourceListChangedNotification
ToolListChangedNotification
PromptListChangedNotification
CustomNotification
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]

View file

@ -3,7 +3,7 @@ use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use super::{
CustomClientNotification, Extensions, Meta, Notification, NotificationNoParam, Request,
CustomNotification, Extensions, Meta, Notification, NotificationNoParam, Request,
RequestNoParam, RequestOptionalParam,
};
#[derive(Serialize, Deserialize)]
@ -249,7 +249,7 @@ where
}
}
impl Serialize for CustomClientNotification {
impl Serialize for CustomNotification {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
@ -277,7 +277,7 @@ impl Serialize for CustomClientNotification {
}
}
impl<'de> Deserialize<'de> for CustomClientNotification {
impl<'de> Deserialize<'de> for CustomNotification {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
@ -294,7 +294,7 @@ impl<'de> Deserialize<'de> for CustomClientNotification {
if let Some(meta) = _meta {
extensions.insert(meta);
}
Ok(CustomClientNotification {
Ok(CustomNotification {
extensions,
method: body.method,
params,