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    /// For the registry routes of the HTTP service: what is held, with
107    /// the key names of the signatures each file carries. The signatures
108    /// are listed as the files state them and are not checked here; the
109    /// one who fetches checks them against keys of their own choosing.
110    pub fn registry_list(&self) -> Value {
111        let list: Vec<Value> = self
112            .held
113            .iter()
114            .map(|h| {
115                let mut entry = Self::reference(h);
116                entry["algorithm"] = json!(h.vocabulary.manifest.algorithm);
117                entry["tokens"] = json!(h.vocabulary.len());
118                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());
119                entry
120            })
121            .collect();
122        json!({ "vocabularies": list })
123    }
124
125    /// The file of the held vocabulary with exactly this digest, with
126    /// the signatures it was loaded with.
127    pub fn registry_file(&self, digest: &str) -> Option<kute::Result<Vec<u8>>> {
128        self.held.iter().find(|h| h.digest == digest).map(|h| vocab::to_vec(&h.vocabulary))
129    }
130
131    fn named(&self, args: &Value, field: &str) -> Result<&Held, Failure> {
132        self.find(text_arg(args, field)?.ok_or_else(|| format!("{field} is required"))?)
133    }
134
135    fn reference(held: &Held) -> Value {
136        json!({ "id": held.vocabulary.id().as_str(), "version": held.vocabulary.version().to_string(), "digest": held.digest })
137    }
138
139    fn encode(&self, args: &Value) -> Result<Value, Failure> {
140        let held = self.named(args, "vocabulary")?;
141        let raw = match (text_arg(args, "text")?, text_arg(args, "data_base64")?) {
142            (Some(text), None) => text.as_bytes().to_vec(),
143            (None, Some(data)) => {
144                if data.len() as u64 > self.limits.max_input_bytes.saturating_mul(4) / 3 + 4 {
145                    return Err(format!("the data is larger than the limit of {} bytes", self.limits.max_input_bytes));
146                }
147                base64::engine::general_purpose::STANDARD.decode(data).map_err(|e| format!("data_base64 is not base64: {e}"))?
148            }
149            _ => return Err("give exactly one of text and data_base64".into()),
150        };
151        if raw.len() as u64 > self.limits.max_input_bytes {
152            return Err(format!("the input is {} bytes; the limit is {}", raw.len(), self.limits.max_input_bytes));
153        }
154        let policy = UnknownPolicy::parse(text_arg(args, "unknown")?.unwrap_or("strict")).map_err(fail)?;
155        let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), &raw, policy).map_err(fail)?;
156        let container = sequence.to_bytes_compressed().map_err(fail)?;
157        let listed = sequence.ids.len() <= self.limits.max_ids_listed;
158        Ok(json!({
159            "vocabulary": Self::reference(held),
160            "input_bytes": raw.len(),
161            "tokens": sequence.ids.len(),
162            "ids": if listed { json!(sequence.ids) } else { Value::Null },
163            "ids_omitted": !listed,
164            "escaped_symbols": sequence.escapes,
165            "container_bytes": container.len(),
166            "container_base64": base64::engine::general_purpose::STANDARD.encode(&container),
167        }))
168    }
169
170    fn decode(&self, args: &Value) -> Result<Value, Failure> {
171        let container = text_arg(args, "container_base64")?.ok_or("container_base64 is required")?;
172        let container = base64::engine::general_purpose::STANDARD.decode(container).map_err(|e| format!("container_base64 is not base64: {e}"))?;
173        // Every token decodes to at least one byte or symbol, so the
174        // output limit also bounds the tokens worth reading.
175        let sequence = TokenSequence::from_bytes_bounded(&container, self.limits.max_output_bytes).map_err(fail)?;
176        let held = self.find(&sequence.vocabulary_digest).map_err(|_| {
177            format!("the container was encoded under {} {} ({}), which is not held", sequence.vocabulary_id, sequence.vocabulary_version, sequence.vocabulary_digest)
178        })?;
179        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)?;
180        if bytes.len() as u64 > self.limits.max_output_bytes {
181            return Err(format!("the container decodes to {} bytes; the limit is {}", bytes.len(), self.limits.max_output_bytes));
182        }
183        let mut out = json!({ "vocabulary": Self::reference(held), "tokens": sequence.ids.len(), "bytes": bytes.len() });
184        match String::from_utf8(bytes) {
185            Ok(text) => out["text"] = json!(text),
186            Err(e) => out["data_base64"] = json!(base64::engine::general_purpose::STANDARD.encode(e.as_bytes())),
187        }
188        Ok(out)
189    }
190
191    fn inspect(&self, args: &Value) -> Result<Value, Failure> {
192        if text_arg(args, "vocabulary")?.is_none() {
193            let list: Vec<Value> = self
194                .held
195                .iter()
196                .map(|h| {
197                    let mut entry = Self::reference(h);
198                    entry["algorithm"] = json!(h.vocabulary.manifest.algorithm);
199                    entry["tokens"] = json!(h.vocabulary.len());
200                    entry
201                })
202                .collect();
203            return Ok(json!({ "vocabularies": list, "limits": self.limits_json() }));
204        }
205        let held = self.named(args, "vocabulary")?;
206        if let Some(id) = number_arg(args, "token")? {
207            let id = u32::try_from(id).map_err(|_| "token is not a token id".to_string())?;
208            return serde_json::to_value(held.vocabulary.record(id).map_err(fail)?).map_err(|e| e.to_string());
209        }
210        let mut report = json!({ "summary": vocab::summarize(&held.vocabulary).map_err(fail)? });
211        let longest = number_arg(args, "longest")?.unwrap_or(0).min(100) as usize;
212        if longest > 0 {
213            let mut learned: Vec<&kute::TokenEntry> = held.vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
214            learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
215            let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| held.vocabulary.record(t.id)).collect::<kute::Result<_>>().map_err(fail)?;
216            report["longest_learned_tokens"] = serde_json::to_value(rows).map_err(|e| e.to_string())?;
217        }
218        Ok(report)
219    }
220
221    fn compare(&self, args: &Value) -> Result<Value, Failure> {
222        let (a, b) = (self.named(args, "a")?, self.named(args, "b")?);
223        serde_json::to_value(vocab::compare(&a.vocabulary, &b.vocabulary).map_err(fail)?).map_err(|e| e.to_string())
224    }
225
226    fn discover(&self, args: &Value) -> Result<Value, Failure> {
227        let records: Vec<Vec<String>> = match (args.get("records"), text_arg(args, "lines")?) {
228            (Some(records), None) => serde_json::from_value(records.clone()).map_err(|_| "records must be a list of lists of strings".to_string())?,
229            (None, Some(lines)) => lines.lines().map(|l| l.split_whitespace().map(str::to_string).collect()).filter(|r: &Vec<String>| !r.is_empty()).collect(),
230            _ => return Err("give exactly one of records and lines".into()),
231        };
232        // Times, when given, are one whole number for each symbol.
233        let times: Option<Vec<Vec<i64>>> = match args.get("times").filter(|v| !v.is_null()) {
234            None => None,
235            Some(_) if args.get("records").is_none() => return Err("times go with records, one number for each symbol".into()),
236            Some(times) => Some(serde_json::from_value(times.clone()).map_err(|_| "times must be a list of lists of whole numbers".to_string())?),
237        };
238        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>();
239        if size > self.limits.max_input_bytes {
240            return Err(format!("the records hold {size} bytes of symbols; the limit is {}", self.limits.max_input_bytes));
241        }
242        let mut params = kute_discover::Params { max_candidates: 200_000, ..Default::default() };
243        if let Some(n) = number_arg(args, "min_support")? {
244            params.min_support = n;
245        }
246        if let Some(n) = number_arg(args, "max_length")? {
247            params.max_length = n as usize;
248        }
249        if let Some(n) = number_arg(args, "window")? {
250            params.window = n as usize;
251        }
252        if let Some(bits) = args.get("min_cohesion_bits").filter(|v| !v.is_null()) {
253            params.min_cohesion_bits = bits.as_f64().ok_or("min_cohesion_bits must be a number")?;
254        }
255        params.max_patterns = (number_arg(args, "max_patterns")?.unwrap_or(50) as usize).min(self.limits.max_patterns);
256        let discovery = kute_discover::discover(&records, &params).map_err(fail)?;
257        let mut answer = serde_json::to_value(&discovery).map_err(|e| e.to_string())?;
258        if let Some(times) = times {
259            if times.len() != records.len() {
260                return Err(format!("{} lists of times for {} records", times.len(), records.len()));
261            }
262            // The unit is the caller's: durations come back in the ticks
263            // that were given. The schema needs one to be a timed schema.
264            let schema = kute::EventSchema {
265                id: "call".into(),
266                version: 1,
267                symbol_field: "symbol".into(),
268                time_field: Some("time".into()),
269                time_unit: Some(kute::TimeUnit::Milliseconds),
270                group_field: None,
271            };
272            let mut stream = kute::EventStream::new(schema).map_err(fail)?;
273            stream.records = records.into_iter().zip(times).map(|(symbols, times)| kute::EventRecord { key: None, symbols, times }).collect();
274            // Refuses times not aligned with their symbols, or going back.
275            stream.validate().map_err(fail)?;
276            answer["timing"] = serde_json::to_value(kute_discover::timing(&discovery, &stream).map_err(fail)?).map_err(|e| e.to_string())?;
277            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();
278        }
279        Ok(answer)
280    }
281
282    fn limits_json(&self) -> Value {
283        json!({
284            "max_request_bytes": self.limits.max_request_bytes,
285            "max_input_bytes": self.limits.max_input_bytes,
286            "max_output_bytes": self.limits.max_output_bytes,
287            "max_ids_listed": self.limits.max_ids_listed,
288            "max_patterns": self.limits.max_patterns,
289        })
290    }
291
292    /// The tools, with the JSON Schema of each one's arguments.
293    pub fn tools() -> Value {
294        let vocabulary = json!({ "type": "string", "description": "A held vocabulary: its digest, its id, or \"id version\"." });
295        let read_only = json!({ "readOnlyHint": true, "openWorldHint": false });
296        json!([
297            {
298                "name": "encode",
299                "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.",
300                "inputSchema": { "type": "object", "required": ["vocabulary"], "additionalProperties": false, "properties": {
301                    "vocabulary": vocabulary,
302                    "text": { "type": "string", "description": "The input as text. Give this or data_base64." },
303                    "data_base64": { "type": "string", "description": "The input as base64 bytes." },
304                    "unknown": { "type": "string", "enum": ["strict", "escape"], "description": "For symbol vocabularies: refuse a symbol the vocabulary lacks (strict, the default) or carry it literally (escape)." }
305                } },
306                "annotations": read_only,
307            },
308            {
309                "name": "decode",
310                "description": "Decode a .kute container produced by encode. The vocabulary is the one the container names, and must be held.",
311                "inputSchema": { "type": "object", "required": ["container_base64"], "additionalProperties": false, "properties": {
312                    "container_base64": { "type": "string" }
313                } },
314                "annotations": read_only,
315            },
316            {
317                "name": "inspect",
318                "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.",
319                "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
320                    "vocabulary": vocabulary,
321                    "token": { "type": "integer", "minimum": 0 },
322                    "longest": { "type": "integer", "minimum": 0, "maximum": 100 }
323                } },
324                "annotations": read_only,
325            },
326            {
327                "name": "compare",
328                "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.",
329                "inputSchema": { "type": "object", "required": ["a", "b"], "additionalProperties": false, "properties": { "a": vocabulary, "b": vocabulary } },
330                "annotations": read_only,
331            },
332            {
333                "name": "discover",
334                "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.",
335                "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
336                    "records": { "type": "array", "items": { "type": "array", "items": { "type": "string" } }, "description": "One list of symbols per record. Give this or lines." },
337                    "lines": { "type": "string", "description": "One record per line, symbols separated by whitespace." },
338                    "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." },
339                    "min_support": { "type": "integer", "minimum": 2 },
340                    "max_length": { "type": "integer", "minimum": 2 },
341                    "window": { "type": "integer", "minimum": 0 },
342                    "min_cohesion_bits": { "type": "number" },
343                    "max_patterns": { "type": "integer", "minimum": 1 }
344                } },
345                "annotations": read_only,
346            }
347        ])
348    }
349
350    /// Run one tool by name. The HTTP service calls the same function.
351    pub fn call(&self, name: &str, args: &Value) -> Result<Value, String> {
352        if !args.is_object() {
353            return Err("arguments must be an object".into());
354        }
355        match name {
356            "encode" => self.encode(args),
357            "decode" => self.decode(args),
358            "inspect" => self.inspect(args),
359            "compare" => self.compare(args),
360            "discover" => self.discover(args),
361            other => Err(format!("there is no tool {other:?}")),
362        }
363    }
364
365    /// Answer one request. `None` for a notification, which gets no answer.
366    pub fn handle(&self, request: &Value) -> Option<Value> {
367        let id = request.get("id").cloned();
368        let error_id = id.clone().unwrap_or(Value::Null);
369        let error = |code: i64, message: String| Some(json!({ "jsonrpc": "2.0", "id": error_id.clone(), "error": { "code": code, "message": message } }));
370        let Some(method) = request.get("method").and_then(Value::as_str) else {
371            return error(-32600, "not a JSON-RPC request: no method".into());
372        };
373        let id = id?; // without an id it is a notification
374        let empty = json!({});
375        let params = request.get("params").unwrap_or(&empty);
376        let result = match method {
377            "initialize" => json!({
378                "protocolVersion": MCP_PROTOCOL,
379                "capabilities": { "tools": {} },
380                "serverInfo": { "name": "kute", "version": kute::KUTE_VERSION },
381                "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.",
382            }),
383            "ping" => json!({}),
384            "tools/list" => json!({ "tools": Self::tools() }),
385            "tools/call" => {
386                let Some(name) = params.get("name").and_then(Value::as_str) else {
387                    return error(-32602, "tools/call needs a name".into());
388                };
389                if !Self::tools().as_array().is_some_and(|tools| tools.iter().any(|t| t["name"] == name)) {
390                    return error(-32602, format!("there is no tool {name:?}"));
391                }
392                // A tool that fails is a result with isError, so the model
393                // sees why; protocol errors are for malformed requests.
394                match self.call(name, params.get("arguments").unwrap_or(&empty)) {
395                    Ok(value) => json!({ "content": [{ "type": "text", "text": value.to_string() }], "structuredContent": value, "isError": false }),
396                    Err(why) => json!({ "content": [{ "type": "text", "text": why }], "isError": true }),
397                }
398            }
399            other => return error(-32601, format!("method {other:?} is not supported")),
400        };
401        Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
402    }
403
404    /// Serve until the input ends. Returns the number of requests answered.
405    pub fn serve(&self, mut input: impl BufRead, mut output: impl Write) -> kute::Result<u64> {
406        let mut answered = 0;
407        loop {
408            let mut line = Vec::new();
409            let read = (&mut input).take(self.limits.max_request_bytes + 1).read_until(b'\n', &mut line)?;
410            if read == 0 {
411                return Ok(answered);
412            }
413            let reply = if line.len() as u64 > self.limits.max_request_bytes && !line.ends_with(b"\n") {
414                // The rest of the line cannot be skipped without reading it,
415                // so say why and stop.
416                let message = format!("the request is longer than {} bytes", self.limits.max_request_bytes);
417                serde_json::to_writer(&mut output, &json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": message } }))?;
418                output.write_all(b"\n")?;
419                output.flush()?;
420                return Err(KuteError::LimitExceeded("an MCP request exceeded the request limit".into()));
421            } else if line.iter().all(u8::is_ascii_whitespace) {
422                continue;
423            } else {
424                match serde_json::from_slice::<Value>(&line) {
425                    Ok(request) if request.is_object() => self.handle(&request),
426                    Ok(_) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": "a request must be one JSON object; batches are not supported" } })),
427                    Err(e) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": format!("not JSON: {e}") } })),
428                }
429            };
430            if let Some(reply) = reply {
431                serde_json::to_writer(&mut output, &reply)?;
432                output.write_all(b"\n")?;
433                output.flush()?;
434                answered += 1;
435            }
436        }
437    }
438}