Skip to main content

openclaw_gateway/
rpc.rs

1//! JSON-RPC protocol.
2
3use serde::{Deserialize, Serialize};
4
5/// JSON-RPC request.
6#[derive(Debug, Deserialize)]
7pub struct RpcRequest {
8    /// JSON-RPC version.
9    pub jsonrpc: String,
10    /// Method name.
11    pub method: String,
12    /// Request parameters.
13    pub params: serde_json::Value,
14    /// Request ID.
15    pub id: Option<String>,
16}
17
18/// JSON-RPC response.
19#[derive(Debug, Serialize)]
20pub struct RpcResponse {
21    /// JSON-RPC version.
22    pub jsonrpc: String,
23    /// Result (if success).
24    pub result: Option<serde_json::Value>,
25    /// Error (if failure).
26    pub error: Option<RpcError>,
27    /// Request ID.
28    pub id: Option<String>,
29}
30
31/// JSON-RPC error.
32#[derive(Debug, Serialize)]
33pub struct RpcError {
34    /// Error code.
35    pub code: i32,
36    /// Error message.
37    pub message: String,
38    /// Additional data.
39    pub data: Option<serde_json::Value>,
40}
41
42impl RpcResponse {
43    /// Create a success response.
44    #[must_use]
45    pub fn success(id: Option<String>, result: serde_json::Value) -> Self {
46        Self {
47            jsonrpc: "2.0".to_string(),
48            result: Some(result),
49            error: None,
50            id,
51        }
52    }
53
54    /// Create an error response.
55    #[must_use]
56    pub fn error(id: Option<String>, code: i32, message: impl Into<String>) -> Self {
57        Self {
58            jsonrpc: "2.0".to_string(),
59            result: None,
60            error: Some(RpcError {
61                code,
62                message: message.into(),
63                data: None,
64            }),
65            id,
66        }
67    }
68}
69
70// Standard JSON-RPC error codes
71/// Parse error.
72pub const PARSE_ERROR: i32 = -32700;
73/// Invalid request.
74pub const INVALID_REQUEST: i32 = -32600;
75/// Method not found.
76pub const METHOD_NOT_FOUND: i32 = -32601;
77/// Invalid params.
78pub const INVALID_PARAMS: i32 = -32602;
79/// Internal error.
80pub const INTERNAL_ERROR: i32 = -32603;
81
82// Application-specific error codes (using -32000 to -32099 range)
83/// Unauthorized (authentication required or failed).
84pub const UNAUTHORIZED: i32 = -32001;
85/// Forbidden (insufficient permissions).
86pub const FORBIDDEN: i32 = -32002;
87/// Resource not found.
88pub const NOT_FOUND: i32 = -32003;