agent_client_protocol_schema/
rpc.rs1use std::sync::Arc;
7
8use derive_more::Display;
9use serde::{Deserialize, Serialize};
10use serde_with::skip_serializing_none;
11
12pub use crate::v1::{Request, RequestId, Response};
14
15#[skip_serializing_none]
17#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
18#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
19#[allow(
20 clippy::exhaustive_structs,
21 reason = "This comes from the JSON-RPC specification itself"
22)]
23#[cfg_attr(feature = "schemars", schemars(rename = "{Params}", extend("x-docs-ignore" = true)))]
24pub struct Notification<Params> {
25 pub method: Arc<str>,
27 pub params: Option<Params>,
29}
30
31#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[cfg_attr(feature = "schemars", schemars(inline))]
34enum JsonRpcVersion {
35 #[serde(rename = "2.0")]
36 V2,
37}
38
39#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[cfg_attr(feature = "schemars", schemars(inline))]
46pub struct JsonRpcMessage<M> {
47 jsonrpc: JsonRpcVersion,
48 #[serde(flatten)]
49 message: M,
50}
51
52impl<M> JsonRpcMessage<M> {
53 #[must_use]
55 pub fn wrap(message: M) -> Self {
56 Self {
57 jsonrpc: JsonRpcVersion::V2,
58 message,
59 }
60 }
61
62 #[must_use]
64 pub fn inner(&self) -> &M {
65 &self.message
66 }
67
68 #[must_use]
70 pub fn into_inner(self) -> M {
71 self.message
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
77#[display("JSON-RPC batch must contain at least one message")]
78#[non_exhaustive]
79pub struct EmptyJsonRpcBatch;
80
81impl std::error::Error for EmptyJsonRpcBatch {}
82
83#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86#[cfg_attr(feature = "schemars", schemars(inline))]
87#[serde(transparent)]
88#[allow(
89 clippy::exhaustive_structs,
90 reason = "This comes from the JSON-RPC specification itself"
91)]
92pub struct JsonRpcBatch<M>(
93 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<JsonRpcMessage<M>>,
94);
95
96impl<M> JsonRpcBatch<M> {
97 pub fn new(messages: Vec<JsonRpcMessage<M>>) -> Result<Self, EmptyJsonRpcBatch> {
106 if messages.is_empty() {
107 Err(EmptyJsonRpcBatch)
108 } else {
109 Ok(Self(messages))
110 }
111 }
112
113 #[must_use]
115 pub fn as_slice(&self) -> &[JsonRpcMessage<M>] {
116 &self.0
117 }
118
119 #[must_use]
121 pub fn into_vec(self) -> Vec<JsonRpcMessage<M>> {
122 self.0
123 }
124}
125
126impl<M> TryFrom<Vec<JsonRpcMessage<M>>> for JsonRpcBatch<M> {
127 type Error = EmptyJsonRpcBatch;
128
129 fn try_from(messages: Vec<JsonRpcMessage<M>>) -> Result<Self, Self::Error> {
130 Self::new(messages)
131 }
132}
133
134impl<'de, M> Deserialize<'de> for JsonRpcBatch<M>
135where
136 M: Deserialize<'de>,
137{
138 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
139 where
140 D: serde::Deserializer<'de>,
141 {
142 let messages = Vec::<JsonRpcMessage<M>>::deserialize(deserializer)?;
143 Self::new(messages).map_err(serde::de::Error::custom)
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 use crate::v1::{
152 AgentNotification, CancelNotification, ClientNotification, ContentBlock, ContentChunk,
153 SessionId, SessionNotification, SessionUpdate, TextContent,
154 };
155 use serde_json::{Value, json};
156
157 #[test]
158 fn notification_without_params_omits_the_key() {
159 let notification = Notification::<Value> {
160 method: "_example/ping".into(),
161 params: None,
162 };
163 assert_eq!(
164 serde_json::to_value(¬ification).unwrap(),
165 json!({ "method": "_example/ping" })
166 );
167
168 for wire in [
170 json!({ "method": "_example/ping" }),
171 json!({ "method": "_example/ping", "params": null }),
172 ] {
173 assert_eq!(
174 serde_json::from_value::<Notification<Value>>(wire).unwrap(),
175 notification
176 );
177 }
178 }
179
180 #[test]
181 fn v1_request_without_params_omits_the_key() {
182 let request = Request::<Value> {
183 id: RequestId::Number(1),
184 method: "session/list".into(),
185 params: None,
186 };
187 assert_eq!(
188 serde_json::to_value(&request).unwrap(),
189 json!({ "id": 1, "method": "session/list" })
190 );
191 }
192
193 #[test]
194 fn batch_deserialization_requires_at_least_one_message() {
195 let err = serde_json::from_value::<JsonRpcBatch<Notification<ClientNotification>>>(
196 Value::Array(Vec::new()),
197 )
198 .unwrap_err();
199 assert!(err.to_string().contains("at least one message"));
200 }
201
202 #[test]
203 fn batch_serialization_round_trips_non_empty_messages() {
204 let notification = JsonRpcMessage::wrap(Notification {
205 method: "cancel".into(),
206 params: Some(ClientNotification::CancelNotification(CancelNotification {
207 session_id: SessionId("test-123".into()),
208 meta: None,
209 })),
210 });
211
212 let batch = JsonRpcBatch::new(vec![notification]).unwrap();
213 let serialized = serde_json::to_value(&batch).unwrap();
214 assert_eq!(
215 serialized,
216 json!([{
217 "jsonrpc": "2.0",
218 "method": "cancel",
219 "params": {
220 "sessionId": "test-123"
221 },
222 }])
223 );
224
225 let deserialized =
226 serde_json::from_value::<JsonRpcBatch<Notification<ClientNotification>>>(serialized)
227 .unwrap();
228 assert_eq!(deserialized.as_slice().len(), 1);
229 assert_eq!(deserialized.as_slice()[0].inner().method.as_ref(), "cancel");
230 }
231
232 #[test]
233 fn notification_wire_format() {
234 let outgoing_msg = JsonRpcMessage::wrap(Notification {
236 method: "cancel".into(),
237 params: Some(ClientNotification::CancelNotification(CancelNotification {
238 session_id: SessionId("test-123".into()),
239 meta: None,
240 })),
241 });
242
243 let serialized: Value = serde_json::to_value(&outgoing_msg).unwrap();
244 assert_eq!(
245 serialized,
246 json!({
247 "jsonrpc": "2.0",
248 "method": "cancel",
249 "params": {
250 "sessionId": "test-123"
251 },
252 })
253 );
254
255 let outgoing_msg = JsonRpcMessage::wrap(Notification {
257 method: "sessionUpdate".into(),
258 params: Some(AgentNotification::SessionNotification(
259 SessionNotification {
260 session_id: SessionId("test-456".into()),
261 update: SessionUpdate::AgentMessageChunk(ContentChunk {
262 content: ContentBlock::Text(TextContent {
263 annotations: None,
264 text: "Hello".to_string(),
265 meta: None,
266 }),
267 message_id: None,
268 meta: None,
269 }),
270 meta: None,
271 },
272 )),
273 });
274
275 let serialized: Value = serde_json::to_value(&outgoing_msg).unwrap();
276 assert_eq!(
277 serialized,
278 json!({
279 "jsonrpc": "2.0",
280 "method": "sessionUpdate",
281 "params": {
282 "sessionId": "test-456",
283 "update": {
284 "sessionUpdate": "agent_message_chunk",
285 "content": {
286 "type": "text",
287 "text": "Hello"
288 }
289 }
290 }
291 })
292 );
293 }
294}