agent_client_protocol_schema/v2/
rpc.rs1use std::sync::Arc;
7
8use derive_more::{Display, From};
9use serde::{Deserialize, Serialize};
10use serde_with::skip_serializing_none;
11
12use super::Error;
13
14#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
20#[derive(
21 Debug, PartialEq, Clone, Hash, Eq, Deserialize, Serialize, PartialOrd, Ord, Display, From,
22)]
23#[serde(untagged)]
24#[expect(
25 clippy::exhaustive_enums,
26 reason = "Request IDs are limited to JSON-RPC's non-null ID types"
27)]
28#[from(String, i64)]
29pub enum RequestId {
30 Number(i64),
32 Str(String),
34}
35
36#[skip_serializing_none]
38#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
39#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
40#[expect(
41 clippy::exhaustive_structs,
42 reason = "callers construct requests with the fields defined by JSON-RPC"
43)]
44#[cfg_attr(feature = "schemars", schemars(rename = "{Params}", extend("x-docs-ignore" = true)))]
45pub struct Request<Params> {
46 pub id: RequestId,
48 pub method: Arc<str>,
50 pub params: Option<Params>,
52}
53
54#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
56#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
57#[expect(
58 clippy::exhaustive_enums,
59 reason = "a JSON-RPC response contains either a result or an error"
60)]
61#[serde(untagged)]
62#[cfg_attr(feature = "schemars", schemars(rename = "{Result}", extend("x-docs-ignore" = true)))]
63pub enum Response<Result> {
64 Result {
66 id: RequestId,
68 #[serde(
71 deserialize_with = "Deserialize::deserialize",
72 bound(deserialize = "Result: Deserialize<'de>")
73 )]
74 result: Result,
75 },
76 Error {
78 #[serde(deserialize_with = "Option::deserialize")]
84 #[cfg_attr(feature = "schemars", schemars(required, transform = nullable_request_id))]
85 id: Option<RequestId>,
86 error: Error,
88 },
89}
90
91#[cfg(feature = "schemars")]
94fn nullable_request_id(schema: &mut schemars::Schema) {
95 let null = serde_json::json!({ "type": "null" });
96 if let Some(variants) = schema
97 .get_mut("anyOf")
98 .and_then(serde_json::Value::as_array_mut)
99 && !variants.contains(&null)
100 {
101 variants.push(null);
102 }
103}
104
105impl<R> Response<R> {
106 #[must_use]
108 pub fn new(id: impl Into<RequestId>, result: std::result::Result<R, Error>) -> Self {
109 match result {
110 Ok(result) => Self::Result {
111 id: id.into(),
112 result,
113 },
114 Err(error) => Self::Error {
115 id: Some(id.into()),
116 error,
117 },
118 }
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::*;
125
126 use serde_json::{Value, json};
127
128 #[test]
129 fn request_without_params_omits_the_key() {
130 let request = Request::<Value> {
131 id: RequestId::Number(1),
132 method: "session/list".into(),
133 params: None,
134 };
135 assert_eq!(
136 serde_json::to_value(&request).unwrap(),
137 json!({ "id": 1, "method": "session/list" })
138 );
139
140 for wire in [
142 json!({ "id": 1, "method": "session/list" }),
143 json!({ "id": 1, "method": "session/list", "params": null }),
144 ] {
145 assert_eq!(
146 serde_json::from_value::<Request<Value>>(wire).unwrap(),
147 request
148 );
149 }
150 }
151
152 #[test]
153 fn request_id_rejects_null() {
154 assert!(serde_json::from_value::<RequestId>(Value::Null).is_err());
155 assert!(
156 serde_json::from_value::<Request<Value>>(json!({ "id": null, "method": "m" })).is_err()
157 );
158 assert_eq!(
159 serde_json::from_value::<RequestId>(json!(-1)).unwrap(),
160 RequestId::Number(-1)
161 );
162 assert_eq!(
163 serde_json::from_value::<RequestId>(json!("id")).unwrap(),
164 RequestId::Str("id".to_owned())
165 );
166 }
167
168 #[test]
169 fn error_response_id_is_required_and_nullable() {
170 let error = json!({ "code": -32700, "message": "Parse error" });
171
172 let response =
173 serde_json::from_value::<Response<Value>>(json!({ "id": null, "error": error }))
174 .unwrap();
175 assert!(matches!(response, Response::Error { id: None, .. }));
176 assert_eq!(
177 serde_json::to_value(&response).unwrap(),
178 json!({ "id": null, "error": error })
179 );
180
181 assert!(serde_json::from_value::<Response<Value>>(json!({ "error": error })).is_err());
182 assert!(
183 serde_json::from_value::<Response<Value>>(json!({ "id": null, "result": {} })).is_err()
184 );
185 }
186}