1use crate::json::{obj, Json};
9use crate::types::{
10 cap_for_method, negotiate_version, Capability, Errc, Method, RcpError, MIN_PROTOCOL_VERSION,
11 PROTOCOL_VERSION,
12};
13use std::collections::HashMap;
14use std::io::{BufRead, BufReader, Read, Write};
15use std::net::{TcpListener, TcpStream};
16
17type Handler = Box<dyn FnMut(&Json) -> Result<Json, RcpError>>;
18
19pub struct Server {
21 info: Json,
22 caps: Json,
23 handlers: HashMap<String, Handler>,
24 initialized: bool,
25 negotiated: i64,
27}
28
29impl Default for Server {
30 fn default() -> Server {
31 Server::new()
32 }
33}
34
35const POSITIVE_INT_FIELDS: &[&str] =
40 &["k", "topN", "candidateK", "n", "hops", "tokenBudget", "limit"];
41
42fn validate_params(params: &Json) -> Option<RcpError> {
46 if params.as_object().is_none() {
47 return Some(RcpError::new(Errc::INVALID_PARAMS, "'params' MUST be an object"));
48 }
49 let int_of = |v: &Json| -> Option<i64> {
50 if v.as_bool().is_some() {
51 return None; }
53 let n = v.as_f64()?;
54 if n.fract() == 0.0 { Some(n as i64) } else { None }
55 };
56
57 for field in POSITIVE_INT_FIELDS {
58 let Some(v) = params.get(*field) else { continue };
59 match int_of(v) {
60 None => {
61 return Some(RcpError::with_data(
62 Errc::INVALID_PARAMS,
63 format!("'{field}' MUST be an integer"),
64 obj(&[("field", Json::from(*field))]),
65 ))
66 }
67 Some(n) if n < 1 => {
68 return Some(RcpError::with_data(
69 Errc::INVALID_PARAMS,
70 format!("'{field}' MUST be >= 1"),
71 obj(&[("field", Json::from(*field))]),
72 ))
73 }
74 Some(_) => {}
75 }
76 }
77
78 let k = params.get("k").and_then(int_of);
80 let cand = params.get("candidateK").and_then(int_of);
81 let top_n = params.get("rerank").and_then(|r| r.get("topN")).and_then(int_of);
82 let viol = |field: &str, msg: &str| {
83 Some(RcpError::with_data(
84 Errc::INVALID_PARAMS,
85 msg.to_string(),
86 obj(&[("field", Json::from(field))]),
87 ))
88 };
89 if let (Some(k), Some(c)) = (k, cand) {
90 if c < k {
91 return viol("candidateK", "'candidateK' MUST be >= 'k' (funnel invariant)");
92 }
93 }
94 if let (Some(k), Some(t)) = (k, top_n) {
95 if t < k {
96 return viol("rerank.topN", "'rerank.topN' MUST be >= 'k' (funnel invariant)");
97 }
98 }
99 if let (Some(c), Some(t)) = (cand, top_n) {
100 if c < t {
101 return viol(
102 "candidateK",
103 "'candidateK' MUST be >= 'rerank.topN' (funnel invariant)",
104 );
105 }
106 }
107 None
108}
109
110impl Server {
111 pub fn new() -> Server {
112 Server {
113 info: obj(&[("name", "unknown".into()), ("version", "0".into())]),
114 caps: Json::object(),
115 handlers: HashMap::new(),
116 initialized: false,
117 negotiated: PROTOCOL_VERSION,
118 }
119 }
120
121 pub fn set_info(&mut self, name: &str, version: &str) -> &mut Self {
123 self.info = obj(&[("name", name.into()), ("version", version.into())]);
124 self
125 }
126
127 pub fn advertise(&mut self, cap: Capability, meta: Json) -> &mut Self {
131 self.caps.insert(cap.wire_key(), meta);
132 self
133 }
134
135 pub fn on<F>(&mut self, method: &str, handler: F) -> &mut Self
137 where
138 F: FnMut(&Json) -> Result<Json, RcpError> + 'static,
139 {
140 self.handlers.insert(method.to_string(), Box::new(handler));
141 self
142 }
143
144 pub fn handle(&mut self, request: &Json) -> Option<Json> {
148 let id = request.get("id").cloned().unwrap_or(Json::Null);
149 let method = match request.get("method").and_then(|m| m.as_str()) {
150 Some(m) => m.to_string(),
151 None => return Some(err(&id, Errc::INVALID_REQUEST, "missing 'method'")),
152 };
153 let params = request.get("params").cloned().unwrap_or_else(Json::object);
154
155 if request.get("id").is_none() {
160 return None;
161 }
162
163 match method.as_str() {
164 Method::INITIALIZE => {
165 if self.initialized {
170 return Some(err(
171 &id,
172 Errc::INVALID_REQUEST,
173 "already initialized; re-negotiation is not permitted mid-session",
174 ));
175 }
176 let peer = params
177 .get("protocolVersion")
178 .and_then(|v| v.as_i64())
179 .unwrap_or(PROTOCOL_VERSION);
180 let neg = negotiate_version(peer);
181 if neg < MIN_PROTOCOL_VERSION {
182 return Some(err(&id, Errc::VERSION_MISMATCH, "no common version"));
183 }
184 self.initialized = true;
188 self.negotiated = neg;
189 Some(ok(&id, self.info_result(neg)))
190 }
191 Method::INFO => Some(ok(&id, self.info_result(PROTOCOL_VERSION))),
192 Method::PING => {
193 let result = match params.get("nonce") {
194 Some(n) => obj(&[("nonce", n.clone())]),
195 None => Json::object(),
196 };
197 Some(ok(&id, result))
198 }
199 Method::CANCEL => Some(err(
202 &id,
203 Errc::INVALID_REQUEST,
204 "'notifications/cancel' is a notification and MUST NOT carry an 'id'",
205 )),
206 Method::SHUTDOWN => Some(ok(&id, Json::object())),
210 _ => {
211 if !self.initialized {
212 return Some(err(&id, Errc::NOT_INITIALIZED, "call 'initialize' first"));
213 }
214 Some(self.dispatch(&id, &method, ¶ms))
215 }
216 }
217 }
218
219 fn dispatch(&mut self, id: &Json, method: &str, params: &Json) -> Json {
220 let cap = match cap_for_method(method) {
221 Some(c) => c,
222 None => return err(id, Errc::UNKNOWN_METHOD, &format!("unknown method '{}'", method)),
223 };
224 let advertised = self.caps.get(cap.wire_key()).is_some_and(|v| !v.is_null());
225 if !self.handlers.contains_key(method) {
226 return err(id, Errc::CAPABILITY_MISSING, &format!("'{}' not implemented", method));
227 }
228 if !advertised {
229 return err(
230 id,
231 Errc::CAPABILITY_MISSING,
232 &format!("capability '{}' not supported", cap.wire_key()),
233 );
234 }
235 if let Some(e) = validate_params(params) {
238 return err_data(id, e.code, &e.message, e.data);
239 }
240 let handler = self.handlers.get_mut(method).expect("handler present");
241 match handler(params) {
242 Ok(result) => ok(id, result),
243 Err(e) => err_data(id, e.code, &e.message, e.data),
244 }
245 }
246
247 pub fn handle_line(&mut self, line: &str) -> String {
250 let msg = match Json::parse(line) {
251 Ok(m) => m,
252 Err(e) => return err(&Json::Null, Errc::PARSE_ERROR, &e).dump(),
253 };
254 if let Json::Array(items) = &msg {
255 if items.is_empty() {
256 return err(&Json::Null, Errc::INVALID_REQUEST, "empty batch").dump();
257 }
258 let mut out = Vec::new();
259 for item in items {
260 if let Some(reply) = self.handle(item) {
261 out.push(reply);
262 }
263 }
264 return if out.is_empty() {
265 String::new()
266 } else {
267 Json::Array(out).dump()
268 };
269 }
270 match self.handle(&msg) {
271 Some(reply) => reply.dump(),
272 None => String::new(),
273 }
274 }
275
276 fn info_result(&self, version: i64) -> Json {
277 obj(&[
278 ("protocolVersion", version.into()),
279 ("server", self.info.clone()),
280 ("capabilities", self.caps.clone()),
281 ])
282 }
283
284 pub fn serve_stdio(&mut self) {
287 let stdin = std::io::stdin();
288 let mut reader = stdin.lock();
289 let stdout = std::io::stdout();
290 let mut out = stdout.lock();
291 let mut line = String::new();
292 loop {
293 line.clear();
294 match reader.read_line(&mut line) {
295 Ok(0) | Err(_) => break, Ok(_) => {}
297 }
298 let trimmed = line.trim();
299 if trimmed.is_empty() {
300 continue;
301 }
302 let is_shutdown = Json::parse(trimmed)
303 .ok()
304 .and_then(|m| m.get("method").and_then(|x| x.as_str()).map(|s| s == Method::SHUTDOWN))
305 .unwrap_or(false);
306 let reply = self.handle_line(trimmed);
307 if !reply.is_empty()
308 && out
309 .write_all(reply.as_bytes())
310 .and_then(|_| out.write_all(b"\n"))
311 .and_then(|_| out.flush())
312 .is_err()
313 {
314 break; }
316 if is_shutdown {
317 break;
318 }
319 }
320 }
321
322 pub fn serve_http(&mut self, port: u16) -> Result<(), RcpError> {
325 let listener = TcpListener::bind(("127.0.0.1", port))
326 .map_err(|e| RcpError::new(Errc::BACKEND_UNAVAILABLE, format!("bind failed: {}", e)))?;
327 for stream in listener.incoming() {
328 match stream {
329 Ok(mut s) => {
330 let _ = self.serve_http_conn(&mut s);
331 }
332 Err(_) => continue,
333 }
334 }
335 Ok(())
336 }
337
338 fn serve_http_conn(&mut self, stream: &mut TcpStream) -> std::io::Result<()> {
339 let mut reader = BufReader::new(stream.try_clone()?);
340 let mut content_length = 0usize;
341 loop {
342 let mut header = String::new();
343 let n = reader.read_line(&mut header)?;
344 if n == 0 {
345 return Ok(());
346 }
347 if header == "\r\n" || header == "\n" {
348 break; }
350 let lower = header.to_ascii_lowercase();
351 if let Some(rest) = lower.strip_prefix("content-length:") {
352 content_length = rest.trim().parse().unwrap_or(0);
353 }
354 }
355 let mut body = vec![0u8; content_length];
356 reader.read_exact(&mut body)?;
357 let text = String::from_utf8_lossy(&body);
358 let text = if text.trim().is_empty() { "{}" } else { text.trim() };
359 let reply = self.handle_line(text);
360 let response = if reply.is_empty() {
361 "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n".to_string()
362 } else {
363 format!(
364 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
365 Content-Length: {}\r\nConnection: close\r\n\r\n{}",
366 reply.len(),
367 reply
368 )
369 };
370 stream.write_all(response.as_bytes())?;
371 stream.flush()
372 }
373}
374
375pub fn make_log_notification(level: &str, message: &str, data: Option<Json>) -> String {
378 let mut params = obj(&[("level", level.into()), ("message", message.into())]);
379 if let Some(d) = data {
380 params.insert("data", d);
381 }
382 obj(&[
383 ("jsonrpc", "2.0".into()),
384 ("method", Method::LOG.into()),
385 ("params", params),
386 ])
387 .dump()
388}
389
390pub fn make_progress_notification(
392 token: Json,
393 progress: f64,
394 stage: Option<&str>,
395 partial: Option<Json>,
396) -> String {
397 let mut params = obj(&[("progressToken", token), ("progress", progress.into())]);
398 if let Some(s) = stage {
399 if !s.is_empty() {
400 params.insert("stage", s);
401 }
402 }
403 if let Some(p) = partial {
404 params.insert("partial", p);
405 }
406 obj(&[
407 ("jsonrpc", "2.0".into()),
408 ("method", Method::PROGRESS.into()),
409 ("params", params),
410 ])
411 .dump()
412}
413
414fn ok(id: &Json, result: Json) -> Json {
416 obj(&[
417 ("jsonrpc", "2.0".into()),
418 ("id", id.clone()),
419 ("result", result),
420 ])
421}
422
423fn err(id: &Json, code: i64, message: &str) -> Json {
424 err_data(id, code, message, None)
425}
426
427fn err_data(id: &Json, code: i64, message: &str, data: Option<Json>) -> Json {
428 let mut error = obj(&[("code", code.into()), ("message", message.into())]);
429 if let Some(d) = data {
430 error.insert("data", d);
431 }
432 obj(&[
433 ("jsonrpc", "2.0".into()),
434 ("id", id.clone()),
435 ("error", error),
436 ])
437}