1use crate::llm::actions::{
4 client_trait::{Client, ClientActionResult},
5 protocol_trait::Protocol,
6 ActionDefinition, Parameter, ParameterDefinition,
7};
8use crate::protocol::EventType;
9use crate::state::app_state::AppState;
10use anyhow::{Context, Result};
11use serde_json::json;
12use std::sync::LazyLock;
13
14pub static JSONRPC_CLIENT_CONNECTED_EVENT: LazyLock<EventType> = LazyLock::new(|| {
16 EventType::new(
17 "jsonrpc_connected",
18 "JSON-RPC client initialized and ready to send requests",
19 json!({"type": "send_jsonrpc_request", "method": "add", "params": [5, 3], "id": 1}),
20 )
21 .with_parameters(vec![Parameter {
22 name: "endpoint".to_string(),
23 type_hint: "string".to_string(),
24 description: "JSON-RPC endpoint URL".to_string(),
25 required: true,
26 }])
27});
28
29pub static JSONRPC_CLIENT_RESPONSE_RECEIVED_EVENT: LazyLock<EventType> = LazyLock::new(|| {
31 EventType::new(
32 "jsonrpc_response_received",
33 "JSON-RPC response received from server",
34 json!({"type": "send_jsonrpc_request", "method": "getStatus", "id": 2}),
35 )
36 .with_parameters(vec![
37 Parameter {
38 name: "id".to_string(),
39 type_hint: "number | string | null".to_string(),
40 description: "Request ID matching the original request".to_string(),
41 required: false,
42 },
43 Parameter {
44 name: "result".to_string(),
45 type_hint: "any".to_string(),
46 description: "Result value (if success)".to_string(),
47 required: false,
48 },
49 Parameter {
50 name: "error".to_string(),
51 type_hint: "object".to_string(),
52 description: "Error object with code, message, and optional data (if error)"
53 .to_string(),
54 required: false,
55 },
56 ])
57});
58
59pub struct JsonRpcClientProtocol;
61
62impl JsonRpcClientProtocol {
63 pub fn new() -> Self {
64 Self
65 }
66}
67
68impl Protocol for JsonRpcClientProtocol {
70 fn get_startup_parameters(&self) -> Vec<ParameterDefinition> {
71 vec![ParameterDefinition {
72 name: "default_headers".to_string(),
73 description: "Default headers to include in all requests".to_string(),
74 type_hint: "object".to_string(),
75 required: false,
76 example: json!({
77 "Authorization": "Bearer token123",
78 "Content-Type": "application/json"
79 }),
80 default: None,
81 }]
82 }
83 fn get_async_actions(&self, _state: &AppState) -> Vec<ActionDefinition> {
84 vec![
85 ActionDefinition {
86 name: "send_jsonrpc_request".to_string(),
87 description: "Send a JSON-RPC 2.0 request to the server".to_string(),
88 parameters: vec![
89 Parameter {
90 name: "method".to_string(),
91 type_hint: "string".to_string(),
92 description: "JSON-RPC method name".to_string(),
93 required: true,
94 },
95 Parameter {
96 name: "params".to_string(),
97 type_hint: "array | object".to_string(),
98 description: "Method parameters (array or object)".to_string(),
99 required: false,
100 },
101 Parameter {
102 name: "id".to_string(),
103 type_hint: "number | string".to_string(),
104 description: "Request ID (omit for notification)".to_string(),
105 required: false,
106 },
107 ],
108 example: json!({
109 "type": "send_jsonrpc_request",
110 "method": "add",
111 "params": [5, 3],
112 "id": 1
113 }),
114 log_template: None,
115 },
116 ActionDefinition {
117 name: "send_jsonrpc_batch".to_string(),
118 description: "Send a batch of JSON-RPC 2.0 requests".to_string(),
119 parameters: vec![Parameter {
120 name: "requests".to_string(),
121 type_hint: "array".to_string(),
122 description: "Array of JSON-RPC request objects".to_string(),
123 required: true,
124 }],
125 example: json!({
126 "type": "send_jsonrpc_batch",
127 "requests": [
128 {"method": "add", "params": [1, 2], "id": 1},
129 {"method": "multiply", "params": [3, 4], "id": 2}
130 ]
131 }),
132 log_template: None,
133 },
134 ActionDefinition {
135 name: "disconnect".to_string(),
136 description: "Disconnect from the JSON-RPC server".to_string(),
137 parameters: vec![],
138 example: json!({
139 "type": "disconnect"
140 }),
141 log_template: None,
142 },
143 ]
144 }
145 fn get_sync_actions(&self) -> Vec<ActionDefinition> {
146 vec![
147 ActionDefinition {
148 name: "wait_for_more".to_string(),
149 description:
150 "Do nothing and wait for the next JSON-RPC response. The correct answer \
151 when what arrived needs no follow-up -- without it the model has to \
152 invent an action it does not want."
153 .to_string(),
154 parameters: vec![],
155 example: json!({
156 "type": "wait_for_more"
157 }),
158 log_template: None,
159 },
160 ActionDefinition {
161 name: "send_jsonrpc_request".to_string(),
162 description: "Send another JSON-RPC request in response to received data"
163 .to_string(),
164 parameters: vec![
165 Parameter {
166 name: "method".to_string(),
167 type_hint: "string".to_string(),
168 description: "JSON-RPC method name".to_string(),
169 required: true,
170 },
171 Parameter {
172 name: "params".to_string(),
173 type_hint: "array | object".to_string(),
174 description: "Method parameters".to_string(),
175 required: false,
176 },
177 Parameter {
178 name: "id".to_string(),
179 type_hint: "number | string".to_string(),
180 description: "Request ID".to_string(),
181 required: false,
182 },
183 ],
184 example: json!({
185 "type": "send_jsonrpc_request",
186 "method": "getStatus",
187 "id": 2
188 }),
189 log_template: None,
190 },
191 ]
192 }
193 fn protocol_name(&self) -> &'static str {
194 "JSON-RPC"
195 }
196 fn get_event_types(&self) -> Vec<EventType> {
197 vec![
198 EventType::new(
199 "jsonrpc_connected",
200 "Triggered when JSON-RPC client is initialized",
201 json!({"type": "send_jsonrpc_request", "method": "add", "params": [5, 3], "id": 1}),
202 ),
203 EventType::new(
204 "jsonrpc_response_received",
205 "Triggered when JSON-RPC client receives a response",
206 json!({"type": "send_jsonrpc_request", "method": "getStatus", "id": 2}),
207 ),
208 ]
209 }
210 fn stack_name(&self) -> &'static str {
211 "ETH>IP>TCP>HTTP>JSON-RPC"
212 }
213 fn keywords(&self) -> Vec<&'static str> {
214 vec!["jsonrpc", "json-rpc", "json rpc", "rpc"]
215 }
216 fn metadata(&self) -> crate::protocol::metadata::ProtocolMetadataV2 {
217 use crate::protocol::metadata::{DevelopmentState, ProtocolMetadataV2};
218
219 ProtocolMetadataV2::builder()
220 .state(DevelopmentState::Experimental)
221 .implementation("reqwest HTTP client with JSON-RPC 2.0 format")
222 .llm_control("Full control over RPC methods, parameters, batch requests")
223 .e2e_testing("Local JSON-RPC server or public JSON-RPC API")
224 .build()
225 }
226 fn description(&self) -> &'static str {
227 "JSON-RPC 2.0 client for making remote procedure calls"
228 }
229 fn example_prompt(&self) -> &'static str {
230 "Connect to JSON-RPC server at http://localhost:8080 and call method 'add' with params [5, 3]"
231 }
232 fn group_name(&self) -> &'static str {
233 "RPC"
234 }
235 fn get_startup_examples(&self) -> crate::llm::actions::StartupExamples {
236 use crate::llm::actions::StartupExamples;
237 use serde_json::json;
238
239 StartupExamples::new(
240 json!({
242 "type": "open_client",
243 "remote_addr": "http://localhost:8080",
244 "base_stack": "jsonrpc",
245 "instruction": "Call the 'add' method with params [5, 3] and report the result"
246 }),
247 json!({
249 "type": "open_client",
250 "remote_addr": "http://localhost:8080",
251 "base_stack": "jsonrpc",
252 "event_handlers": [{
253 "event_pattern": "jsonrpc_response_received",
254 "handler": {
255 "type": "script",
256 "language": "python",
257 "code": "<jsonrpc_client_handler>"
258 }
259 }]
260 }),
261 json!({
263 "type": "open_client",
264 "remote_addr": "http://localhost:8080",
265 "base_stack": "jsonrpc",
266 "event_handlers": [
267 {
268 "event_pattern": "jsonrpc_connected",
269 "handler": {
270 "type": "static",
271 "actions": [{
272 "type": "send_jsonrpc_request",
273 "method": "add",
274 "params": [5, 3],
275 "id": 1
276 }]
277 }
278 },
279 {
280 "event_pattern": "jsonrpc_response_received",
281 "handler": {
282 "type": "static",
283 "actions": [{
284 "type": "disconnect"
285 }]
286 }
287 }
288 ]
289 }),
290 )
291 }
292}
293
294impl Client for JsonRpcClientProtocol {
296 fn connect(
297 &self,
298 ctx: crate::protocol::ConnectContext,
299 ) -> std::pin::Pin<
300 Box<dyn std::future::Future<Output = anyhow::Result<std::net::SocketAddr>> + Send>,
301 > {
302 Box::pin(async move {
303 use crate::client::jsonrpc::JsonRpcClient;
304 JsonRpcClient::connect_with_llm_actions(
305 ctx.remote_addr,
306 ctx.llm_client,
307 ctx.state,
308 ctx.status_tx,
309 ctx.client_id,
310 ctx.startup_params,
311 )
312 .await
313 })
314 }
315 fn execute_action(&self, action: serde_json::Value) -> Result<ClientActionResult> {
316 let action_type = action
317 .get("type")
318 .and_then(|v| v.as_str())
319 .context("Missing 'type' field in action")?;
320
321 match action_type {
322 "send_jsonrpc_request" => {
323 let method = action
324 .get("method")
325 .and_then(|v| v.as_str())
326 .context("Missing 'method' field")?
327 .to_string();
328
329 let params = action.get("params").cloned();
330 let id = action.get("id").cloned();
331
332 Ok(ClientActionResult::Custom {
334 name: "jsonrpc_request".to_string(),
335 data: json!({
336 "method": method,
337 "params": params,
338 "id": id,
339 }),
340 })
341 }
342 "send_jsonrpc_batch" => {
343 let requests = action
344 .get("requests")
345 .and_then(|v| v.as_array())
346 .context("Missing 'requests' array")?
347 .clone();
348
349 Ok(ClientActionResult::Custom {
350 name: "jsonrpc_batch".to_string(),
351 data: json!({
352 "requests": requests,
353 }),
354 })
355 }
356 "disconnect" => Ok(ClientActionResult::Disconnect),
357 "wait_for_more" => Ok(ClientActionResult::WaitForMore),
361 _ => Err(anyhow::anyhow!(
362 "Unknown JSON-RPC client action: {}",
363 action_type
364 )),
365 }
366 }
367}