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#[expect(
20 clippy::exhaustive_structs,
21 reason = "callers construct notifications with the fields defined by JSON-RPC"
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))]
86#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
87#[cfg_attr(feature = "schemars", schemars(inline))]
88#[serde(transparent)]
89pub struct JsonRpcBatch<M>(
90 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))] Vec<JsonRpcMessage<M>>,
91);
92
93impl<M> JsonRpcBatch<M> {
94 pub fn new(messages: Vec<JsonRpcMessage<M>>) -> Result<Self, EmptyJsonRpcBatch> {
103 if messages.is_empty() {
104 Err(EmptyJsonRpcBatch)
105 } else {
106 Ok(Self(messages))
107 }
108 }
109
110 #[must_use]
112 pub fn as_slice(&self) -> &[JsonRpcMessage<M>] {
113 &self.0
114 }
115
116 #[must_use]
118 pub fn into_vec(self) -> Vec<JsonRpcMessage<M>> {
119 self.0
120 }
121}
122
123impl<M> TryFrom<Vec<JsonRpcMessage<M>>> for JsonRpcBatch<M> {
124 type Error = EmptyJsonRpcBatch;
125
126 fn try_from(messages: Vec<JsonRpcMessage<M>>) -> Result<Self, Self::Error> {
127 Self::new(messages)
128 }
129}
130
131impl<'de, M> Deserialize<'de> for JsonRpcBatch<M>
132where
133 M: Deserialize<'de>,
134{
135 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
136 where
137 D: serde::Deserializer<'de>,
138 {
139 let messages = Vec::<JsonRpcMessage<M>>::deserialize(deserializer)?;
140 Self::new(messages).map_err(serde::de::Error::custom)
141 }
142}
143
144#[cfg(test)]
145mod tests {
146 use super::*;
147
148 use crate::v1::{
149 AgentNotification, CancelNotification, ClientNotification, ContentBlock, ContentChunk,
150 SessionId, SessionNotification, SessionUpdate, TextContent,
151 };
152 use serde_json::{Value, json};
153
154 #[test]
155 fn notification_without_params_omits_the_key() {
156 let notification = Notification::<Value> {
157 method: "_example/ping".into(),
158 params: None,
159 };
160 assert_eq!(
161 serde_json::to_value(¬ification).unwrap(),
162 json!({ "method": "_example/ping" })
163 );
164
165 for wire in [
167 json!({ "method": "_example/ping" }),
168 json!({ "method": "_example/ping", "params": null }),
169 ] {
170 assert_eq!(
171 serde_json::from_value::<Notification<Value>>(wire).unwrap(),
172 notification
173 );
174 }
175 }
176
177 #[test]
178 fn v1_request_without_params_omits_the_key() {
179 let request = Request::<Value> {
180 id: RequestId::Number(1),
181 method: "session/list".into(),
182 params: None,
183 };
184 assert_eq!(
185 serde_json::to_value(&request).unwrap(),
186 json!({ "id": 1, "method": "session/list" })
187 );
188 }
189
190 #[test]
191 fn batch_deserialization_requires_at_least_one_message() {
192 let err = serde_json::from_value::<JsonRpcBatch<Notification<ClientNotification>>>(
193 Value::Array(Vec::new()),
194 )
195 .unwrap_err();
196 assert!(err.to_string().contains("at least one message"));
197 }
198
199 #[test]
200 fn batch_serialization_round_trips_non_empty_messages() {
201 let notification = JsonRpcMessage::wrap(Notification {
202 method: "cancel".into(),
203 params: Some(ClientNotification::CancelNotification(CancelNotification {
204 session_id: SessionId("test-123".into()),
205 meta: None,
206 })),
207 });
208
209 let batch = JsonRpcBatch::new(vec![notification]).unwrap();
210 let serialized = serde_json::to_value(&batch).unwrap();
211 assert_eq!(
212 serialized,
213 json!([{
214 "jsonrpc": "2.0",
215 "method": "cancel",
216 "params": {
217 "sessionId": "test-123"
218 },
219 }])
220 );
221
222 let deserialized =
223 serde_json::from_value::<JsonRpcBatch<Notification<ClientNotification>>>(serialized)
224 .unwrap();
225 assert_eq!(deserialized.as_slice().len(), 1);
226 assert_eq!(deserialized.as_slice()[0].inner().method.as_ref(), "cancel");
227 }
228
229 #[test]
230 fn notification_wire_format() {
231 let outgoing_msg = JsonRpcMessage::wrap(Notification {
233 method: "cancel".into(),
234 params: Some(ClientNotification::CancelNotification(CancelNotification {
235 session_id: SessionId("test-123".into()),
236 meta: None,
237 })),
238 });
239
240 let serialized: Value = serde_json::to_value(&outgoing_msg).unwrap();
241 assert_eq!(
242 serialized,
243 json!({
244 "jsonrpc": "2.0",
245 "method": "cancel",
246 "params": {
247 "sessionId": "test-123"
248 },
249 })
250 );
251
252 let outgoing_msg = JsonRpcMessage::wrap(Notification {
254 method: "sessionUpdate".into(),
255 params: Some(AgentNotification::SessionNotification(
256 SessionNotification {
257 session_id: SessionId("test-456".into()),
258 update: SessionUpdate::AgentMessageChunk(ContentChunk {
259 content: ContentBlock::Text(TextContent {
260 annotations: None,
261 text: "Hello".to_string(),
262 meta: None,
263 }),
264 message_id: None,
265 meta: None,
266 }),
267 meta: None,
268 },
269 )),
270 });
271
272 let serialized: Value = serde_json::to_value(&outgoing_msg).unwrap();
273 assert_eq!(
274 serialized,
275 json!({
276 "jsonrpc": "2.0",
277 "method": "sessionUpdate",
278 "params": {
279 "sessionId": "test-456",
280 "update": {
281 "sessionUpdate": "agent_message_chunk",
282 "content": {
283 "type": "text",
284 "text": "Hello"
285 }
286 }
287 }
288 })
289 );
290 }
291}