Skip to main content

kimi_wire/protocol/
jsonrpc.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4/// JSON-RPC version marker.
5///
6/// This type can only represent the value `"2.0"`, matching the JSON-RPC 2.0
7/// specification. It serializes as the JSON string `"2.0"` and deserialization
8/// rejects any other value.
9///
10/// Construct via [`JsonRpcVersion::V2`] or [`JsonRpcVersion::default()`].
11#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
12pub struct JsonRpcVersion;
13
14impl JsonRpcVersion {
15    /// The only valid JSON-RPC version this crate supports.
16    pub const V2: Self = Self;
17
18    /// Wire representation as a `&'static str` (`"2.0"`).
19    #[must_use]
20    pub const fn as_str(&self) -> &'static str {
21        "2.0"
22    }
23}
24
25impl serde::Serialize for JsonRpcVersion {
26    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
27        serializer.serialize_str(self.as_str())
28    }
29}
30
31impl<'de> serde::Deserialize<'de> for JsonRpcVersion {
32    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
33        let s = <std::borrow::Cow<'_, str>>::deserialize(deserializer)?;
34        if s == "2.0" {
35            Ok(Self)
36        } else {
37            Err(serde::de::Error::custom(format!(
38                "unsupported JSON-RPC version: expected \"2.0\", got {s:?}"
39            )))
40        }
41    }
42}
43
44/// A JSON-RPC 2.0 request.
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46pub struct JsonRpcRequest<Params> {
47    /// JSON-RPC version.
48    pub jsonrpc: JsonRpcVersion,
49    /// Method name.
50    pub method: String,
51    /// Request id.
52    pub id: String,
53    /// Method parameters.
54    pub params: Params,
55}
56
57/// A JSON-RPC 2.0 notification (no id).
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59pub struct JsonRpcNotification<Params> {
60    /// JSON-RPC version.
61    pub jsonrpc: JsonRpcVersion,
62    /// Method name.
63    pub method: String,
64    /// Method parameters.
65    pub params: Params,
66}
67
68/// A successful JSON-RPC 2.0 response.
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
70pub struct JsonRpcSuccessResponse<Result> {
71    /// JSON-RPC version.
72    pub jsonrpc: JsonRpcVersion,
73    /// Request id matching the request.
74    pub id: String,
75    /// Result value.
76    pub result: Result,
77}
78
79/// An error JSON-RPC 2.0 response.
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
81pub struct JsonRpcErrorResponse {
82    /// JSON-RPC version.
83    pub jsonrpc: JsonRpcVersion,
84    /// Request id matching the request (or `null`).
85    pub id: String,
86    /// Error details.
87    pub error: JsonRpcError,
88}
89
90/// JSON-RPC error object.
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
92pub struct JsonRpcError {
93    /// Error code.
94    pub code: i32,
95    /// Error message.
96    pub message: String,
97    /// Additional error data.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub data: Option<Value>,
100}
101
102/// JSON-RPC error code for "Method not found".
103pub const METHOD_NOT_FOUND: i32 = -32601;
104
105/// A raw, untyped wire message for low-level parsing.
106///
107/// All fields are optional so that any valid JSON-RPC line can be parsed
108/// without knowing the concrete schema upfront.
109#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
110pub struct RawWireMessage {
111    /// JSON-RPC version.
112    pub jsonrpc: JsonRpcVersion,
113    /// Request/response id, if present.
114    pub id: Option<String>,
115    /// Method name for requests/notifications.
116    pub method: Option<String>,
117    /// Parameters for requests/notifications.
118    pub params: Option<Value>,
119    /// Result for success responses.
120    pub result: Option<Value>,
121    /// Error for error responses.
122    pub error: Option<JsonRpcError>,
123}