Skip to main content

example_server/
example_server.rs

1//! example_server.rs — a complete, dependency-free RCP/1 retrieval engine.
2//!
3//! Run over stdio (default):  cargo run --example example_server
4//! Or over HTTP:              cargo run --example example_server -- --http 8000
5
6use rcp::{obj, Capability, Json, Method, Server};
7
8const DIM: usize = 384;
9
10const DOCS: [(&str, &str); 3] = [
11    ("d1", "The Eiffel Tower is a wrought-iron lattice tower in Paris, France."),
12    ("d2", "Photosynthesis converts light energy into chemical energy in plants."),
13    ("d3", "The Great Wall of China stretches thousands of kilometres."),
14];
15
16fn embed_one(text: &str) -> Vec<f64> {
17    let mut v = vec![0.0f64; DIM];
18    for tok in text.to_lowercase().split_whitespace() {
19        let mut h: u32 = 2166136261; // FNV-1a (32-bit)
20        for b in tok.bytes() {
21            h ^= b as u32;
22            h = h.wrapping_mul(16777619);
23        }
24        v[(h as usize) % DIM] += 1.0;
25    }
26    let norm = v.iter().map(|x| x * x).sum::<f64>().sqrt();
27    let norm = if norm > 0.0 { norm } else { 1.0 };
28    v.iter().map(|x| x / norm).collect()
29}
30
31fn cosine(a: &[f64], b: &[f64]) -> f64 {
32    a.iter().zip(b).map(|(x, y)| x * y).sum()
33}
34
35fn search(query: &str, k: usize) -> Json {
36    let q = embed_one(query);
37    let mut scored: Vec<(f64, &str, &str)> = DOCS
38        .iter()
39        .map(|(id, text)| (cosine(&q, &embed_one(text)), *id, *text))
40        .collect();
41    scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
42    let hits: Vec<Json> = scored
43        .iter()
44        .take(k)
45        .map(|(s, id, text)| {
46            obj(&[
47                ("id", (*id).into()),
48                ("score", (*s).into()),
49                ("text", (*text).into()),
50            ])
51        })
52        .collect();
53    Json::Array(hits)
54}
55
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
116
117fn main() {
118    let args: Vec<String> = std::env::args().collect();
119    let mut s = build();
120    if args.len() >= 3 && args[1] == "--http" {
121        let port: u16 = args[2].parse().unwrap_or(8000);
122        let _ = s.serve_http(port);
123    } else {
124        s.serve_stdio();
125    }
126}