lean_ctx_server/engine/
mod.rs1use std::path::PathBuf;
3use std::sync::atomic::{AtomicI64, Ordering};
4
5use anyhow::{Context, Result, anyhow};
6use rmcp::{
7 model::{
8 CallToolRequest, CallToolRequestParams, CallToolResult, ClientJsonRpcMessage,
9 ClientRequest, JsonRpcRequest, NumberOrString, ServerJsonRpcMessage, ServerResult,
10 },
11 service::RoleServer,
12 service::serve_directly,
13 transport::OneshotTransport,
14};
15use serde_json::{Map, Value};
16
17use crate::tools::LeanCtxServer;
18
19pub struct ContextEngine {
20 server: LeanCtxServer,
21 next_id: AtomicI64,
22}
23
24impl ContextEngine {
25 pub fn new() -> Self {
26 Self {
27 server: LeanCtxServer::new(),
28 next_id: AtomicI64::new(1),
29 }
30 }
31
32 pub fn with_project_root(project_root: impl Into<PathBuf>) -> Self {
33 let root = project_root.into().to_string_lossy().to_string();
34 Self {
35 server: LeanCtxServer::new_with_project_root(Some(&root)),
36 next_id: AtomicI64::new(1),
37 }
38 }
39
40 pub fn from_server(server: LeanCtxServer) -> Self {
41 Self {
42 server,
43 next_id: AtomicI64::new(1),
44 }
45 }
46
47 pub fn server(&self) -> &LeanCtxServer {
48 &self.server
49 }
50
51 pub fn manifest(&self) -> Value {
52 lean_ctx::core::mcp_manifest::manifest_value()
53 }
54
55 pub async fn call_tool_value(&self, name: &str, arguments: Option<Value>) -> Result<Value> {
56 let result = self.call_tool_result(name, arguments).await?;
57 serde_json::to_value(result).map_err(|e| anyhow!("serialize CallToolResult: {e}"))
58 }
59
60 pub async fn call_tool_result(
61 &self,
62 name: &str,
63 arguments: Option<Value>,
64 ) -> Result<CallToolResult> {
65 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
66 let req_id = NumberOrString::Number(id);
67
68 let args_obj: Map<String, Value> = match arguments {
69 None => Map::new(),
70 Some(Value::Object(m)) => m,
71 Some(other) => {
72 return Err(anyhow!(
73 "tool arguments must be a JSON object (got {other})"
74 ));
75 }
76 };
77
78 let params = CallToolRequestParams::new(name.to_string()).with_arguments(args_obj);
79 let call: CallToolRequest = CallToolRequest::new(params);
80 let client_req = ClientRequest::CallToolRequest(call);
81 let msg = ClientJsonRpcMessage::Request(JsonRpcRequest::new(req_id, client_req));
82
83 let (transport, mut rx) = OneshotTransport::<RoleServer>::new(msg);
84 let service = serve_directly(self.server.clone(), transport, None);
85 tokio::spawn(async move {
86 let _ = service.waiting().await;
87 });
88 let deadline = tokio::time::Instant::now() + std::time::Duration::from_mins(2);
89 loop {
90 let server_msg = match tokio::time::timeout_at(deadline, rx.recv()).await {
91 Ok(Some(msg)) => msg,
92 Ok(None) => return Err(anyhow!("no response from tool call")),
93 Err(_) => return Err(anyhow!("tool call timed out after 120s")),
94 };
95
96 match server_msg {
97 ServerJsonRpcMessage::Notification(_) => {}
98 ServerJsonRpcMessage::Response(r) => {
99 return match r.result {
100 ServerResult::CallToolResult(result) => Ok(result),
101 other => Err(anyhow!("unexpected server result: {other:?}")),
102 };
103 }
104 ServerJsonRpcMessage::Error(e) => {
105 return Err(anyhow!("{e:?}")).context("tool call error");
106 }
107 ServerJsonRpcMessage::Request(_) => {
108 return Err(anyhow!("unexpected request"));
109 }
110 }
111 }
112 }
113
114 pub async fn call_tool_text(&self, name: &str, arguments: Option<Value>) -> Result<String> {
115 let result = self.call_tool_result(name, arguments).await?;
116 let mut out = String::new();
117 for c in result.content {
118 if let Some(t) = c.as_text() {
119 out.push_str(&t.text);
120 }
121 }
122 if out.is_empty()
123 && let Some(v) = result.structured_content
124 {
125 out = v.to_string();
126 }
127 Ok(out)
128 }
129}
130
131impl Default for ContextEngine {
132 fn default() -> Self {
133 Self::new()
134 }
135}
136
137pub mod operators;
139
140#[cfg(test)]
141mod canary_sweep_tests;
142#[cfg(test)]
143mod transport_tests;