Skip to main content

agent_client_protocol/jsonrpc/
raw_error.rs

1//! Transport-level error objects, before choosing an application protocol.
2
3use agent_client_protocol_schema::MaybeUndefined;
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6
7use super::RawJsonRpcId;
8
9/// A JSON-RPC error without ACP-specific interpretation.
10///
11/// Raw transports and relays preserve unknown fields and distinguish omitted
12/// `data` from explicit JSON null. Convert to [`crate::Error`] only when
13/// dispatching an ACP response; other protocols have their own error domains.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[non_exhaustive]
16pub struct RawJsonRpcError {
17    /// The peer's numeric error code, not an ACP [`crate::ErrorCode`].
18    pub code: i32,
19    /// The peer's error message.
20    pub message: String,
21    /// Optional error data. Explicit null is retained separately from omission.
22    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
23    pub data: MaybeUndefined<Value>,
24    /// Additional fields on the error object.
25    #[serde(flatten)]
26    pub extra: Map<String, Value>,
27}
28
29/// A transport-level JSON-RPC response with an opaque result or raw error.
30///
31/// Errors are boxed so their extensible representation does not enlarge every
32/// request, notification, and queued frame.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(untagged)]
35pub enum RawJsonRpcResponse {
36    /// A successful response.
37    Result {
38        /// The ID of the request this response answers.
39        id: RawJsonRpcId,
40        /// The result, uninterpreted.
41        // Require the key even though `Value` accepts null.
42        #[serde(deserialize_with = "Deserialize::deserialize")]
43        result: Value,
44    },
45    /// An Error Response.
46    Error {
47        /// The ID of the request this response answers, or `null` when it
48        /// could not be determined.
49        id: RawJsonRpcId,
50        /// The error, uninterpreted.
51        error: Box<RawJsonRpcError>,
52    },
53}
54
55impl RawJsonRpcResponse {
56    /// Builds a response from a Rust [`Result`].
57    #[must_use]
58    pub fn new(id: impl Into<RawJsonRpcId>, result: Result<Value, Box<RawJsonRpcError>>) -> Self {
59        let id = id.into();
60        match result {
61            Ok(result) => Self::Result { id, result },
62            Err(error) => Self::Error { id, error },
63        }
64    }
65
66    /// The ID of the request this response answers.
67    #[must_use]
68    pub fn id(&self) -> &RawJsonRpcId {
69        match self {
70            Self::Result { id, .. } | Self::Error { id, .. } => id,
71        }
72    }
73}
74
75impl RawJsonRpcError {
76    /// Construct an error without data or extension fields.
77    #[must_use]
78    pub fn new(code: i32, message: impl Into<String>) -> Self {
79        Self {
80            code,
81            message: message.into(),
82            data: MaybeUndefined::Undefined,
83            extra: Map::new(),
84        }
85    }
86
87    /// Set error data, preserving explicit null.
88    #[must_use]
89    pub fn data(mut self, data: Value) -> Self {
90        self.data = if data.is_null() {
91            MaybeUndefined::Null
92        } else {
93            MaybeUndefined::Value(data)
94        };
95        self
96    }
97
98    /// Interpret this error as an ACP response for the typed dispatcher.
99    ///
100    /// ACP's error type does not model extension fields, so this intentionally
101    /// discards `extra`. Do not use it when forwarding raw frames or interpreting
102    /// errors from another protocol.
103    #[must_use]
104    pub fn into_acp_error(self) -> crate::Error {
105        let mut error = crate::Error::new(self.code, self.message);
106        error.data = match self.data {
107            MaybeUndefined::Undefined => None,
108            MaybeUndefined::Null => Some(Value::Null),
109            MaybeUndefined::Value(data) => Some(data),
110        };
111        error
112    }
113}
114
115impl From<crate::Error> for RawJsonRpcError {
116    fn from(error: crate::Error) -> Self {
117        let raw = Self::new(error.code.into(), error.message);
118        match error.data {
119            Some(data) => raw.data(data),
120            None => raw,
121        }
122    }
123}
124
125impl std::fmt::Display for RawJsonRpcError {
126    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(formatter, "{} ({})", self.message, self.code)
128    }
129}
130
131impl std::error::Error for RawJsonRpcError {}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::{Channel, RawJsonRpcMessage, TransportFrame};
137    use futures::StreamExt as _;
138    use serde_json::json;
139
140    #[test]
141    fn raw_errors_preserve_codes_data_presence_and_extensions() {
142        for code in [i32::MIN, -32000, -32602, 0, 12345, i32::MAX] {
143            for data in [None, Some(Value::Null), Some(json!({"detail":[1,2]}))] {
144                let mut error = json!({
145                    "code": code,
146                    "message": "peer",
147                    "extension": {"retry": true},
148                    "_meta": {"opaque": "kept"}
149                });
150                if let Some(data) = &data {
151                    error["data"] = data.clone();
152                }
153                let wire = json!({"jsonrpc":"2.0", "id":"logical", "error":error});
154                let parsed: RawJsonRpcMessage = serde_json::from_value(wire.clone()).unwrap();
155                assert_eq!(serde_json::to_value(&parsed).unwrap(), wire);
156                let RawJsonRpcMessage::Response(RawJsonRpcResponse::Error { error, .. }) = parsed
157                else {
158                    panic!("expected a raw error response");
159                };
160                assert_eq!(error.code, code);
161                match data {
162                    None => assert!(error.data.is_undefined()),
163                    Some(Value::Null) => assert!(error.data.is_null()),
164                    Some(value) => assert_eq!(error.data.value(), Some(&value)),
165                }
166            }
167        }
168    }
169
170    #[tokio::test]
171    async fn raw_responses_survive_framing_and_channel_relay() {
172        let error = json!({"code":-32000, "message":"peer", "extension":{"retry":true}});
173        for wire in [
174            json!({"jsonrpc":"2.0", "id":"error", "error":error}),
175            json!([
176                {"jsonrpc":"2.0", "id":"omitted", "error":error},
177                {"jsonrpc":"2.0", "id":"null", "error":{
178                    "code":12345, "message":"peer", "data":null, "_meta":{"opaque":"kept"}
179                }},
180                {"jsonrpc":"2.0", "id":"success", "result":null}
181            ]),
182        ] {
183            let frame = TransportFrame::parse_json(&wire.to_string());
184            let (source, relay_in) = Channel::duplex();
185            let (relay_out, mut destination) = Channel::duplex();
186            source.tx.unbounded_send(frame).unwrap();
187            drop(source);
188            Channel {
189                rx: relay_in.rx,
190                tx: relay_out.tx,
191            }
192            .copy()
193            .await
194            .unwrap();
195            let received = destination.rx.next().await.unwrap();
196            let received: Value = serde_json::from_str(&received.to_json().unwrap()).unwrap();
197            assert_eq!(received, wire);
198        }
199    }
200
201    #[test]
202    fn acp_error_interpretation_is_explicit_and_keeps_data_presence() {
203        for (code, expected_code) in [
204            (-32000, crate::ErrorCode::AUTH_REQUIRED),
205            (12345, crate::ErrorCode::new(12345)),
206        ] {
207            for data in [None, Some(Value::Null), Some(json!({"detail":"kept"}))] {
208                let mut raw = RawJsonRpcError::new(code, "peer");
209                raw.extra.insert("extension".into(), json!(true));
210                if let Some(data) = &data {
211                    raw = raw.data(data.clone());
212                }
213                let error = raw.into_acp_error();
214                assert_eq!(error.code, expected_code);
215                assert_eq!(error.message, "peer");
216                assert_eq!(error.data, data);
217                let roundtrip = RawJsonRpcError::from(error);
218                assert_eq!(roundtrip.code, code);
219                assert!(roundtrip.extra.is_empty());
220                match data {
221                    None => assert!(roundtrip.data.is_undefined()),
222                    Some(Value::Null) => assert!(roundtrip.data.is_null()),
223                    Some(value) => assert_eq!(roundtrip.data.value(), Some(&value)),
224                }
225            }
226        }
227    }
228
229    #[test]
230    fn acp_response_constructor_preserves_explicit_null_data() {
231        for data in [None, Some(Value::Null), Some(json!({"detail":"kept"}))] {
232            let mut error = crate::Error::invalid_params();
233            error.data = data.clone();
234            let message = RawJsonRpcMessage::response(RawJsonRpcId::Null, Err(error));
235            let wire = serde_json::to_value(message).unwrap();
236            assert_eq!(wire["error"]["code"], -32602);
237            assert_eq!(wire["error"].get("data"), data.as_ref());
238        }
239    }
240
241    #[test]
242    fn malformed_raw_errors_are_still_rejected() {
243        for error in [
244            Value::Null,
245            json!({"code":-32000}),
246            json!({"message":"peer"}),
247            json!({"code":null, "message":"peer"}),
248            json!({"code":"-32000", "message":"peer"}),
249            json!({"code":1.5, "message":"peer"}),
250            json!({"code":-32000, "message":null}),
251        ] {
252            assert!(
253                serde_json::from_value::<RawJsonRpcMessage>(
254                    json!({"jsonrpc":"2.0", "id":1, "error":error})
255                )
256                .is_err()
257            );
258        }
259    }
260}