Skip to main content

systemprompt_agent/models/a2a/
jsonrpc.rs

1//! JSON-RPC 2.0 framing primitives: request identifiers and the request and
2//! response envelopes used by the A2A protocol.
3//!
4//! Copyright (c) systemprompt.io — Business Source License 1.1.
5//! See <https://systemprompt.io> for licensing details.
6
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10pub const JSON_RPC_VERSION_2_0: &str = "2.0";
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13#[serde(untagged)]
14pub enum RequestId {
15    String(String),
16    Number(i64),
17}
18
19pub type NumberOrString = RequestId;
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Request<T> {
23    pub jsonrpc: String,
24    pub method: String,
25    pub params: T,
26    pub id: RequestId,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
30pub struct JsonRpcResponse<T> {
31    pub jsonrpc: String,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub result: Option<T>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub error: Option<JsonRpcError>,
36    pub id: RequestId,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
40pub struct JsonRpcError {
41    pub code: i32,
42    pub message: String,
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub data: Option<Value>,
45}
46
47impl JsonRpcError {
48    pub fn new(code: i32, message: impl Into<String>) -> Self {
49        Self {
50            code,
51            message: message.into(),
52            data: None,
53        }
54    }
55
56    pub fn with_data(code: i32, message: impl Into<String>, data: Value) -> Self {
57        Self {
58            code,
59            message: message.into(),
60            data: Some(data),
61        }
62    }
63
64    pub fn parse_error() -> Self {
65        Self::new(-32700, "Parse error")
66    }
67
68    pub fn invalid_request() -> Self {
69        Self::new(-32600, "Invalid Request")
70    }
71
72    pub fn method_not_found() -> Self {
73        Self::new(-32601, "Method not found")
74    }
75
76    pub fn invalid_params() -> Self {
77        Self::new(-32602, "Invalid params")
78    }
79
80    pub fn internal_error() -> Self {
81        Self::new(-32603, "Internal error")
82    }
83}