use std::{borrow::Cow, sync::Arc};
mod annotated;
mod capabilities;
mod content;
mod elicitation_schema;
mod extension;
mod meta;
mod prompt;
mod resource;
mod serde_impl;
mod tool;
pub use annotated::*;
pub use capabilities::*;
pub use content::*;
pub use elicitation_schema::*;
pub use extension::*;
pub use meta::*;
pub use prompt::*;
pub use resource::*;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
pub use tool::*;
pub type JsonObject<F = Value> = serde_json::Map<String, F>;
pub fn object(value: serde_json::Value) -> JsonObject {
debug_assert!(value.is_object());
match value {
serde_json::Value::Object(map) => map,
_ => JsonObject::default(),
}
}
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
#[macro_export]
macro_rules! object {
({$($tt:tt)*}) => {
$crate::model::object(serde_json::json! {
{$($tt)*}
})
};
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy, Eq)]
#[cfg_attr(feature = "server", derive(schemars::JsonSchema))]
pub struct EmptyObject {}
pub trait ConstString: Default {
const VALUE: &str;
fn as_str(&self) -> &'static str {
Self::VALUE
}
}
#[macro_export]
macro_rules! const_string {
($name:ident = $value:literal) => {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct $name;
impl ConstString for $name {
const VALUE: &str = $value;
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
$value.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>
where
D: serde::Deserializer<'de>,
{
let s: String = serde::Deserialize::deserialize(deserializer)?;
if s == $value {
Ok($name)
} else {
Err(serde::de::Error::custom(format!(concat!(
"expect const string value \"",
$value,
"\""
))))
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for $name {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed(stringify!($name))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
use serde_json::{Map, json};
let mut schema_map = Map::new();
schema_map.insert("type".to_string(), json!("string"));
schema_map.insert("format".to_string(), json!("const"));
schema_map.insert("const".to_string(), json!($value));
schemars::Schema::from(schema_map)
}
}
};
}
const_string!(JsonRpcVersion2_0 = "2.0");
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProtocolVersion(Cow<'static, str>);
impl Default for ProtocolVersion {
fn default() -> Self {
Self::LATEST
}
}
impl std::fmt::Display for ProtocolVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl ProtocolVersion {
pub const V_2025_06_18: Self = Self(Cow::Borrowed("2025-06-18"));
pub const V_2025_03_26: Self = Self(Cow::Borrowed("2025-03-26"));
pub const V_2024_11_05: Self = Self(Cow::Borrowed("2024-11-05"));
pub const LATEST: Self = Self::V_2025_03_26;
}
impl Serialize for ProtocolVersion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ProtocolVersion {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
#[allow(clippy::single_match)]
match s.as_str() {
"2024-11-05" => return Ok(ProtocolVersion::V_2024_11_05),
"2025-03-26" => return Ok(ProtocolVersion::V_2025_03_26),
"2025-06-18" => return Ok(ProtocolVersion::V_2025_06_18),
_ => {}
}
Ok(ProtocolVersion(Cow::Owned(s)))
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum NumberOrString {
Number(i64),
String(Arc<str>),
}
impl NumberOrString {
pub fn into_json_value(self) -> Value {
match self {
NumberOrString::Number(n) => Value::Number(serde_json::Number::from(n)),
NumberOrString::String(s) => Value::String(s.to_string()),
}
}
}
impl std::fmt::Display for NumberOrString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NumberOrString::Number(n) => n.fmt(f),
NumberOrString::String(s) => s.fmt(f),
}
}
}
impl Serialize for NumberOrString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
NumberOrString::Number(n) => n.serialize(serializer),
NumberOrString::String(s) => s.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for NumberOrString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: Value = Deserialize::deserialize(deserializer)?;
match value {
Value::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(NumberOrString::Number(i))
} else if let Some(u) = n.as_u64() {
if u <= i64::MAX as u64 {
Ok(NumberOrString::Number(u as i64))
} else {
Err(serde::de::Error::custom("Number too large for i64"))
}
} else {
Err(serde::de::Error::custom("Expected an integer"))
}
}
Value::String(s) => Ok(NumberOrString::String(s.into())),
_ => Err(serde::de::Error::custom("Expect number or string")),
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for NumberOrString {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("NumberOrString")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
use serde_json::{Map, json};
let mut number_schema = Map::new();
number_schema.insert("type".to_string(), json!("number"));
let mut string_schema = Map::new();
string_schema.insert("type".to_string(), json!("string"));
let mut schema_map = Map::new();
schema_map.insert("oneOf".to_string(), json!([number_schema, string_schema]));
schemars::Schema::from(schema_map)
}
}
pub type RequestId = NumberOrString;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Hash, Eq)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProgressToken(pub NumberOrString);
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Request<M = String, P = JsonObject> {
pub method: M,
pub params: P,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> Request<M, P> {
pub fn new(params: P) -> Self {
Self {
method: Default::default(),
params,
extensions: Extensions::default(),
}
}
}
impl<M, P> GetExtensions for Request<M, P> {
fn extensions(&self) -> &Extensions {
&self.extensions
}
fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct RequestOptionalParam<M = String, P = JsonObject> {
pub method: M,
pub params: Option<P>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> RequestOptionalParam<M, P> {
pub fn with_param(params: P) -> Self {
Self {
method: Default::default(),
params: Some(params),
extensions: Extensions::default(),
}
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct RequestNoParam<M = String> {
pub method: M,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M> GetExtensions for RequestNoParam<M> {
fn extensions(&self) -> &Extensions {
&self.extensions
}
fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Notification<M = String, P = JsonObject> {
pub method: M,
pub params: P,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> Notification<M, P> {
pub fn new(params: P) -> Self {
Self {
method: Default::default(),
params,
extensions: Extensions::default(),
}
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct NotificationNoParam<M = String> {
pub method: M,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcRequest<R = Request> {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
#[serde(flatten)]
pub request: R,
}
type DefaultResponse = JsonObject;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcResponse<R = JsonObject> {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
pub result: R,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcError {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
pub error: ErrorData,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcNotification<N = Notification> {
pub jsonrpc: JsonRpcVersion2_0,
#[serde(flatten)]
pub notification: N,
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ErrorCode(pub i32);
impl ErrorCode {
pub const RESOURCE_NOT_FOUND: Self = Self(-32002);
pub const INVALID_REQUEST: Self = Self(-32600);
pub const METHOD_NOT_FOUND: Self = Self(-32601);
pub const INVALID_PARAMS: Self = Self(-32602);
pub const INTERNAL_ERROR: Self = Self(-32603);
pub const PARSE_ERROR: Self = Self(-32700);
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ErrorData {
pub code: ErrorCode,
pub message: Cow<'static, str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl ErrorData {
pub fn new(
code: ErrorCode,
message: impl Into<Cow<'static, str>>,
data: Option<Value>,
) -> Self {
Self {
code,
message: message.into(),
data,
}
}
pub fn resource_not_found(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::RESOURCE_NOT_FOUND, message, data)
}
pub fn parse_error(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::PARSE_ERROR, message, data)
}
pub fn invalid_request(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INVALID_REQUEST, message, data)
}
pub fn method_not_found<M: ConstString>() -> Self {
Self::new(ErrorCode::METHOD_NOT_FOUND, M::VALUE, None)
}
pub fn invalid_params(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INVALID_PARAMS, message, data)
}
pub fn internal_error(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INTERNAL_ERROR, message, data)
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum JsonRpcMessage<Req = Request, Resp = DefaultResponse, Noti = Notification> {
Request(JsonRpcRequest<Req>),
Response(JsonRpcResponse<Resp>),
Notification(JsonRpcNotification<Noti>),
Error(JsonRpcError),
}
impl<Req, Resp, Not> JsonRpcMessage<Req, Resp, Not> {
#[inline]
pub const fn request(request: Req, id: RequestId) -> Self {
JsonRpcMessage::Request(JsonRpcRequest {
jsonrpc: JsonRpcVersion2_0,
id,
request,
})
}
#[inline]
pub const fn response(response: Resp, id: RequestId) -> Self {
JsonRpcMessage::Response(JsonRpcResponse {
jsonrpc: JsonRpcVersion2_0,
id,
result: response,
})
}
#[inline]
pub const fn error(error: ErrorData, id: RequestId) -> Self {
JsonRpcMessage::Error(JsonRpcError {
jsonrpc: JsonRpcVersion2_0,
id,
error,
})
}
#[inline]
pub const fn notification(notification: Not) -> Self {
JsonRpcMessage::Notification(JsonRpcNotification {
jsonrpc: JsonRpcVersion2_0,
notification,
})
}
pub fn into_request(self) -> Option<(Req, RequestId)> {
match self {
JsonRpcMessage::Request(r) => Some((r.request, r.id)),
_ => None,
}
}
pub fn into_response(self) -> Option<(Resp, RequestId)> {
match self {
JsonRpcMessage::Response(r) => Some((r.result, r.id)),
_ => None,
}
}
pub fn into_notification(self) -> Option<Not> {
match self {
JsonRpcMessage::Notification(n) => Some(n.notification),
_ => None,
}
}
pub fn into_error(self) -> Option<(ErrorData, RequestId)> {
match self {
JsonRpcMessage::Error(e) => Some((e.error, e.id)),
_ => None,
}
}
pub fn into_result(self) -> Option<(Result<Resp, ErrorData>, RequestId)> {
match self {
JsonRpcMessage::Response(r) => Some((Ok(r.result), r.id)),
JsonRpcMessage::Error(e) => Some((Err(e.error), e.id)),
_ => None,
}
}
}
pub type EmptyResult = EmptyObject;
impl From<()> for EmptyResult {
fn from(_value: ()) -> Self {
EmptyResult {}
}
}
impl From<EmptyResult> for () {
fn from(_value: EmptyResult) {}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CancelledNotificationParam {
pub request_id: RequestId,
pub reason: Option<String>,
}
const_string!(CancelledNotificationMethod = "notifications/cancelled");
pub type CancelledNotification =
Notification<CancelledNotificationMethod, CancelledNotificationParam>;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CustomClientNotification {
pub method: String,
pub params: Option<Value>,
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl CustomClientNotification {
pub fn new(method: impl Into<String>, params: Option<Value>) -> Self {
Self {
method: method.into(),
params,
extensions: Extensions::default(),
}
}
pub fn params_as<T: DeserializeOwned>(&self) -> Result<Option<T>, serde_json::Error> {
self.params
.as_ref()
.map(|params| serde_json::from_value(params.clone()))
.transpose()
}
}
const_string!(InitializeResultMethod = "initialize");
pub type InitializeRequest = Request<InitializeResultMethod, InitializeRequestParam>;
const_string!(InitializedNotificationMethod = "notifications/initialized");
pub type InitializedNotification = NotificationNoParam<InitializedNotificationMethod>;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct InitializeRequestParam {
pub protocol_version: ProtocolVersion,
pub capabilities: ClientCapabilities,
pub client_info: Implementation,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct InitializeResult {
pub protocol_version: ProtocolVersion,
pub capabilities: ServerCapabilities,
pub server_info: Implementation,
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
}
pub type ServerInfo = InitializeResult;
pub type ClientInfo = InitializeRequestParam;
#[allow(clippy::derivable_impls)]
impl Default for ServerInfo {
fn default() -> Self {
ServerInfo {
protocol_version: ProtocolVersion::default(),
capabilities: ServerCapabilities::default(),
server_info: Implementation::from_build_env(),
instructions: None,
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for ClientInfo {
fn default() -> Self {
ClientInfo {
protocol_version: ProtocolVersion::default(),
capabilities: ClientCapabilities::default(),
client_info: Implementation::from_build_env(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Icon {
pub src: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sizes: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Implementation {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub icons: Option<Vec<Icon>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub website_url: Option<String>,
}
impl Default for Implementation {
fn default() -> Self {
Self::from_build_env()
}
}
impl Implementation {
pub fn from_build_env() -> Self {
Implementation {
name: env!("CARGO_CRATE_NAME").to_owned(),
title: None,
version: env!("CARGO_PKG_VERSION").to_owned(),
icons: None,
website_url: None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct PaginatedRequestParam {
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
}
const_string!(PingRequestMethod = "ping");
pub type PingRequest = RequestNoParam<PingRequestMethod>;
const_string!(ProgressNotificationMethod = "notifications/progress");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProgressNotificationParam {
pub progress_token: ProgressToken,
pub progress: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub total: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub type ProgressNotification = Notification<ProgressNotificationMethod, ProgressNotificationParam>;
pub type Cursor = String;
macro_rules! paginated_result {
($t:ident {
$i_item: ident: $t_item: ty
}) => {
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct $t {
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
pub meta: Option<Meta>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<Cursor>,
pub $i_item: $t_item,
}
impl $t {
pub fn with_all_items(
items: $t_item,
) -> Self {
Self {
meta: None,
next_cursor: None,
$i_item: items,
}
}
}
};
}
const_string!(ListResourcesRequestMethod = "resources/list");
pub type ListResourcesRequest =
RequestOptionalParam<ListResourcesRequestMethod, PaginatedRequestParam>;
paginated_result!(ListResourcesResult {
resources: Vec<Resource>
});
const_string!(ListResourceTemplatesRequestMethod = "resources/templates/list");
pub type ListResourceTemplatesRequest =
RequestOptionalParam<ListResourceTemplatesRequestMethod, PaginatedRequestParam>;
paginated_result!(ListResourceTemplatesResult {
resource_templates: Vec<ResourceTemplate>
});
const_string!(ReadResourceRequestMethod = "resources/read");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ReadResourceRequestParam {
pub uri: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ReadResourceResult {
pub contents: Vec<ResourceContents>,
}
pub type ReadResourceRequest = Request<ReadResourceRequestMethod, ReadResourceRequestParam>;
const_string!(ResourceListChangedNotificationMethod = "notifications/resources/list_changed");
pub type ResourceListChangedNotification =
NotificationNoParam<ResourceListChangedNotificationMethod>;
const_string!(SubscribeRequestMethod = "resources/subscribe");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SubscribeRequestParam {
pub uri: String,
}
pub type SubscribeRequest = Request<SubscribeRequestMethod, SubscribeRequestParam>;
const_string!(UnsubscribeRequestMethod = "resources/unsubscribe");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct UnsubscribeRequestParam {
pub uri: String,
}
pub type UnsubscribeRequest = Request<UnsubscribeRequestMethod, UnsubscribeRequestParam>;
const_string!(ResourceUpdatedNotificationMethod = "notifications/resources/updated");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ResourceUpdatedNotificationParam {
pub uri: String,
}
pub type ResourceUpdatedNotification =
Notification<ResourceUpdatedNotificationMethod, ResourceUpdatedNotificationParam>;
const_string!(ListPromptsRequestMethod = "prompts/list");
pub type ListPromptsRequest = RequestOptionalParam<ListPromptsRequestMethod, PaginatedRequestParam>;
paginated_result!(ListPromptsResult {
prompts: Vec<Prompt>
});
const_string!(GetPromptRequestMethod = "prompts/get");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct GetPromptRequestParam {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub arguments: Option<JsonObject>,
}
pub type GetPromptRequest = Request<GetPromptRequestMethod, GetPromptRequestParam>;
const_string!(PromptListChangedNotificationMethod = "notifications/prompts/list_changed");
pub type PromptListChangedNotification = NotificationNoParam<PromptListChangedNotificationMethod>;
const_string!(ToolListChangedNotificationMethod = "notifications/tools/list_changed");
pub type ToolListChangedNotification = NotificationNoParam<ToolListChangedNotificationMethod>;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
#[serde(rename_all = "lowercase")] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum LoggingLevel {
Debug,
Info,
Notice,
Warning,
Error,
Critical,
Alert,
Emergency,
}
const_string!(SetLevelRequestMethod = "logging/setLevel");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SetLevelRequestParam {
pub level: LoggingLevel,
}
pub type SetLevelRequest = Request<SetLevelRequestMethod, SetLevelRequestParam>;
const_string!(LoggingMessageNotificationMethod = "notifications/message");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct LoggingMessageNotificationParam {
pub level: LoggingLevel,
#[serde(skip_serializing_if = "Option::is_none")]
pub logger: Option<String>,
pub data: Value,
}
pub type LoggingMessageNotification =
Notification<LoggingMessageNotificationMethod, LoggingMessageNotificationParam>;
const_string!(CreateMessageRequestMethod = "sampling/createMessage");
pub type CreateMessageRequest = Request<CreateMessageRequestMethod, CreateMessageRequestParam>;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Role {
User,
Assistant,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SamplingMessage {
pub role: Role,
pub content: Content,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ContextInclusion {
#[serde(rename = "allServers")]
AllServers,
#[serde(rename = "none")]
None,
#[serde(rename = "thisServer")]
ThisServer,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CreateMessageRequestParam {
pub messages: Vec<SamplingMessage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model_preferences: Option<ModelPreferences>,
#[serde(skip_serializing_if = "Option::is_none")]
pub system_prompt: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub include_context: Option<ContextInclusion>,
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f32>,
pub max_tokens: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop_sequences: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ModelPreferences {
#[serde(skip_serializing_if = "Option::is_none")]
pub hints: Option<Vec<ModelHint>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cost_priority: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub speed_priority: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub intelligence_priority: Option<f32>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ModelHint {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CompletionContext {
#[serde(skip_serializing_if = "Option::is_none")]
pub arguments: Option<std::collections::HashMap<String, String>>,
}
impl CompletionContext {
pub fn new() -> Self {
Self::default()
}
pub fn with_arguments(arguments: std::collections::HashMap<String, String>) -> Self {
Self {
arguments: Some(arguments),
}
}
pub fn get_argument(&self, name: &str) -> Option<&String> {
self.arguments.as_ref()?.get(name)
}
pub fn has_arguments(&self) -> bool {
self.arguments.as_ref().is_some_and(|args| !args.is_empty())
}
pub fn argument_names(&self) -> impl Iterator<Item = &str> {
self.arguments
.as_ref()
.into_iter()
.flat_map(|args| args.keys())
.map(|k| k.as_str())
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CompleteRequestParam {
pub r#ref: Reference,
pub argument: ArgumentInfo,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<CompletionContext>,
}
pub type CompleteRequest = Request<CompleteRequestMethod, CompleteRequestParam>;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CompletionInfo {
pub values: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub has_more: Option<bool>,
}
impl CompletionInfo {
pub const MAX_VALUES: usize = 100;
pub fn new(values: Vec<String>) -> Result<Self, String> {
if values.len() > Self::MAX_VALUES {
return Err(format!(
"Too many completion values: {} (max: {})",
values.len(),
Self::MAX_VALUES
));
}
Ok(Self {
values,
total: None,
has_more: None,
})
}
pub fn with_all_values(values: Vec<String>) -> Result<Self, String> {
let completion = Self::new(values)?;
Ok(Self {
total: Some(completion.values.len() as u32),
has_more: Some(false),
..completion
})
}
pub fn with_pagination(
values: Vec<String>,
total: Option<u32>,
has_more: bool,
) -> Result<Self, String> {
let completion = Self::new(values)?;
Ok(Self {
total,
has_more: Some(has_more),
..completion
})
}
pub fn has_more_results(&self) -> bool {
self.has_more.unwrap_or(false)
}
pub fn total_available(&self) -> Option<u32> {
self.total
}
pub fn validate(&self) -> Result<(), String> {
if self.values.len() > Self::MAX_VALUES {
return Err(format!(
"Too many completion values: {} (max: {})",
self.values.len(),
Self::MAX_VALUES
));
}
Ok(())
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CompleteResult {
pub completion: CompletionInfo,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "type")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Reference {
#[serde(rename = "ref/resource")]
Resource(ResourceReference),
#[serde(rename = "ref/prompt")]
Prompt(PromptReference),
}
impl Reference {
pub fn for_prompt(name: impl Into<String>) -> Self {
Self::Prompt(PromptReference {
name: name.into(),
title: None,
})
}
pub fn for_resource(uri: impl Into<String>) -> Self {
Self::Resource(ResourceReference { uri: uri.into() })
}
pub fn reference_type(&self) -> &'static str {
match self {
Self::Prompt(_) => "ref/prompt",
Self::Resource(_) => "ref/resource",
}
}
pub fn as_prompt_name(&self) -> Option<&str> {
match self {
Self::Prompt(prompt_ref) => Some(&prompt_ref.name),
_ => None,
}
}
pub fn as_resource_uri(&self) -> Option<&str> {
match self {
Self::Resource(resource_ref) => Some(&resource_ref.uri),
_ => None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ResourceReference {
pub uri: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct PromptReference {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
}
const_string!(CompleteRequestMethod = "completion/complete");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ArgumentInfo {
pub name: String,
pub value: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Root {
pub uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
const_string!(ListRootsRequestMethod = "roots/list");
pub type ListRootsRequest = RequestNoParam<ListRootsRequestMethod>;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ListRootsResult {
pub roots: Vec<Root>,
}
const_string!(RootsListChangedNotificationMethod = "notifications/roots/list_changed");
pub type RootsListChangedNotification = NotificationNoParam<RootsListChangedNotificationMethod>;
const_string!(ElicitationCreateRequestMethod = "elicitation/create");
const_string!(ElicitationResponseNotificationMethod = "notifications/elicitation/response");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ElicitationAction {
Accept,
Decline,
Cancel,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CreateElicitationRequestParam {
pub message: String,
pub requested_schema: ElicitationSchema,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CreateElicitationResult {
pub action: ElicitationAction,
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<Value>,
}
pub type CreateElicitationRequest =
Request<ElicitationCreateRequestMethod, CreateElicitationRequestParam>;
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CallToolResult {
pub content: Vec<Content>,
#[serde(skip_serializing_if = "Option::is_none")]
pub structured_content: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_error: Option<bool>,
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
pub meta: Option<Meta>,
}
impl CallToolResult {
pub fn success(content: Vec<Content>) -> Self {
CallToolResult {
content,
structured_content: None,
is_error: Some(false),
meta: None,
}
}
pub fn error(content: Vec<Content>) -> Self {
CallToolResult {
content,
structured_content: None,
is_error: Some(true),
meta: None,
}
}
pub fn structured(value: Value) -> Self {
CallToolResult {
content: vec![Content::text(value.to_string())],
structured_content: Some(value),
is_error: Some(false),
meta: None,
}
}
pub fn structured_error(value: Value) -> Self {
CallToolResult {
content: vec![Content::text(value.to_string())],
structured_content: Some(value),
is_error: Some(true),
meta: None,
}
}
pub fn into_typed<T>(self) -> Result<T, serde_json::Error>
where
T: DeserializeOwned,
{
let raw_text = match (self.structured_content, &self.content.first()) {
(Some(value), _) => return serde_json::from_value(value),
(None, Some(contents)) => {
if let Some(text) = contents.as_text() {
let text = &text.text;
Some(text)
} else {
None
}
}
(None, None) => None,
};
if let Some(text) = raw_text {
return serde_json::from_str(text);
}
serde_json::from_value(serde_json::Value::Null)
}
}
impl<'de> Deserialize<'de> for CallToolResult {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CallToolResultHelper {
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<Vec<Content>>,
#[serde(skip_serializing_if = "Option::is_none")]
structured_content: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
is_error: Option<bool>,
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
meta: Option<Meta>,
}
let helper = CallToolResultHelper::deserialize(deserializer)?;
let result = CallToolResult {
content: helper.content.unwrap_or_default(),
structured_content: helper.structured_content,
is_error: helper.is_error,
meta: helper.meta,
};
if result.content.is_empty() && result.structured_content.is_none() {
return Err(serde::de::Error::custom(
"CallToolResult must have either content or structured_content",
));
}
Ok(result)
}
}
const_string!(ListToolsRequestMethod = "tools/list");
pub type ListToolsRequest = RequestOptionalParam<ListToolsRequestMethod, PaginatedRequestParam>;
paginated_result!(
ListToolsResult {
tools: Vec<Tool>
}
);
const_string!(CallToolRequestMethod = "tools/call");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CallToolRequestParam {
pub name: Cow<'static, str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub arguments: Option<JsonObject>,
}
pub type CallToolRequest = Request<CallToolRequestMethod, CallToolRequestParam>;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CreateMessageResult {
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop_reason: Option<String>,
#[serde(flatten)]
pub message: SamplingMessage,
}
impl CreateMessageResult {
pub const STOP_REASON_END_TURN: &str = "endTurn";
pub const STOP_REASON_END_SEQUENCE: &str = "stopSequence";
pub const STOP_REASON_END_MAX_TOKEN: &str = "maxTokens";
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct GetPromptResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
pub messages: Vec<PromptMessage>,
}
macro_rules! ts_union {
(
export type $U:ident =
$($rest:tt)*
) => {
ts_union!(@declare $U { $($rest)* });
ts_union!(@impl_from $U { $($rest)* });
};
(@declare $U:ident { $($variant:tt)* }) => {
ts_union!(@declare_variant $U { } {$($variant)*} );
};
(@declare_variant $U:ident { $($declared:tt)* } {$(|)? box $V:ident $($rest:tt)*}) => {
ts_union!(@declare_variant $U { $($declared)* $V(Box<$V>), } {$($rest)*});
};
(@declare_variant $U:ident { $($declared:tt)* } {$(|)? $V:ident $($rest:tt)*}) => {
ts_union!(@declare_variant $U { $($declared)* $V($V), } {$($rest)*});
};
(@declare_variant $U:ident { $($declared:tt)* } { ; }) => {
ts_union!(@declare_end $U { $($declared)* } );
};
(@declare_end $U:ident { $($declared:tt)* }) => {
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum $U {
$($declared)*
}
};
(@impl_from $U: ident {$(|)? box $V:ident $($rest:tt)*}) => {
impl From<$V> for $U {
fn from(value: $V) -> Self {
$U::$V(Box::new(value))
}
}
ts_union!(@impl_from $U {$($rest)*});
};
(@impl_from $U: ident {$(|)? $V:ident $($rest:tt)*}) => {
impl From<$V> for $U {
fn from(value: $V) -> Self {
$U::$V(value)
}
}
ts_union!(@impl_from $U {$($rest)*});
};
(@impl_from $U: ident { ; }) => {};
(@impl_from $U: ident { }) => {};
}
ts_union!(
export type ClientRequest =
| PingRequest
| InitializeRequest
| CompleteRequest
| SetLevelRequest
| GetPromptRequest
| ListPromptsRequest
| ListResourcesRequest
| ListResourceTemplatesRequest
| ReadResourceRequest
| SubscribeRequest
| UnsubscribeRequest
| CallToolRequest
| ListToolsRequest;
);
impl ClientRequest {
pub fn method(&self) -> &'static str {
match &self {
ClientRequest::PingRequest(r) => r.method.as_str(),
ClientRequest::InitializeRequest(r) => r.method.as_str(),
ClientRequest::CompleteRequest(r) => r.method.as_str(),
ClientRequest::SetLevelRequest(r) => r.method.as_str(),
ClientRequest::GetPromptRequest(r) => r.method.as_str(),
ClientRequest::ListPromptsRequest(r) => r.method.as_str(),
ClientRequest::ListResourcesRequest(r) => r.method.as_str(),
ClientRequest::ListResourceTemplatesRequest(r) => r.method.as_str(),
ClientRequest::ReadResourceRequest(r) => r.method.as_str(),
ClientRequest::SubscribeRequest(r) => r.method.as_str(),
ClientRequest::UnsubscribeRequest(r) => r.method.as_str(),
ClientRequest::CallToolRequest(r) => r.method.as_str(),
ClientRequest::ListToolsRequest(r) => r.method.as_str(),
}
}
}
ts_union!(
export type ClientNotification =
| CancelledNotification
| ProgressNotification
| InitializedNotification
| RootsListChangedNotification
| CustomClientNotification;
);
ts_union!(
export type ClientResult = box CreateMessageResult | ListRootsResult | CreateElicitationResult | EmptyResult;
);
impl ClientResult {
pub fn empty(_: ()) -> ClientResult {
ClientResult::EmptyResult(EmptyResult {})
}
}
pub type ClientJsonRpcMessage = JsonRpcMessage<ClientRequest, ClientResult, ClientNotification>;
ts_union!(
export type ServerRequest =
| PingRequest
| CreateMessageRequest
| ListRootsRequest
| CreateElicitationRequest;
);
ts_union!(
export type ServerNotification =
| CancelledNotification
| ProgressNotification
| LoggingMessageNotification
| ResourceUpdatedNotification
| ResourceListChangedNotification
| ToolListChangedNotification
| PromptListChangedNotification;
);
ts_union!(
export type ServerResult =
| InitializeResult
| CompleteResult
| GetPromptResult
| ListPromptsResult
| ListResourcesResult
| ListResourceTemplatesResult
| ReadResourceResult
| CallToolResult
| ListToolsResult
| CreateElicitationResult
| EmptyResult
;
);
impl ServerResult {
pub fn empty(_: ()) -> ServerResult {
ServerResult::EmptyResult(EmptyResult {})
}
}
pub type ServerJsonRpcMessage = JsonRpcMessage<ServerRequest, ServerResult, ServerNotification>;
impl TryInto<CancelledNotification> for ServerNotification {
type Error = ServerNotification;
fn try_into(self) -> Result<CancelledNotification, Self::Error> {
if let ServerNotification::CancelledNotification(t) = self {
Ok(t)
} else {
Err(self)
}
}
}
impl TryInto<CancelledNotification> for ClientNotification {
type Error = ClientNotification;
fn try_into(self) -> Result<CancelledNotification, Self::Error> {
if let ClientNotification::CancelledNotification(t) = self {
Ok(t)
} else {
Err(self)
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn test_notification_serde() {
let raw = json!( {
"jsonrpc": JsonRpcVersion2_0,
"method": InitializedNotificationMethod,
});
let message: ClientJsonRpcMessage =
serde_json::from_value(raw.clone()).expect("invalid notification");
match &message {
ClientJsonRpcMessage::Notification(JsonRpcNotification {
notification: ClientNotification::InitializedNotification(_n),
..
}) => {}
_ => panic!("Expected Notification"),
}
let json = serde_json::to_value(message).expect("valid json");
assert_eq!(json, raw);
}
#[test]
fn test_custom_client_notification_roundtrip() {
let raw = json!( {
"jsonrpc": JsonRpcVersion2_0,
"method": "notifications/custom",
"params": {"foo": "bar"},
});
let message: ClientJsonRpcMessage =
serde_json::from_value(raw.clone()).expect("invalid notification");
match &message {
ClientJsonRpcMessage::Notification(JsonRpcNotification {
notification: ClientNotification::CustomClientNotification(notification),
..
}) => {
assert_eq!(notification.method, "notifications/custom");
assert_eq!(
notification
.params
.as_ref()
.and_then(|p| p.get("foo"))
.expect("foo present"),
"bar"
);
}
_ => panic!("Expected custom client notification"),
}
let json = serde_json::to_value(message).expect("valid json");
assert_eq!(json, raw);
}
#[test]
fn test_request_conversion() {
let raw = json!( {
"jsonrpc": JsonRpcVersion2_0,
"id": 1,
"method": "request",
"params": {"key": "value"},
});
let message: JsonRpcMessage = serde_json::from_value(raw.clone()).expect("invalid request");
match &message {
JsonRpcMessage::Request(r) => {
assert_eq!(r.id, RequestId::Number(1));
assert_eq!(r.request.method, "request");
assert_eq!(
&r.request.params,
json!({"key": "value"})
.as_object()
.expect("should be an object")
);
}
_ => panic!("Expected Request"),
}
let json = serde_json::to_value(&message).expect("valid json");
assert_eq!(json, raw);
}
#[test]
fn test_initial_request_response_serde() {
let request = json!({
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {
"listChanged": true
},
"sampling": {}
},
"clientInfo": {
"name": "ExampleClient",
"version": "1.0.0"
}
}
});
let raw_response_json = json!({
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"logging": {},
"prompts": {
"listChanged": true
},
"resources": {
"subscribe": true,
"listChanged": true
},
"tools": {
"listChanged": true
}
},
"serverInfo": {
"name": "ExampleServer",
"version": "1.0.0"
}
}
});
let request: ClientJsonRpcMessage =
serde_json::from_value(request.clone()).expect("invalid request");
let (request, id) = request.into_request().expect("should be a request");
assert_eq!(id, RequestId::Number(1));
match request {
ClientRequest::InitializeRequest(Request {
method: _,
params:
InitializeRequestParam {
protocol_version: _,
capabilities,
client_info,
},
..
}) => {
assert_eq!(capabilities.roots.unwrap().list_changed, Some(true));
assert_eq!(capabilities.sampling.unwrap().len(), 0);
assert_eq!(client_info.name, "ExampleClient");
assert_eq!(client_info.version, "1.0.0");
}
_ => panic!("Expected InitializeRequest"),
}
let server_response: ServerJsonRpcMessage =
serde_json::from_value(raw_response_json.clone()).expect("invalid response");
let (response, id) = server_response
.clone()
.into_response()
.expect("expect response");
assert_eq!(id, RequestId::Number(1));
match response {
ServerResult::InitializeResult(InitializeResult {
protocol_version: _,
capabilities,
server_info,
instructions,
}) => {
assert_eq!(capabilities.logging.unwrap().len(), 0);
assert_eq!(capabilities.prompts.unwrap().list_changed, Some(true));
assert_eq!(
capabilities.resources.as_ref().unwrap().subscribe,
Some(true)
);
assert_eq!(capabilities.resources.unwrap().list_changed, Some(true));
assert_eq!(capabilities.tools.unwrap().list_changed, Some(true));
assert_eq!(server_info.name, "ExampleServer");
assert_eq!(server_info.version, "1.0.0");
assert_eq!(server_info.icons, None);
assert_eq!(instructions, None);
}
other => panic!("Expected InitializeResult, got {other:?}"),
}
let server_response_json: Value = serde_json::to_value(&server_response).expect("msg");
assert_eq!(server_response_json, raw_response_json);
}
#[test]
fn test_negative_and_large_request_ids() {
let negative_id_json = json!({
"jsonrpc": "2.0",
"id": -1,
"method": "test",
"params": {}
});
let message: JsonRpcMessage =
serde_json::from_value(negative_id_json.clone()).expect("Should parse negative ID");
match &message {
JsonRpcMessage::Request(r) => {
assert_eq!(r.id, RequestId::Number(-1));
}
_ => panic!("Expected Request"),
}
let serialized = serde_json::to_value(&message).expect("Should serialize");
assert_eq!(serialized, negative_id_json);
let large_negative_json = json!({
"jsonrpc": "2.0",
"id": -9007199254740991i64, "method": "test",
"params": {}
});
let message: JsonRpcMessage = serde_json::from_value(large_negative_json.clone())
.expect("Should parse large negative ID");
match &message {
JsonRpcMessage::Request(r) => {
assert_eq!(r.id, RequestId::Number(-9007199254740991i64));
}
_ => panic!("Expected Request"),
}
let large_positive_json = json!({
"jsonrpc": "2.0",
"id": 9007199254740991i64,
"method": "test",
"params": {}
});
let message: JsonRpcMessage = serde_json::from_value(large_positive_json.clone())
.expect("Should parse large positive ID");
match &message {
JsonRpcMessage::Request(r) => {
assert_eq!(r.id, RequestId::Number(9007199254740991i64));
}
_ => panic!("Expected Request"),
}
let zero_id_json = json!({
"jsonrpc": "2.0",
"id": 0,
"method": "test",
"params": {}
});
let message: JsonRpcMessage =
serde_json::from_value(zero_id_json.clone()).expect("Should parse zero ID");
match &message {
JsonRpcMessage::Request(r) => {
assert_eq!(r.id, RequestId::Number(0));
}
_ => panic!("Expected Request"),
}
}
#[test]
fn test_protocol_version_order() {
let v1 = ProtocolVersion::V_2024_11_05;
let v2 = ProtocolVersion::V_2025_03_26;
assert!(v1 < v2);
}
#[test]
fn test_icon_serialization() {
let icon = Icon {
src: "https://example.com/icon.png".to_string(),
mime_type: Some("image/png".to_string()),
sizes: Some(vec!["48x48".to_string()]),
};
let json = serde_json::to_value(&icon).unwrap();
assert_eq!(json["src"], "https://example.com/icon.png");
assert_eq!(json["mimeType"], "image/png");
assert_eq!(json["sizes"][0], "48x48");
let deserialized: Icon = serde_json::from_value(json).unwrap();
assert_eq!(deserialized, icon);
}
#[test]
fn test_icon_minimal() {
let icon = Icon {
src: "data:image/svg+xml;base64,PHN2Zy8+".to_string(),
mime_type: None,
sizes: None,
};
let json = serde_json::to_value(&icon).unwrap();
assert_eq!(json["src"], "data:image/svg+xml;base64,PHN2Zy8+");
assert!(json.get("mimeType").is_none());
assert!(json.get("sizes").is_none());
}
#[test]
fn test_implementation_with_icons() {
let implementation = Implementation {
name: "test-server".to_string(),
title: Some("Test Server".to_string()),
version: "1.0.0".to_string(),
icons: Some(vec![
Icon {
src: "https://example.com/icon.png".to_string(),
mime_type: Some("image/png".to_string()),
sizes: Some(vec!["48x48".to_string()]),
},
Icon {
src: "https://example.com/icon.svg".to_string(),
mime_type: Some("image/svg+xml".to_string()),
sizes: Some(vec!["any".to_string()]),
},
]),
website_url: Some("https://example.com".to_string()),
};
let json = serde_json::to_value(&implementation).unwrap();
assert_eq!(json["name"], "test-server");
assert_eq!(json["websiteUrl"], "https://example.com");
assert!(json["icons"].is_array());
assert_eq!(json["icons"][0]["src"], "https://example.com/icon.png");
assert_eq!(json["icons"][0]["sizes"][0], "48x48");
assert_eq!(json["icons"][1]["mimeType"], "image/svg+xml");
assert_eq!(json["icons"][1]["sizes"][0], "any");
}
#[test]
fn test_backward_compatibility() {
let old_json = json!({
"name": "legacy-server",
"version": "0.9.0"
});
let implementation: Implementation = serde_json::from_value(old_json).unwrap();
assert_eq!(implementation.name, "legacy-server");
assert_eq!(implementation.version, "0.9.0");
assert_eq!(implementation.icons, None);
assert_eq!(implementation.website_url, None);
}
#[test]
fn test_initialize_with_icons() {
let init_result = InitializeResult {
protocol_version: ProtocolVersion::default(),
capabilities: ServerCapabilities::default(),
server_info: Implementation {
name: "icon-server".to_string(),
title: None,
version: "2.0.0".to_string(),
icons: Some(vec![Icon {
src: "https://example.com/server.png".to_string(),
mime_type: Some("image/png".to_string()),
sizes: Some(vec!["48x48".to_string()]),
}]),
website_url: Some("https://docs.example.com".to_string()),
},
instructions: None,
};
let json = serde_json::to_value(&init_result).unwrap();
assert!(json["serverInfo"]["icons"].is_array());
assert_eq!(
json["serverInfo"]["icons"][0]["src"],
"https://example.com/server.png"
);
assert_eq!(json["serverInfo"]["icons"][0]["sizes"][0], "48x48");
assert_eq!(json["serverInfo"]["websiteUrl"], "https://docs.example.com");
}
}