model_context_protocol/
lib.rs1use serde::{Deserialize, Serialize};
16
17pub const PROTOCOL_VERSION: &str = "0.1.0";
19
20pub trait Protocol {
22 fn initialize(&mut self) -> Result<(), Error>;
24
25 fn send_message(&self, message: Message) -> Result<(), Error>;
27
28 fn receive_message(&self) -> Result<Message, Error>;
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct Message {
35 pub id: String,
37 pub message_type: MessageType,
39 pub payload: serde_json::Value,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
45pub enum MessageType {
46 Request,
48 Response,
50 Notification,
52 Error,
54}
55
56#[derive(Debug, Clone)]
58pub enum Error {
59 ConnectionError(String),
61 SerializationError(String),
63 ProtocolError(String),
65 Unknown(String),
67}
68
69impl std::fmt::Display for Error {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 match self {
72 Error::ConnectionError(msg) => write!(f, "Connection error: {}", msg),
73 Error::SerializationError(msg) => write!(f, "Serialization error: {}", msg),
74 Error::ProtocolError(msg) => write!(f, "Protocol error: {}", msg),
75 Error::Unknown(msg) => write!(f, "Unknown error: {}", msg),
76 }
77 }
78}
79
80impl std::error::Error for Error {}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 #[test]
87 fn test_protocol_version() {
88 assert_eq!(PROTOCOL_VERSION, "0.1.0");
89 }
90
91 #[test]
92 fn test_message_serialization() {
93 let msg = Message {
94 id: "test-123".to_string(),
95 message_type: MessageType::Request,
96 payload: serde_json::json!({"test": "data"}),
97 };
98
99 let serialized = serde_json::to_string(&msg).unwrap();
100 let deserialized: Message = serde_json::from_str(&serialized).unwrap();
101
102 assert_eq!(msg.id, deserialized.id);
103 }
104}