Skip to main content

rcp/
client.rs

1//! client.rs — connect to any RCP server (subprocess or HTTP), then typed calls.
2//!
3//! Mirrors the C++/Python/Node `Client`: connecting performs the `initialize`
4//! handshake and caches the negotiated protocol version, server identity, and
5//! capabilities. Every typed call is **capability-gated** — a call to a feature
6//! the server never advertised returns `Err(CapabilityMissing)` before any
7//! round-trip. Synchronous and blocking; every call returns `Result<_, RcpError>`.
8
9use crate::json::{obj, Json};
10use crate::transport::{HttpTransport, StdioTransport, Transport};
11use crate::types::{
12    Capability, Errc, Method, RcpError, MIN_PROTOCOL_VERSION, PROTOCOL_VERSION,
13};
14
15/// One retrieval hit. `id`/`score`/`text` are always present (id coerced to a
16/// string); every optional spec §7.7 field is surfaced when the server sent it —
17/// `confidence` (normalised [0,1]), `unit`/`level` (granularity & abstraction),
18/// `provenance` (graph/tree lineage), `trust` (provenance + safety), and
19/// per-stage `scores`. `raw` is the untouched JSON object for anything else.
20#[derive(Clone, Debug)]
21pub struct Hit {
22    pub id: String,
23    pub score: f64,
24    pub text: String,
25    pub citation: Option<Json>,
26    pub confidence: Option<f64>,
27    pub unit: Option<String>,
28    pub level: Option<i64>,
29    pub modality: Option<String>,
30    pub scores: Option<Json>,
31    pub provenance: Option<Json>,
32    pub trust: Option<Json>,
33    pub raw: Json,
34}
35
36/// The full result of `search`: hits plus telemetry and an optional page cursor.
37#[derive(Clone, Debug)]
38pub struct SearchResult {
39    pub hits: Vec<Hit>,
40    pub usage: Json,
41    pub next_cursor: Option<String>,
42}
43
44fn hit_from_json(h: &Json) -> Hit {
45    let id = match h.get("id") {
46        Some(Json::Str(s)) => s.clone(),
47        Some(other) => other.dump(),
48        None => String::new(),
49    };
50    let opt = |k: &str| h.get(k).filter(|v| !v.is_null()).cloned();
51    Hit {
52        id,
53        score: h.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0),
54        text: h.get("text").and_then(|v| v.as_str()).unwrap_or("").to_string(),
55        citation: opt("citation"),
56        confidence: h.get("confidence").and_then(|v| v.as_f64()),
57        unit: h.get("unit").and_then(|v| v.as_str()).map(str::to_string),
58        level: h.get("level").and_then(|v| v.as_i64()),
59        modality: h.get("modality").and_then(|v| v.as_str()).map(str::to_string),
60        scores: opt("scores"),
61        provenance: opt("provenance"),
62        trust: opt("trust"),
63        raw: h.clone(),
64    }
65}
66
67/// A connected RCP client.
68pub struct Client {
69    transport: Box<dyn Transport>,
70    next_id: i64,
71    protocol_version: i64,
72    server: Json,
73    caps: Json,
74}
75
76impl Client {
77    // ── connection ──────────────────────────────────────────────────────────
78    /// Spawn an RCP server subprocess and connect. `argv` e.g. `["python3", "srv.py"]`.
79    pub fn connect_stdio<S: AsRef<str>>(argv: &[S]) -> Result<Client, RcpError> {
80        let argv: Vec<String> = argv.iter().map(|s| s.as_ref().to_string()).collect();
81        let t = StdioTransport::spawn(&argv)?;
82        Client::from_transport(Box::new(t))
83    }
84
85    /// Connect to an HTTP RCP server, e.g. `"http://127.0.0.1:8000/rcp"`.
86    pub fn connect_http(base_url: &str) -> Result<Client, RcpError> {
87        Client::from_transport(Box::new(HttpTransport::new(base_url)))
88    }
89
90    fn from_transport(transport: Box<dyn Transport>) -> Result<Client, RcpError> {
91        let mut c = Client {
92            transport,
93            next_id: 0,
94            protocol_version: PROTOCOL_VERSION,
95            server: Json::object(),
96            caps: Json::object(),
97        };
98        let params = obj(&[
99            ("protocolVersion", PROTOCOL_VERSION.into()),
100            (
101                "client",
102                obj(&[("name", "rcp-rust".into()), ("version", "1.0".into())]),
103            ),
104            ("capabilities", Json::object()),
105        ]);
106        let res = c.request(Method::INITIALIZE, params)?;
107        let pv = res
108            .get("protocolVersion")
109            .and_then(|v| v.as_i64())
110            .unwrap_or(PROTOCOL_VERSION);
111        if pv < MIN_PROTOCOL_VERSION {
112            return Err(RcpError::new(
113                Errc::VERSION_MISMATCH,
114                "server offered no usable protocol version",
115            ));
116        }
117        c.protocol_version = pv;
118        c.server = res.get("server").cloned().unwrap_or_else(Json::object);
119        c.caps = res.get("capabilities").cloned().unwrap_or_else(Json::object);
120        Ok(c)
121    }
122
123    // ── introspection ───────────────────────────────────────────────────────
124    pub fn protocol_version(&self) -> i64 {
125        self.protocol_version
126    }
127    pub fn server(&self) -> &Json {
128        &self.server
129    }
130    pub fn capabilities(&self) -> &Json {
131        &self.caps
132    }
133    pub fn supports(&self, cap: Capability) -> bool {
134        matches!(self.caps.get(cap.wire_key()), Some(v) if !v.is_null())
135    }
136
137    // ── typed, capability-gated calls ───────────────────────────────────────
138    /// Dense embeddings → one `Vec<f64>` per input. `kind` selects asymmetric pooling.
139    pub fn embed(&mut self, texts: &[&str], kind: Option<&str>) -> Result<Vec<Vec<f64>>, RcpError> {
140        self.gate(Capability::Embed)?;
141        let inputs: Vec<Json> = texts.iter().map(|t| Json::from(*t)).collect();
142        let mut params = obj(&[("inputs", Json::Array(inputs))]);
143        if let Some(k) = kind {
144            params.insert("kind", k);
145        }
146        let r = self.request(Method::EMBED, params)?;
147        let vectors = r.get("vectors").and_then(|v| v.as_array()).cloned().unwrap_or_default();
148        Ok(vectors
149            .iter()
150            .map(|row| {
151                row.as_array()
152                    .map(|a| a.iter().filter_map(|x| x.as_f64()).collect())
153                    .unwrap_or_default()
154            })
155            .collect())
156    }
157
158    /// Learned-sparse (SPLADE) terms → raw result `{ sparse: [...] }`.
159    pub fn embed_sparse(&mut self, texts: &[&str]) -> Result<Json, RcpError> {
160        self.gate(Capability::SparseEmbed)?;
161        let inputs: Vec<Json> = texts.iter().map(|t| Json::from(*t)).collect();
162        self.request(Method::EMBED_SPARSE, obj(&[("inputs", Json::Array(inputs))]))
163    }
164
165    /// Per-token multi-vector (ColBERT/ColPali) → `{ matrices, dimension }`.
166    pub fn embed_multi(&mut self, inputs: Vec<Json>) -> Result<Json, RcpError> {
167        self.gate(Capability::MultiVector)?;
168        self.request(Method::EMBED_MULTI, obj(&[("inputs", Json::Array(inputs))]))
169    }
170
171    /// Cross-encoder rerank → one score per passage.
172    pub fn rerank(&mut self, query: &str, passages: &[&str]) -> Result<Vec<f64>, RcpError> {
173        self.gate(Capability::Rerank)?;
174        let ps: Vec<Json> = passages.iter().map(|p| Json::from(*p)).collect();
175        let params = obj(&[("query", query.into()), ("passages", Json::Array(ps))]);
176        let r = self.request(Method::RERANK, params)?;
177        let scores = r.get("scores").and_then(|v| v.as_array()).cloned().unwrap_or_default();
178        Ok(scores.iter().filter_map(|x| x.as_f64()).collect())
179    }
180
181    /// Full retrieve → hits, usage, and an optional page cursor (spec §7.6).
182    pub fn search(&mut self, query: &str, k: i64, opts: Option<Json>) -> Result<SearchResult, RcpError> {
183        self.gate(Capability::Retrieve)?;
184        if k < 1 {
185            return Err(RcpError::new(Errc::INVALID_PARAMS, "value must be >= 1"));
186        }
187        let mut params = opts.unwrap_or_else(Json::object);
188        params.insert("query", query);
189        params.insert("k", k);
190        let r = self.request(Method::RETRIEVE, params)?;
191        let hits = r
192            .get("hits")
193            .and_then(|v| v.as_array())
194            .map(|a| a.iter().map(hit_from_json).collect())
195            .unwrap_or_default();
196        Ok(SearchResult {
197            hits,
198            usage: r.get("usage").cloned().unwrap_or_else(Json::object),
199            next_cursor: r.get("nextCursor").and_then(|v| v.as_str()).map(str::to_string),
200        })
201    }
202
203    /// Convenience over `search` → just the hits.
204    pub fn retrieve(&mut self, query: &str, k: i64) -> Result<Vec<Hit>, RcpError> {
205        Ok(self.search(query, k, None)?.hits)
206    }
207
208    /// GraphRAG op ("local"|"global"|…) → raw result (spec §7.9).
209    pub fn graph(&mut self, op: &str, params: Option<Json>) -> Result<Json, RcpError> {
210        self.gate(Capability::Graph)?;
211        let mut p = params.unwrap_or_else(Json::object);
212        p.insert("op", op);
213        self.request(Method::GRAPH, p)
214    }
215
216    /// Query transform (HyDE, expansion, …) → raw result (spec §7.8).
217    pub fn transform(&mut self, query: &str, method: &str) -> Result<Json, RcpError> {
218        self.gate(Capability::Transform)?;
219        self.request(Method::TRANSFORM, obj(&[("query", query.into()), ("method", method.into())]))
220    }
221
222    /// Add documents to the corpus (spec §7.10).
223    pub fn index_add(&mut self, params: Json) -> Result<Json, RcpError> {
224        self.gate(Capability::Index)?;
225        self.request(Method::INDEX_ADD, params)
226    }
227
228    /// Delete documents by id or filter (spec §7.11).
229    pub fn index_delete(&mut self, params: Json) -> Result<Json, RcpError> {
230        self.gate(Capability::Index)?;
231        self.request(Method::INDEX_DELETE, params)
232    }
233
234    /// List downstream engines of an aggregator (spec §7.12).
235    pub fn catalog(&mut self) -> Result<Json, RcpError> {
236        self.gate(Capability::Catalog)?;
237        self.request(Method::CATALOG_LIST, Json::object())
238    }
239
240    /// Send client→server relevance/reward/integrity signals (spec §7.16). Each
241    /// signal REQUIRES `hitId`. Returns `{ accepted }`; side-effect only.
242    pub fn feedback(&mut self, signals: Vec<Json>, opts: Option<Json>) -> Result<Json, RcpError> {
243        self.gate(Capability::Feedback)?;
244        for s in &signals {
245            if s.get("hitId").filter(|v| !v.is_null()).is_none() {
246                return Err(RcpError::new(
247                    Errc::INVALID_PARAMS,
248                    "each feedback signal requires 'hitId'",
249                ));
250            }
251        }
252        let mut p = opts.unwrap_or_else(Json::object);
253        p.insert("signals", Json::Array(signals));
254        self.request(Method::FEEDBACK, p)
255    }
256
257    /// Build or update a global/session memory (spec §7.17) → `{ memoryId, tokens? }`.
258    pub fn memory_build(&mut self, params: Option<Json>) -> Result<Json, RcpError> {
259        self.gate(Capability::Memory)?;
260        self.request(Method::MEMORY_BUILD, params.unwrap_or_else(Json::object))
261    }
262
263    /// Recall clues / entry-points from a memory (spec §7.17) → `{ clues, hits? }`.
264    pub fn memory_recall(&mut self, query: &str, opts: Option<Json>) -> Result<Json, RcpError> {
265        self.gate(Capability::Memory)?;
266        if let Some(n) = opts.as_ref().and_then(|o| o.get("n")).and_then(|v| v.as_i64()) {
267            if n < 1 {
268                return Err(RcpError::new(Errc::INVALID_PARAMS, "value must be >= 1"));
269            }
270        }
271        let mut p = opts.unwrap_or_else(Json::object);
272        p.insert("query", query);
273        self.request(Method::MEMORY_RECALL, p)
274    }
275
276    /// Re-fetch identity + capabilities without re-initialising.
277    pub fn info(&mut self) -> Result<Json, RcpError> {
278        let r = self.request(Method::INFO, Json::object())?;
279        self.server = r.get("server").cloned().unwrap_or_else(Json::object);
280        self.caps = r.get("capabilities").cloned().unwrap_or_else(Json::object);
281        Ok(r)
282    }
283
284    /// Escape hatch: invoke an arbitrary method with raw params.
285    pub fn call(&mut self, method: &str, params: Json) -> Result<Json, RcpError> {
286        self.request(method, params)
287    }
288
289    /// Liveness check; echoes `{ nonce }` when a nonce is given (spec §9).
290    pub fn ping(&mut self, nonce: Option<Json>) -> Result<Json, RcpError> {
291        let mut p = Json::object();
292        if let Some(n) = nonce {
293            p.insert("nonce", n);
294        }
295        self.request(Method::PING, p)
296    }
297
298    /// Politely ask the server to stop, then close the transport. Never errors.
299    pub fn shutdown(&mut self) {
300        let _ = self.request(Method::SHUTDOWN, Json::object());
301        self.transport.close();
302    }
303
304    // ── internals ───────────────────────────────────────────────────────────
305    fn gate(&self, cap: Capability) -> Result<(), RcpError> {
306        if self.supports(cap) {
307            Ok(())
308        } else {
309            Err(RcpError::new(
310                Errc::CAPABILITY_MISSING,
311                format!("server does not advertise '{}'", cap.wire_key()),
312            ))
313        }
314    }
315
316    fn request(&mut self, method: &str, params: Json) -> Result<Json, RcpError> {
317        self.next_id += 1;
318        let req = obj(&[
319            ("jsonrpc", "2.0".into()),
320            ("id", self.next_id.into()),
321            ("method", method.into()),
322            ("params", params),
323        ]);
324        let reply = self.transport.call(&req)?;
325        if let Some(err) = reply.get("error") {
326            if !err.is_null() {
327                return Err(RcpError::from_json(err));
328            }
329        }
330        Ok(reply.get("result").cloned().unwrap_or_else(Json::object))
331    }
332}