1use std::io::{BufRead, Write};
20use std::path::PathBuf;
21
22use serde_json::{Value, json};
23
24use crate::render::json_string;
25use crate::{EXIT_FAILURE, EXIT_OK, Rendered, doctor, explain, flows, init, status};
26
27const LATEST_PROTOCOL: &str = "2025-06-18";
30
31const SUPPORTED_PROTOCOLS: [&str; 3] = ["2024-11-05", "2025-03-26", "2025-06-18"];
35
36const INSTRUCTIONS: &str = "Keel adds production-grade resilience (retry, backoff, timeout, breaker, \
38rate limit, cache) and durable flows to this project with zero code changes; policy lives in keel.toml. \
39Every tool's text result is byte-identical to the matching CLI --json output: \
40get_status = `keel status --json`, get_doctor_report = `keel doctor --json`, \
41propose_policy = `keel init --diff --json` (an applyable keel.toml patch — never writes), \
42list_flows = `keel flows --json`, get_trace = `keel trace <flow> --json`, \
43explain_error = `keel explain <code> --json`. Outputs are deterministic \
44(sorted keys, no timestamps), so two calls can be diffed to see real change.";
45
46const PARSE_ERROR: i64 = -32700;
48const INVALID_REQUEST: i64 = -32600;
49const METHOD_NOT_FOUND: i64 = -32601;
50const INVALID_PARAMS: i64 = -32602;
51
52struct RpcError {
55 code: i64,
56 message: String,
57}
58
59fn rpc_error(code: i64, message: impl Into<String>) -> RpcError {
61 RpcError {
62 code,
63 message: message.into(),
64 }
65}
66
67#[derive(Debug)]
71pub struct Server {
72 project: PathBuf,
73 now_ms: fn() -> i64,
74}
75
76impl Server {
77 #[must_use]
79 pub fn new(project: PathBuf, now_ms: fn() -> i64) -> Self {
80 Self { project, now_ms }
81 }
82
83 pub fn serve<R: BufRead, W: Write>(&self, input: R, mut output: W) -> i32 {
87 for line in input.lines() {
88 let Ok(line) = line else {
89 return EXIT_FAILURE;
90 };
91 if line.trim().is_empty() {
92 continue;
93 }
94 let Some(response) = self.handle_line(&line) else {
95 continue;
96 };
97 let Ok(text) = serde_json::to_string(&response) else {
98 return EXIT_FAILURE;
99 };
100 if writeln!(output, "{text}")
101 .and_then(|()| output.flush())
102 .is_err()
103 {
104 return EXIT_FAILURE;
105 }
106 }
107 EXIT_OK
108 }
109
110 fn handle_line(&self, line: &str) -> Option<Value> {
113 let Ok(message) = serde_json::from_str::<Value>(line) else {
114 return Some(error_response(
115 &Value::Null,
116 PARSE_ERROR,
117 "Parse error: the line is not valid JSON. Send one JSON-RPC 2.0 message per line.",
118 ));
119 };
120 self.handle_message(&message)
121 }
122
123 fn handle_message(&self, message: &Value) -> Option<Value> {
125 let Some(frame) = message.as_object() else {
126 return Some(error_response(
127 &Value::Null,
128 INVALID_REQUEST,
129 "Invalid request: expected a JSON-RPC 2.0 object (batches are not supported).",
130 ));
131 };
132 let id = frame.get("id").cloned();
133 let Some(method) = frame.get("method").and_then(Value::as_str) else {
134 return id.map(|id| {
137 error_response(
138 &id,
139 INVALID_REQUEST,
140 "Invalid request: missing `method`. This server accepts initialize, ping, tools/list, and tools/call.",
141 )
142 });
143 };
144 let params = frame.get("params").cloned().unwrap_or(Value::Null);
145 let id = id?;
147 let outcome = match method {
148 "initialize" => Ok(initialize_result(¶ms)),
149 "ping" => Ok(json!({})),
150 "tools/call" => self.tools_call(¶ms),
151 "tools/list" => Ok(json!({ "tools": tool_catalog() })),
152 other => Err(rpc_error(
153 METHOD_NOT_FOUND,
154 format!(
155 "Method not found: {other:?}. This server supports initialize, ping, tools/list, and tools/call."
156 ),
157 )),
158 };
159 Some(match outcome {
160 Ok(result) => json!({ "id": id, "jsonrpc": "2.0", "result": result }),
161 Err(e) => error_response(&id, e.code, &e.message),
162 })
163 }
164
165 fn tools_call(&self, params: &Value) -> Result<Value, RpcError> {
170 let Some(name) = params.get("name").and_then(Value::as_str) else {
171 return Err(rpc_error(
172 INVALID_PARAMS,
173 "tools/call requires a string `name` parameter naming the tool.",
174 ));
175 };
176 let args = params
177 .get("arguments")
178 .cloned()
179 .unwrap_or_else(|| json!({}));
180 let rendered = self.call_tool(name, &args)?;
181 Ok(json!({
182 "content": [ { "text": json_string(&rendered.json), "type": "text" } ],
183 "isError": rendered.exit != EXIT_OK,
184 }))
185 }
186
187 fn call_tool(&self, name: &str, args: &Value) -> Result<Rendered, RpcError> {
191 match name {
192 "explain_error" => Ok(explain::run(require_str(args, "code", name)?)),
193 "get_doctor_report" => Ok(doctor::run(&self.project)),
194 "get_status" => Ok(status::run(&self.project, (self.now_ms)())),
195 "get_trace" => Ok(flows::trace(
196 &self.project,
197 require_str(args, "flow", name)?,
198 )),
199 "list_flows" => Ok(flows::flows(
200 &self.project,
201 optional_bool(args, "dead", name)?,
202 (self.now_ms)(),
203 )),
204 "propose_policy" => Ok(init::run(
205 &self.project,
206 init::InitOptions {
207 diff: true,
208 stamp: false,
209 agents: false,
210 },
211 )),
212 other => Err(rpc_error(
213 INVALID_PARAMS,
214 format!(
215 "Unknown tool: {other:?}. Available tools: explain_error, get_doctor_report, get_status, get_trace, list_flows, propose_policy."
216 ),
217 )),
218 }
219 }
220}
221
222fn initialize_result(params: &Value) -> Value {
225 let requested = params
226 .get("protocolVersion")
227 .and_then(Value::as_str)
228 .unwrap_or(LATEST_PROTOCOL);
229 let version = if SUPPORTED_PROTOCOLS.contains(&requested) {
230 requested
231 } else {
232 LATEST_PROTOCOL
233 };
234 json!({
235 "capabilities": { "tools": {} },
236 "instructions": INSTRUCTIONS,
237 "protocolVersion": version,
238 "serverInfo": { "name": "keel", "version": env!("CARGO_PKG_VERSION") },
239 })
240}
241
242fn tool_catalog() -> Value {
245 json!([
246 {
247 "description": "Explain a KEEL-E0NN error code: what happened, why, and what to do next. Byte-identical to `keel explain <code> --json`.",
248 "inputSchema": {
249 "properties": {
250 "code": { "description": "The error code, e.g. \"KEEL-E014\".", "type": "string" }
251 },
252 "required": ["code"],
253 "type": "object"
254 },
255 "name": "explain_error"
256 },
257 {
258 "description": "The honesty report: what is wrapped, what is visible but unwrapped and why, adapter pins, policy validity, and the journal backend — findings carry applyable fixes where possible. Byte-identical to `keel doctor --json`.",
259 "inputSchema": { "properties": {}, "type": "object" },
260 "name": "get_doctor_report"
261 },
262 {
263 "description": "One screen of what Keel is doing for this project: coverage, calls, retries saved, breaker opens, cache hit rate, and durable-flow counts. Byte-identical to `keel status --json`.",
264 "inputSchema": { "properties": {}, "type": "object" },
265 "name": "get_status"
266 },
267 {
268 "description": "Trace one durable (Tier 2) flow step by step: outcomes, attempts, timings. Byte-identical to `keel trace <flow> --json`.",
269 "inputSchema": {
270 "properties": {
271 "flow": { "description": "A flow_id, or a substring of an id/entrypoint that names exactly one flow.", "type": "string" }
272 },
273 "required": ["flow"],
274 "type": "object"
275 },
276 "name": "get_trace"
277 },
278 {
279 "description": "List durable (Tier 2) flows: id, entrypoint, status, steps done/total. Byte-identical to `keel flows --json`.",
280 "inputSchema": {
281 "properties": {
282 "dead": { "description": "List only dead flows (those that exhausted their resume cap).", "type": "boolean" }
283 },
284 "type": "object"
285 },
286 "name": "list_flows"
287 },
288 {
289 "description": "Propose policy changes as a keel.toml diff from static + observed evidence (never writes): an applyable unified patch plus structured changes. Byte-identical to `keel init --diff --json`.",
290 "inputSchema": { "properties": {}, "type": "object" },
291 "name": "propose_policy"
292 }
293 ])
294}
295
296fn error_response(id: &Value, code: i64, message: &str) -> Value {
298 json!({
299 "error": { "code": code, "message": message },
300 "id": id,
301 "jsonrpc": "2.0",
302 })
303}
304
305fn require_str<'a>(args: &'a Value, key: &str, tool: &str) -> Result<&'a str, RpcError> {
307 args.get(key).and_then(Value::as_str).ok_or_else(|| {
308 rpc_error(
309 INVALID_PARAMS,
310 format!("{tool} requires a string `{key}` argument."),
311 )
312 })
313}
314
315fn optional_bool(args: &Value, key: &str, tool: &str) -> Result<bool, RpcError> {
318 match args.get(key) {
319 None | Some(Value::Null) => Ok(false),
320 Some(Value::Bool(b)) => Ok(*b),
321 Some(_) => Err(rpc_error(
322 INVALID_PARAMS,
323 format!("{tool}'s `{key}` argument must be a boolean."),
324 )),
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 const T0: i64 = 1_783_728_000_000;
333
334 fn t0() -> i64 {
335 T0
336 }
337
338 fn server_in(dir: &std::path::Path) -> Server {
339 Server::new(dir.to_path_buf(), t0)
340 }
341
342 fn empty_project() -> tempfile::TempDir {
343 tempfile::TempDir::new().unwrap()
344 }
345
346 fn respond(server: &Server, line: &str) -> Value {
348 server.handle_line(line).expect("a response is due")
349 }
350
351 #[test]
352 fn initialize_echoes_a_supported_version_and_names_the_server() {
353 let dir = empty_project();
354 let r = respond(
355 &server_in(dir.path()),
356 r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}"#,
357 );
358 assert_eq!(r["id"], 1);
359 assert_eq!(r["result"]["protocolVersion"], "2025-03-26");
360 assert_eq!(r["result"]["serverInfo"]["name"], "keel");
361 assert_eq!(
362 r["result"]["serverInfo"]["version"],
363 env!("CARGO_PKG_VERSION")
364 );
365 assert!(r["result"]["capabilities"]["tools"].is_object());
366 assert!(
367 r["result"]["instructions"]
368 .as_str()
369 .unwrap()
370 .contains("byte-identical")
371 );
372 }
373
374 #[test]
375 fn initialize_with_an_unknown_version_offers_the_latest_supported() {
376 let dir = empty_project();
377 let r = respond(
378 &server_in(dir.path()),
379 r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2099-01-01"}}"#,
380 );
381 assert_eq!(r["result"]["protocolVersion"], LATEST_PROTOCOL);
382 }
383
384 #[test]
385 fn notifications_get_no_response() {
386 let dir = empty_project();
387 let s = server_in(dir.path());
388 assert!(
389 s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
390 .is_none()
391 );
392 assert!(
394 s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/whatever"}"#)
395 .is_none()
396 );
397 }
398
399 #[test]
400 fn parse_error_answers_with_null_id() {
401 let dir = empty_project();
402 let r = respond(&server_in(dir.path()), "{not json");
403 assert_eq!(r["error"]["code"], PARSE_ERROR);
404 assert!(r["id"].is_null());
405 }
406
407 #[test]
408 fn non_object_frames_are_invalid_requests() {
409 let dir = empty_project();
410 let r = respond(&server_in(dir.path()), "[1,2,3]");
411 assert_eq!(r["error"]["code"], INVALID_REQUEST);
412 }
413
414 #[test]
415 fn unknown_method_is_method_not_found() {
416 let dir = empty_project();
417 let r = respond(
418 &server_in(dir.path()),
419 r#"{"jsonrpc":"2.0","id":7,"method":"resources/list"}"#,
420 );
421 assert_eq!(r["error"]["code"], METHOD_NOT_FOUND);
422 assert_eq!(r["id"], 7);
423 }
424
425 #[test]
426 fn ping_answers_an_empty_object() {
427 let dir = empty_project();
428 let r = respond(
429 &server_in(dir.path()),
430 r#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#,
431 );
432 assert_eq!(r["result"], json!({}));
433 }
434
435 #[test]
436 fn tools_list_is_the_six_spec_tools_alphabetically() {
437 let dir = empty_project();
438 let r = respond(
439 &server_in(dir.path()),
440 r#"{"jsonrpc":"2.0","id":3,"method":"tools/list"}"#,
441 );
442 let names: Vec<&str> = r["result"]["tools"]
443 .as_array()
444 .unwrap()
445 .iter()
446 .map(|t| t["name"].as_str().unwrap())
447 .collect();
448 assert_eq!(
449 names,
450 [
451 "explain_error",
452 "get_doctor_report",
453 "get_status",
454 "get_trace",
455 "list_flows",
456 "propose_policy",
457 ]
458 );
459 for tool in r["result"]["tools"].as_array().unwrap() {
461 assert_eq!(tool["inputSchema"]["type"], "object");
462 assert!(tool["description"].as_str().unwrap().contains("--json"));
463 }
464 }
465
466 #[test]
467 fn unknown_tool_is_invalid_params() {
468 let dir = empty_project();
469 let r = respond(
470 &server_in(dir.path()),
471 r#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"get_everything"}}"#,
472 );
473 assert_eq!(r["error"]["code"], INVALID_PARAMS);
474 assert!(
475 r["error"]["message"]
476 .as_str()
477 .unwrap()
478 .contains("Available tools")
479 );
480 }
481
482 #[test]
483 fn missing_required_argument_is_invalid_params() {
484 let dir = empty_project();
485 let s = server_in(dir.path());
486 let r = respond(
487 &s,
488 r#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"get_trace"}}"#,
489 );
490 assert_eq!(r["error"]["code"], INVALID_PARAMS);
491 assert!(r["error"]["message"].as_str().unwrap().contains("`flow`"));
492 let r = respond(
493 &s,
494 r#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"explain_error","arguments":{}}}"#,
495 );
496 assert_eq!(r["error"]["code"], INVALID_PARAMS);
497 assert!(r["error"]["message"].as_str().unwrap().contains("`code`"));
498 }
499
500 #[test]
501 fn mistyped_dead_argument_is_invalid_params_not_coerced() {
502 let dir = empty_project();
503 let r = respond(
504 &server_in(dir.path()),
505 r#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"list_flows","arguments":{"dead":"yes"}}}"#,
506 );
507 assert_eq!(r["error"]["code"], INVALID_PARAMS);
508 assert!(r["error"]["message"].as_str().unwrap().contains("boolean"));
509 }
510
511 #[test]
512 fn explain_error_text_is_byte_identical_to_the_json_twin() {
513 let dir = empty_project();
514 let r = respond(
515 &server_in(dir.path()),
516 r#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"explain_error","arguments":{"code":"KEEL-E014"}}}"#,
517 );
518 assert_eq!(r["result"]["isError"], false);
519 assert_eq!(
520 r["result"]["content"][0]["text"].as_str().unwrap(),
521 json_string(&explain::run("KEEL-E014").json)
522 );
523 assert_eq!(r["result"]["content"][0]["type"], "text");
524 }
525
526 #[test]
527 fn a_failing_tool_is_a_result_with_is_error_not_a_protocol_error() {
528 let dir = empty_project();
529 let r = respond(
530 &server_in(dir.path()),
531 r#"{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"explain_error","arguments":{"code":"KEEL-E999"}}}"#,
532 );
533 assert!(r.get("error").is_none(), "tool failures are not RPC errors");
534 assert_eq!(r["result"]["isError"], true);
535 assert_eq!(
536 r["result"]["content"][0]["text"].as_str().unwrap(),
537 json_string(&explain::run("KEEL-E999").json)
538 );
539 }
540
541 #[test]
542 fn list_flows_defaults_dead_to_false_and_accepts_true() {
543 let dir = empty_project();
544 let s = server_in(dir.path());
545 let r = respond(
546 &s,
547 r#"{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"list_flows"}}"#,
548 );
549 let text = r["result"]["content"][0]["text"].as_str().unwrap();
550 assert_eq!(text, json_string(&flows::flows(dir.path(), false, T0).json));
551 let r = respond(
552 &s,
553 r#"{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"list_flows","arguments":{"dead":true}}}"#,
554 );
555 let text = r["result"]["content"][0]["text"].as_str().unwrap();
556 assert_eq!(text, json_string(&flows::flows(dir.path(), true, T0).json));
557 }
558
559 #[test]
560 fn serve_skips_blank_lines_and_exits_ok_on_eof() {
561 let dir = empty_project();
562 let script = "\n\
563 {\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n\
564 \n\
565 {\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n";
566 let mut out = Vec::new();
567 let code = server_in(dir.path()).serve(std::io::Cursor::new(script), &mut out);
568 assert_eq!(code, EXIT_OK);
569 let lines: Vec<&str> = std::str::from_utf8(&out).unwrap().lines().collect();
570 assert_eq!(lines.len(), 1, "one request → one response line");
571 let v: Value = serde_json::from_str(lines[0]).unwrap();
572 assert_eq!(v["id"], 1);
573 }
574}