Skip to main content

kute_cli/
mcp.rs

1//! A Model Context Protocol server over standard input and output: one
2//! JSON-RPC 2.0 message per line.
3//!
4//! It offers five tools, all of them read-only with respect to this
5//! machine: `encode`, `decode`, `inspect`, `compare` and `discover`. It
6//! works on the vocabularies it was started with and on data passed in the
7//! call. It reads and writes no file, opens no connection, trains nothing,
8//! publishes nothing and keeps nothing between calls. Every input and
9//! output is bounded by [`Limits`].
10
11use base64::Engine as _;
12use kute::{vocab, Engine, KuteError, TokenSequence, Tokenizer, UnknownPolicy, Vocabulary};
13use serde_json::{json, Value};
14use std::io::{BufRead, Read, Write};
15
16/// The protocol revision this server was written against. A client that
17/// asks for another is answered with this one, as the protocol prescribes.
18pub const MCP_PROTOCOL: &str = "2025-06-18";
19
20/// What one call may cost.
21#[derive(Clone, Debug)]
22pub struct Limits {
23    /// Longest request line, in bytes. A longer one ends the session.
24    pub max_request_bytes: u64,
25    /// Most bytes of text or data in one `encode` or `discover` call.
26    pub max_input_bytes: u64,
27    /// Most bytes `decode` gives back, and most tokens it reads.
28    pub max_output_bytes: u64,
29    /// `encode` lists ids only up to this many; the container always holds all.
30    pub max_ids_listed: usize,
31    /// Most patterns `discover` reports of each kind.
32    pub max_patterns: usize,
33}
34
35impl Default for Limits {
36    fn default() -> Self {
37        Self { max_request_bytes: 8 << 20, max_input_bytes: 1 << 20, max_output_bytes: 4 << 20, max_ids_listed: 4096, max_patterns: 200 }
38    }
39}
40
41struct Held {
42    digest: String,
43    vocabulary: Vocabulary,
44    tokenizer: Box<dyn Tokenizer>,
45}
46
47pub struct Server {
48    engine: Engine,
49    held: Vec<Held>,
50    limits: Limits,
51}
52
53type Failure = String;
54
55fn fail(e: KuteError) -> Failure {
56    e.to_string()
57}
58
59fn text_arg<'a>(args: &'a Value, name: &str) -> Result<Option<&'a str>, Failure> {
60    match args.get(name) {
61        None | Some(Value::Null) => Ok(None),
62        Some(Value::String(s)) => Ok(Some(s)),
63        Some(_) => Err(format!("{name} must be a string")),
64    }
65}
66
67fn number_arg(args: &Value, name: &str) -> Result<Option<u64>, Failure> {
68    match args.get(name) {
69        None | Some(Value::Null) => Ok(None),
70        Some(v) => v.as_u64().map(Some).ok_or_else(|| format!("{name} must be a whole number, zero or more")),
71    }
72}
73
74impl Server {
75    pub fn new(engine: Engine, vocabularies: Vec<Vocabulary>, limits: Limits) -> kute::Result<Self> {
76        let mut held: Vec<Held> = Vec::new();
77        for vocabulary in vocabularies {
78            let digest = vocabulary.compute_digest()?;
79            if held.iter().any(|h| h.digest == digest) {
80                continue;
81            }
82            let tokenizer = engine.tokenizer(vocabulary.clone())?;
83            held.push(Held { digest, vocabulary, tokenizer });
84        }
85        Ok(Self { engine, held, limits })
86    }
87
88    /// A held vocabulary by digest, by `id version`, or by id alone when
89    /// only one version of it is held.
90    fn find(&self, name: &str) -> Result<&Held, Failure> {
91        let matches: Vec<&Held> = self
92            .held
93            .iter()
94            .filter(|h| {
95                let (id, version) = (h.vocabulary.id().as_str(), h.vocabulary.version().to_string());
96                h.digest == name || id == name || format!("{id} {version}") == name || format!("{id}@{version}") == name
97            })
98            .collect();
99        match matches.as_slice() {
100            [one] => Ok(one),
101            [] => Err(format!("no vocabulary {name:?} is held; call inspect without arguments to list them")),
102            _ => Err(format!("{name:?} names {} held vocabularies; give the version or the digest", matches.len())),
103        }
104    }
105
106    /// The engine vocabularies are checked with.
107    pub fn engine(&self) -> &Engine {
108        &self.engine
109    }
110
111    /// For the registry routes of the HTTP service: what is held, with
112    /// the key names of the signatures each file carries. The signatures
113    /// are listed as the files state them and are not checked here; the
114    /// one who fetches checks them against keys of their own choosing.
115    pub fn registry_list(&self) -> Value {
116        let list: Vec<Value> = self
117            .held
118            .iter()
119            .map(|h| {
120                let mut entry = Self::reference(h);
121                entry["algorithm"] = json!(h.vocabulary.manifest.algorithm);
122                entry["tokens"] = json!(h.vocabulary.len());
123                entry["signed_by"] = json!(h.vocabulary.integrity.as_ref().map(|i| i.signatures.iter().map(|s| s.key_id.clone()).collect::<Vec<_>>()).unwrap_or_default());
124                entry
125            })
126            .collect();
127        json!({ "vocabularies": list })
128    }
129
130    /// The file of the held vocabulary with exactly this digest, with
131    /// the signatures it was loaded with.
132    pub fn registry_file(&self, digest: &str) -> Option<kute::Result<Vec<u8>>> {
133        self.held.iter().find(|h| h.digest == digest).map(|h| vocab::to_vec(&h.vocabulary))
134    }
135
136    fn named(&self, args: &Value, field: &str) -> Result<&Held, Failure> {
137        self.find(text_arg(args, field)?.ok_or_else(|| format!("{field} is required"))?)
138    }
139
140    fn reference(held: &Held) -> Value {
141        json!({ "id": held.vocabulary.id().as_str(), "version": held.vocabulary.version().to_string(), "digest": held.digest })
142    }
143
144    fn encode(&self, args: &Value) -> Result<Value, Failure> {
145        let held = self.named(args, "vocabulary")?;
146        let raw = match (text_arg(args, "text")?, text_arg(args, "data_base64")?) {
147            (Some(text), None) => text.as_bytes().to_vec(),
148            (None, Some(data)) => {
149                if data.len() as u64 > self.limits.max_input_bytes.saturating_mul(4) / 3 + 4 {
150                    return Err(format!("the data is larger than the limit of {} bytes", self.limits.max_input_bytes));
151                }
152                base64::engine::general_purpose::STANDARD.decode(data).map_err(|e| format!("data_base64 is not base64: {e}"))?
153            }
154            _ => return Err("give exactly one of text and data_base64".into()),
155        };
156        if raw.len() as u64 > self.limits.max_input_bytes {
157            return Err(format!("the input is {} bytes; the limit is {}", raw.len(), self.limits.max_input_bytes));
158        }
159        let policy = UnknownPolicy::parse(text_arg(args, "unknown")?.unwrap_or("strict")).map_err(fail)?;
160        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), &raw, policy).map_err(fail)?;
161        let container = sequence.to_bytes_compressed().map_err(fail)?;
162        let listed = sequence.ids.len() <= self.limits.max_ids_listed;
163        Ok(json!({
164            "vocabulary": Self::reference(held),
165            "input_bytes": raw.len(),
166            "tokens": sequence.ids.len(),
167            "ids": if listed { json!(sequence.ids) } else { Value::Null },
168            "ids_omitted": !listed,
169            "escaped_symbols": sequence.escapes,
170            "container_bytes": container.len(),
171            "container_base64": base64::engine::general_purpose::STANDARD.encode(&container),
172        }))
173    }
174
175    fn decode(&self, args: &Value) -> Result<Value, Failure> {
176        let container = text_arg(args, "container_base64")?.ok_or("container_base64 is required")?;
177        let container = base64::engine::general_purpose::STANDARD.decode(container).map_err(|e| format!("container_base64 is not base64: {e}"))?;
178        // Every token decodes to at least one byte or symbol, so the
179        // output limit also bounds the tokens worth reading.
180        let sequence = TokenSequence::from_bytes_bounded(&container, self.limits.max_output_bytes).map_err(fail)?;
181        let held = self.find(&sequence.vocabulary_digest).map_err(|_| {
182            format!("the container was encoded under {} {} ({}), which is not held", sequence.vocabulary_id, sequence.vocabulary_version, sequence.vocabulary_digest)
183        })?;
184        let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.limits.max_output_bytes, self.limits.max_output_bytes).map_err(fail)?;
185        if bytes.len() as u64 > self.limits.max_output_bytes {
186            return Err(format!("the container decodes to {} bytes; the limit is {}", bytes.len(), self.limits.max_output_bytes));
187        }
188        let mut out = json!({ "vocabulary": Self::reference(held), "tokens": sequence.ids.len(), "bytes": bytes.len() });
189        match String::from_utf8(bytes) {
190            Ok(text) => out["text"] = json!(text),
191            Err(e) => out["data_base64"] = json!(base64::engine::general_purpose::STANDARD.encode(e.as_bytes())),
192        }
193        Ok(out)
194    }
195
196    fn inspect(&self, args: &Value) -> Result<Value, Failure> {
197        if text_arg(args, "vocabulary")?.is_none() {
198            let list: Vec<Value> = self
199                .held
200                .iter()
201                .map(|h| {
202                    let mut entry = Self::reference(h);
203                    entry["algorithm"] = json!(h.vocabulary.manifest.algorithm);
204                    entry["tokens"] = json!(h.vocabulary.len());
205                    entry
206                })
207                .collect();
208            return Ok(json!({ "vocabularies": list, "limits": self.limits_json() }));
209        }
210        let held = self.named(args, "vocabulary")?;
211        if let Some(id) = number_arg(args, "token")? {
212            let id = u32::try_from(id).map_err(|_| "token is not a token id".to_string())?;
213            return serde_json::to_value(held.vocabulary.record(id).map_err(fail)?).map_err(|e| e.to_string());
214        }
215        let mut report = json!({ "summary": vocab::summarize(&held.vocabulary).map_err(fail)? });
216        let longest = number_arg(args, "longest")?.unwrap_or(0).min(100) as usize;
217        if longest > 0 {
218            let mut learned: Vec<&kute::TokenEntry> = held.vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
219            learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
220            let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| held.vocabulary.record(t.id)).collect::<kute::Result<_>>().map_err(fail)?;
221            report["longest_learned_tokens"] = serde_json::to_value(rows).map_err(|e| e.to_string())?;
222        }
223        Ok(report)
224    }
225
226    fn compare(&self, args: &Value) -> Result<Value, Failure> {
227        let (a, b) = (self.named(args, "a")?, self.named(args, "b")?);
228        serde_json::to_value(vocab::compare(&a.vocabulary, &b.vocabulary).map_err(fail)?).map_err(|e| e.to_string())
229    }
230
231    fn discover(&self, args: &Value) -> Result<Value, Failure> {
232        let records: Vec<Vec<String>> = match (args.get("records"), text_arg(args, "lines")?) {
233            (Some(records), None) => serde_json::from_value(records.clone()).map_err(|_| "records must be a list of lists of strings".to_string())?,
234            (None, Some(lines)) => lines.lines().map(|l| l.split_whitespace().map(str::to_string).collect()).filter(|r: &Vec<String>| !r.is_empty()).collect(),
235            _ => return Err("give exactly one of records and lines".into()),
236        };
237        // Times, when given, are one whole number for each symbol.
238        let times: Option<Vec<Vec<i64>>> = match args.get("times").filter(|v| !v.is_null()) {
239            None => None,
240            Some(_) if args.get("records").is_none() => return Err("times go with records, one number for each symbol".into()),
241            Some(times) => Some(serde_json::from_value(times.clone()).map_err(|_| "times must be a list of lists of whole numbers".to_string())?),
242        };
243        let size: u64 = records.iter().flatten().map(|s| s.len() as u64 + 1).sum::<u64>() + times.iter().flatten().map(|t| 8 * t.len() as u64).sum::<u64>();
244        if size > self.limits.max_input_bytes {
245            return Err(format!("the records hold {size} bytes of symbols; the limit is {}", self.limits.max_input_bytes));
246        }
247        let mut params = kute_discover::Params { max_candidates: 200_000, ..Default::default() };
248        if let Some(n) = number_arg(args, "min_support")? {
249            params.min_support = n;
250        }
251        if let Some(n) = number_arg(args, "max_length")? {
252            params.max_length = n as usize;
253        }
254        if let Some(n) = number_arg(args, "window")? {
255            params.window = n as usize;
256        }
257        if let Some(bits) = args.get("min_cohesion_bits").filter(|v| !v.is_null()) {
258            params.min_cohesion_bits = bits.as_f64().ok_or("min_cohesion_bits must be a number")?;
259        }
260        params.max_patterns = (number_arg(args, "max_patterns")?.unwrap_or(50) as usize).min(self.limits.max_patterns);
261        let discovery = kute_discover::discover(&records, &params).map_err(fail)?;
262        let mut answer = serde_json::to_value(&discovery).map_err(|e| e.to_string())?;
263        if let Some(times) = times {
264            if times.len() != records.len() {
265                return Err(format!("{} lists of times for {} records", times.len(), records.len()));
266            }
267            // The unit is the caller's: durations come back in the ticks
268            // that were given. The schema needs one to be a timed schema.
269            let schema = kute::EventSchema {
270                id: "call".into(),
271                version: 1,
272                symbol_field: "symbol".into(),
273                time_field: Some("time".into()),
274                time_unit: Some(kute::TimeUnit::Milliseconds),
275                group_field: None,
276            };
277            let mut stream = kute::EventStream::new(schema).map_err(fail)?;
278            stream.records = records.into_iter().zip(times).map(|(symbols, times)| kute::EventRecord { key: None, symbols, times }).collect();
279            // Refuses times not aligned with their symbols, or going back.
280            stream.validate().map_err(fail)?;
281            answer["timing"] = serde_json::to_value(kute_discover::timing(&discovery, &stream).map_err(fail)?).map_err(|e| e.to_string())?;
282            answer["timing_what"] = "per pattern (index into patterns), in the ticks the times were given in: time from the first event of an occurrence to its last; for a gapped pair, from the first symbol to the nearest second symbol within the window. Measured on the records given, the same ones the patterns were found in.".into();
283        }
284        Ok(answer)
285    }
286
287    fn limits_json(&self) -> Value {
288        json!({
289            "max_request_bytes": self.limits.max_request_bytes,
290            "max_input_bytes": self.limits.max_input_bytes,
291            "max_output_bytes": self.limits.max_output_bytes,
292            "max_ids_listed": self.limits.max_ids_listed,
293            "max_patterns": self.limits.max_patterns,
294        })
295    }
296
297    /// The tools, with the JSON Schema of each one's arguments.
298    pub fn tools() -> Value {
299        let vocabulary = json!({ "type": "string", "description": "A held vocabulary: its digest, its id, or \"id version\"." });
300        let read_only = json!({ "readOnlyHint": true, "openWorldHint": false });
301        json!([
302            {
303                "name": "encode",
304                "description": "Encode text or bytes under a held vocabulary. Returns the token ids and a .kute container (base64) that decode accepts. Lossless: decoding the container gives the input back.",
305                "inputSchema": { "type": "object", "required": ["vocabulary"], "additionalProperties": false, "properties": {
306                    "vocabulary": vocabulary,
307                    "text": { "type": "string", "description": "The input as text. Give this or data_base64." },
308                    "data_base64": { "type": "string", "description": "The input as base64 bytes." },
309                    "unknown": { "type": "string", "enum": ["strict", "escape"], "description": "For symbol vocabularies: refuse a symbol the vocabulary lacks (strict, the default) or carry it literally (escape)." }
310                } },
311                "annotations": read_only,
312            },
313            {
314                "name": "decode",
315                "description": "Decode a .kute container produced by encode. The vocabulary is the one the container names, and must be held.",
316                "inputSchema": { "type": "object", "required": ["container_base64"], "additionalProperties": false, "properties": {
317                    "container_base64": { "type": "string" }
318                } },
319                "annotations": read_only,
320            },
321            {
322                "name": "inspect",
323                "description": "Without arguments, list the held vocabularies and this server's limits. With a vocabulary, summarize it; with token, show one token; with longest, the N longest learned tokens.",
324                "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
325                    "vocabulary": vocabulary,
326                    "token": { "type": "integer", "minimum": 0 },
327                    "longest": { "type": "integer", "minimum": 0, "maximum": 100 }
328                } },
329                "annotations": read_only,
330            },
331            {
332                "name": "compare",
333                "description": "Compare two held vocabularies by token content: shared and distinct payloads. Token ids are not compared; the same id in two vocabularies means nothing.",
334                "inputSchema": { "type": "object", "required": ["a", "b"], "additionalProperties": false, "properties": { "a": vocabulary, "b": vocabulary } },
335                "annotations": read_only,
336            },
337            {
338                "name": "discover",
339                "description": "Find recurring patterns in records of symbols passed in the call: contiguous sequences and gapped pairs, with support and cohesion. A statistical description of the input, not a claim about meaning. Nothing is stored.",
340                "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
341                    "records": { "type": "array", "items": { "type": "array", "items": { "type": "string" } }, "description": "One list of symbols per record. Give this or lines." },
342                    "lines": { "type": "string", "description": "One record per line, symbols separated by whitespace." },
343                    "times": { "type": "array", "items": { "type": "array", "items": { "type": "integer" } }, "description": "With records: one whole-number timestamp for each symbol, never going back within a record. The answer then has timing: how long each pattern took, in the same ticks." },
344                    "min_support": { "type": "integer", "minimum": 2 },
345                    "max_length": { "type": "integer", "minimum": 2 },
346                    "window": { "type": "integer", "minimum": 0 },
347                    "min_cohesion_bits": { "type": "number" },
348                    "max_patterns": { "type": "integer", "minimum": 1 }
349                } },
350                "annotations": read_only,
351            }
352        ])
353    }
354
355    /// Run one tool by name. The HTTP service calls the same function.
356    pub fn call(&self, name: &str, args: &Value) -> Result<Value, String> {
357        if !args.is_object() {
358            return Err("arguments must be an object".into());
359        }
360        match name {
361            "encode" => self.encode(args),
362            "decode" => self.decode(args),
363            "inspect" => self.inspect(args),
364            "compare" => self.compare(args),
365            "discover" => self.discover(args),
366            other => Err(format!("there is no tool {other:?}")),
367        }
368    }
369
370    /// Answer one request. `None` for a notification, which gets no answer.
371    pub fn handle(&self, request: &Value) -> Option<Value> {
372        let id = request.get("id").cloned();
373        let error_id = id.clone().unwrap_or(Value::Null);
374        let error = |code: i64, message: String| Some(json!({ "jsonrpc": "2.0", "id": error_id.clone(), "error": { "code": code, "message": message } }));
375        let Some(method) = request.get("method").and_then(Value::as_str) else {
376            return error(-32600, "not a JSON-RPC request: no method".into());
377        };
378        let id = id?; // without an id it is a notification
379        let empty = json!({});
380        let params = request.get("params").unwrap_or(&empty);
381        let result = match method {
382            "initialize" => json!({
383                "protocolVersion": MCP_PROTOCOL,
384                "capabilities": { "tools": {} },
385                "serverInfo": { "name": "kute", "version": kute::KUTE_VERSION },
386                "instructions": "Tokenization tools over the vocabularies this server was started with. Call inspect without arguments first. Nothing is trained, stored, published or read from disk.",
387            }),
388            "ping" => json!({}),
389            "tools/list" => json!({ "tools": Self::tools() }),
390            "tools/call" => {
391                let Some(name) = params.get("name").and_then(Value::as_str) else {
392                    return error(-32602, "tools/call needs a name".into());
393                };
394                if !Self::tools().as_array().is_some_and(|tools| tools.iter().any(|t| t["name"] == name)) {
395                    return error(-32602, format!("there is no tool {name:?}"));
396                }
397                // A tool that fails is a result with isError, so the model
398                // sees why; protocol errors are for malformed requests.
399                match self.call(name, params.get("arguments").unwrap_or(&empty)) {
400                    Ok(value) => json!({ "content": [{ "type": "text", "text": value.to_string() }], "structuredContent": value, "isError": false }),
401                    Err(why) => json!({ "content": [{ "type": "text", "text": why }], "isError": true }),
402                }
403            }
404            other => return error(-32601, format!("method {other:?} is not supported")),
405        };
406        Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
407    }
408
409    /// Serve until the input ends. Returns the number of requests answered.
410    pub fn serve(&self, mut input: impl BufRead, mut output: impl Write) -> kute::Result<u64> {
411        let mut answered = 0;
412        loop {
413            let mut line = Vec::new();
414            let read = (&mut input).take(self.limits.max_request_bytes + 1).read_until(b'\n', &mut line)?;
415            if read == 0 {
416                return Ok(answered);
417            }
418            let reply = if line.len() as u64 > self.limits.max_request_bytes && !line.ends_with(b"\n") {
419                // The rest of the line cannot be skipped without reading it,
420                // so say why and stop.
421                let message = format!("the request is longer than {} bytes", self.limits.max_request_bytes);
422                serde_json::to_writer(&mut output, &json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": message } }))?;
423                output.write_all(b"\n")?;
424                output.flush()?;
425                return Err(KuteError::LimitExceeded("an MCP request exceeded the request limit".into()));
426            } else if line.iter().all(u8::is_ascii_whitespace) {
427                continue;
428            } else {
429                match serde_json::from_slice::<Value>(&line) {
430                    Ok(request) if request.is_object() => self.handle(&request),
431                    Ok(_) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": "a request must be one JSON object; batches are not supported" } })),
432                    Err(e) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": format!("not JSON: {e}") } })),
433                }
434            };
435            if let Some(reply) = reply {
436                serde_json::to_writer(&mut output, &reply)?;
437                output.write_all(b"\n")?;
438                output.flush()?;
439                answered += 1;
440            }
441        }
442    }
443}