pub mod cancel;
pub mod discover;
pub mod meta;
pub mod progress;
pub mod serve;
pub mod subs;
pub mod writer;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const PROTOCOL_VERSION: &str = "2026-07-28";
pub const PARSE_ERROR: i64 = -32700;
pub const INVALID_REQUEST: i64 = -32600;
pub const METHOD_NOT_FOUND: i64 = -32601;
pub const INVALID_PARAMS: i64 = -32602;
pub const INTERNAL_ERROR: i64 = -32603;
pub const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022;
#[derive(Debug, Deserialize)]
pub struct JsonRpcMessage {
pub jsonrpc: String,
#[serde(default, deserialize_with = "present_or_absent")]
pub id: Option<Value>,
pub method: String,
pub params: Option<Value>,
}
#[derive(Debug, Serialize)]
pub struct JsonRpcResponse {
pub jsonrpc: &'static str,
pub id: Value,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<JsonRpcError>,
}
#[derive(Debug, Serialize)]
pub struct JsonRpcNotification {
pub jsonrpc: &'static str,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Serialize)]
pub struct JsonRpcError {
pub code: i64,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
fn present_or_absent<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
where
D: serde::Deserializer<'de>,
{
Value::deserialize(deserializer).map(Some)
}
impl JsonRpcResponse {
#[must_use]
pub fn success(id: Value, result: Value) -> Self {
Self {
jsonrpc: "2.0",
id,
result: Some(result),
error: None,
}
}
#[must_use]
pub fn error(id: Value, code: i64, message: impl Into<String>) -> Self {
Self {
jsonrpc: "2.0",
id,
result: None,
error: Some(JsonRpcError {
code,
message: message.into(),
data: None,
}),
}
}
#[must_use]
pub fn error_with_data(id: Value, code: i64, message: impl Into<String>, data: Value) -> Self {
Self {
jsonrpc: "2.0",
id,
result: None,
error: Some(JsonRpcError {
code,
message: message.into(),
data: Some(data),
}),
}
}
}
impl JsonRpcNotification {
#[must_use]
pub fn new(method: impl Into<String>, params: Value) -> Self {
Self {
jsonrpc: "2.0",
method: method.into(),
params: Some(params),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum RequestKey {
Num(i64),
Str(String),
}
impl RequestKey {
#[must_use]
pub fn from_value(value: &Value) -> Option<Self> {
match value {
Value::Number(n) => n.as_i64().map(Self::Num),
Value::String(s) => Some(Self::Str(s.clone())),
_ => None,
}
}
#[must_use]
pub fn to_value(&self) -> Value {
match self {
Self::Num(n) => Value::Number((*n).into()),
Self::Str(s) => Value::String(s.clone()),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct CacheHints {
pub ttl_ms: u64,
pub scope: CacheScope,
}
#[derive(Clone, Copy, Debug)]
pub enum CacheScope {
Public,
#[expect(
dead_code,
reason = "no authenticated resource yet; fires when one emits this scope"
)]
Private,
}
impl CacheScope {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::Private => "private",
}
}
}
impl CacheHints {
#[must_use]
pub const fn constant() -> Self {
Self {
ttl_ms: 3_600_000,
scope: CacheScope::Public,
}
}
#[must_use]
pub const fn immutable_content() -> Self {
Self {
ttl_ms: 86_400_000,
scope: CacheScope::Public,
}
}
#[must_use]
pub const fn short_list() -> Self {
Self {
ttl_ms: 60_000,
scope: CacheScope::Public,
}
}
}
#[must_use]
pub fn complete(payload: Value, hints: Option<CacheHints>, server_info: &Value) -> Value {
let mut object = match payload {
Value::Object(map) => map,
other => {
let mut map = serde_json::Map::new();
map.insert("value".to_string(), other);
map
}
};
object.insert(
"resultType".to_string(),
Value::String("complete".to_string()),
);
if let Some(hints) = hints {
object.insert("ttlMs".to_string(), Value::Number(hints.ttl_ms.into()));
object.insert(
"cacheScope".to_string(),
Value::String(hints.scope.as_str().to_string()),
);
}
match object.get_mut("_meta") {
Some(Value::Object(existing)) => {
existing.insert(meta::KEY_SERVER_INFO.to_string(), server_info.clone());
}
_ => {
object.insert(
"_meta".to_string(),
serde_json::json!({ meta::KEY_SERVER_INFO: server_info }),
);
}
}
Value::Object(object)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn request_key_distinguishes_string_from_number() {
let numeric = RequestKey::from_value(&serde_json::json!(1)).unwrap();
let textual = RequestKey::from_value(&serde_json::json!("1")).unwrap();
assert_ne!(numeric, textual);
}
#[test]
fn request_key_rejects_null_and_composite_ids() {
assert!(RequestKey::from_value(&Value::Null).is_none());
assert!(RequestKey::from_value(&serde_json::json!([1])).is_none());
assert!(RequestKey::from_value(&serde_json::json!({})).is_none());
}
#[test]
fn request_key_round_trips() {
for value in [serde_json::json!(7), serde_json::json!("abc")] {
let key = RequestKey::from_value(&value).unwrap();
assert_eq!(key.to_value(), value);
}
}
#[test]
fn complete_always_stamps_result_type_and_server_info() {
let info = serde_json::json!({ "name": "atpmcp", "version": "1" });
let result = complete(serde_json::json!({ "tools": [] }), None, &info);
assert_eq!(result["resultType"], "complete");
assert_eq!(result["_meta"]["io.modelcontextprotocol/serverInfo"], info);
assert!(result.get("ttlMs").is_none());
assert!(result.get("cacheScope").is_none());
}
#[test]
fn complete_preserves_meta_the_payload_already_carries() {
let info = serde_json::json!({ "name": "atpmcp" });
let payload = serde_json::json!({
"_meta": { "io.modelcontextprotocol/subscriptionId": 7 }
});
let result = complete(payload, None, &info);
assert_eq!(result["_meta"]["io.modelcontextprotocol/subscriptionId"], 7);
assert_eq!(result["_meta"][meta::KEY_SERVER_INFO], info);
}
#[test]
fn complete_emits_cache_hints_when_given() {
let info = serde_json::json!({ "name": "atpmcp" });
let result = complete(
serde_json::json!({ "resources": [] }),
Some(CacheHints::constant()),
&info,
);
assert_eq!(result["ttlMs"], 3_600_000);
assert_eq!(result["cacheScope"], "public");
}
#[test]
fn cache_hint_ttls_are_non_negative() {
for hints in [
CacheHints::constant(),
CacheHints::immutable_content(),
CacheHints::short_list(),
] {
assert!(hints.ttl_ms > 0);
}
}
}