1use base64::Engine as _;
12use kute::{vocab, Engine, KuteError, TokenSequence, Tokenizer, UnknownPolicy, Vocabulary};
13use serde_json::{json, Value};
14use std::io::{BufRead, Read, Write};
15
16pub const MCP_PROTOCOL: &str = "2025-06-18";
19
20#[derive(Clone, Debug)]
22pub struct Limits {
23 pub max_request_bytes: u64,
25 pub max_input_bytes: u64,
27 pub max_output_bytes: u64,
29 pub max_ids_listed: usize,
31 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 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 fn named(&self, args: &Value, field: &str) -> Result<&Held, Failure> {
107 self.find(text_arg(args, field)?.ok_or_else(|| format!("{field} is required"))?)
108 }
109
110 fn reference(held: &Held) -> Value {
111 json!({ "id": held.vocabulary.id().as_str(), "version": held.vocabulary.version().to_string(), "digest": held.digest })
112 }
113
114 fn encode(&self, args: &Value) -> Result<Value, Failure> {
115 let held = self.named(args, "vocabulary")?;
116 let raw = match (text_arg(args, "text")?, text_arg(args, "data_base64")?) {
117 (Some(text), None) => text.as_bytes().to_vec(),
118 (None, Some(data)) => {
119 if data.len() as u64 > self.limits.max_input_bytes.saturating_mul(4) / 3 + 4 {
120 return Err(format!("the data is larger than the limit of {} bytes", self.limits.max_input_bytes));
121 }
122 base64::engine::general_purpose::STANDARD.decode(data).map_err(|e| format!("data_base64 is not base64: {e}"))?
123 }
124 _ => return Err("give exactly one of text and data_base64".into()),
125 };
126 if raw.len() as u64 > self.limits.max_input_bytes {
127 return Err(format!("the input is {} bytes; the limit is {}", raw.len(), self.limits.max_input_bytes));
128 }
129 let policy = UnknownPolicy::parse(text_arg(args, "unknown")?.unwrap_or("strict")).map_err(fail)?;
130 let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), &raw, policy).map_err(fail)?;
131 let container = sequence.to_bytes_compressed().map_err(fail)?;
132 let listed = sequence.ids.len() <= self.limits.max_ids_listed;
133 Ok(json!({
134 "vocabulary": Self::reference(held),
135 "input_bytes": raw.len(),
136 "tokens": sequence.ids.len(),
137 "ids": if listed { json!(sequence.ids) } else { Value::Null },
138 "ids_omitted": !listed,
139 "escaped_symbols": sequence.escapes,
140 "container_bytes": container.len(),
141 "container_base64": base64::engine::general_purpose::STANDARD.encode(&container),
142 }))
143 }
144
145 fn decode(&self, args: &Value) -> Result<Value, Failure> {
146 let container = text_arg(args, "container_base64")?.ok_or("container_base64 is required")?;
147 let container = base64::engine::general_purpose::STANDARD.decode(container).map_err(|e| format!("container_base64 is not base64: {e}"))?;
148 let sequence = TokenSequence::from_bytes_bounded(&container, self.limits.max_output_bytes).map_err(fail)?;
151 let held = self.find(&sequence.vocabulary_digest).map_err(|_| {
152 format!("the container was encoded under {} {} ({}), which is not held", sequence.vocabulary_id, sequence.vocabulary_version, sequence.vocabulary_digest)
153 })?;
154 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)?;
155 if bytes.len() as u64 > self.limits.max_output_bytes {
156 return Err(format!("the container decodes to {} bytes; the limit is {}", bytes.len(), self.limits.max_output_bytes));
157 }
158 let mut out = json!({ "vocabulary": Self::reference(held), "tokens": sequence.ids.len(), "bytes": bytes.len() });
159 match String::from_utf8(bytes) {
160 Ok(text) => out["text"] = json!(text),
161 Err(e) => out["data_base64"] = json!(base64::engine::general_purpose::STANDARD.encode(e.as_bytes())),
162 }
163 Ok(out)
164 }
165
166 fn inspect(&self, args: &Value) -> Result<Value, Failure> {
167 if text_arg(args, "vocabulary")?.is_none() {
168 let list: Vec<Value> = self
169 .held
170 .iter()
171 .map(|h| {
172 let mut entry = Self::reference(h);
173 entry["algorithm"] = json!(h.vocabulary.manifest.algorithm);
174 entry["tokens"] = json!(h.vocabulary.len());
175 entry
176 })
177 .collect();
178 return Ok(json!({ "vocabularies": list, "limits": self.limits_json() }));
179 }
180 let held = self.named(args, "vocabulary")?;
181 if let Some(id) = number_arg(args, "token")? {
182 let id = u32::try_from(id).map_err(|_| "token is not a token id".to_string())?;
183 return serde_json::to_value(held.vocabulary.record(id).map_err(fail)?).map_err(|e| e.to_string());
184 }
185 let mut report = json!({ "summary": vocab::summarize(&held.vocabulary).map_err(fail)? });
186 let longest = number_arg(args, "longest")?.unwrap_or(0).min(100) as usize;
187 if longest > 0 {
188 let mut learned: Vec<&kute::TokenEntry> = held.vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
189 learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
190 let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| held.vocabulary.record(t.id)).collect::<kute::Result<_>>().map_err(fail)?;
191 report["longest_learned_tokens"] = serde_json::to_value(rows).map_err(|e| e.to_string())?;
192 }
193 Ok(report)
194 }
195
196 fn compare(&self, args: &Value) -> Result<Value, Failure> {
197 let (a, b) = (self.named(args, "a")?, self.named(args, "b")?);
198 serde_json::to_value(vocab::compare(&a.vocabulary, &b.vocabulary).map_err(fail)?).map_err(|e| e.to_string())
199 }
200
201 fn discover(&self, args: &Value) -> Result<Value, Failure> {
202 let records: Vec<Vec<String>> = match (args.get("records"), text_arg(args, "lines")?) {
203 (Some(records), None) => serde_json::from_value(records.clone()).map_err(|_| "records must be a list of lists of strings".to_string())?,
204 (None, Some(lines)) => lines.lines().map(|l| l.split_whitespace().map(str::to_string).collect()).filter(|r: &Vec<String>| !r.is_empty()).collect(),
205 _ => return Err("give exactly one of records and lines".into()),
206 };
207 let size: u64 = records.iter().flatten().map(|s| s.len() as u64 + 1).sum();
208 if size > self.limits.max_input_bytes {
209 return Err(format!("the records hold {size} bytes of symbols; the limit is {}", self.limits.max_input_bytes));
210 }
211 let mut params = kute_discover::Params { max_candidates: 200_000, ..Default::default() };
212 if let Some(n) = number_arg(args, "min_support")? {
213 params.min_support = n;
214 }
215 if let Some(n) = number_arg(args, "max_length")? {
216 params.max_length = n as usize;
217 }
218 if let Some(n) = number_arg(args, "window")? {
219 params.window = n as usize;
220 }
221 if let Some(bits) = args.get("min_cohesion_bits").filter(|v| !v.is_null()) {
222 params.min_cohesion_bits = bits.as_f64().ok_or("min_cohesion_bits must be a number")?;
223 }
224 params.max_patterns = (number_arg(args, "max_patterns")?.unwrap_or(50) as usize).min(self.limits.max_patterns);
225 let discovery = kute_discover::discover(&records, ¶ms).map_err(fail)?;
226 serde_json::to_value(discovery).map_err(|e| e.to_string())
227 }
228
229 fn limits_json(&self) -> Value {
230 json!({
231 "max_request_bytes": self.limits.max_request_bytes,
232 "max_input_bytes": self.limits.max_input_bytes,
233 "max_output_bytes": self.limits.max_output_bytes,
234 "max_ids_listed": self.limits.max_ids_listed,
235 "max_patterns": self.limits.max_patterns,
236 })
237 }
238
239 pub fn tools() -> Value {
241 let vocabulary = json!({ "type": "string", "description": "A held vocabulary: its digest, its id, or \"id version\"." });
242 let read_only = json!({ "readOnlyHint": true, "openWorldHint": false });
243 json!([
244 {
245 "name": "encode",
246 "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.",
247 "inputSchema": { "type": "object", "required": ["vocabulary"], "additionalProperties": false, "properties": {
248 "vocabulary": vocabulary,
249 "text": { "type": "string", "description": "The input as text. Give this or data_base64." },
250 "data_base64": { "type": "string", "description": "The input as base64 bytes." },
251 "unknown": { "type": "string", "enum": ["strict", "escape"], "description": "For symbol vocabularies: refuse a symbol the vocabulary lacks (strict, the default) or carry it literally (escape)." }
252 } },
253 "annotations": read_only,
254 },
255 {
256 "name": "decode",
257 "description": "Decode a .kute container produced by encode. The vocabulary is the one the container names, and must be held.",
258 "inputSchema": { "type": "object", "required": ["container_base64"], "additionalProperties": false, "properties": {
259 "container_base64": { "type": "string" }
260 } },
261 "annotations": read_only,
262 },
263 {
264 "name": "inspect",
265 "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.",
266 "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
267 "vocabulary": vocabulary,
268 "token": { "type": "integer", "minimum": 0 },
269 "longest": { "type": "integer", "minimum": 0, "maximum": 100 }
270 } },
271 "annotations": read_only,
272 },
273 {
274 "name": "compare",
275 "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.",
276 "inputSchema": { "type": "object", "required": ["a", "b"], "additionalProperties": false, "properties": { "a": vocabulary, "b": vocabulary } },
277 "annotations": read_only,
278 },
279 {
280 "name": "discover",
281 "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.",
282 "inputSchema": { "type": "object", "additionalProperties": false, "properties": {
283 "records": { "type": "array", "items": { "type": "array", "items": { "type": "string" } }, "description": "One list of symbols per record. Give this or lines." },
284 "lines": { "type": "string", "description": "One record per line, symbols separated by whitespace." },
285 "min_support": { "type": "integer", "minimum": 2 },
286 "max_length": { "type": "integer", "minimum": 2 },
287 "window": { "type": "integer", "minimum": 0 },
288 "min_cohesion_bits": { "type": "number" },
289 "max_patterns": { "type": "integer", "minimum": 1 }
290 } },
291 "annotations": read_only,
292 }
293 ])
294 }
295
296 pub fn call(&self, name: &str, args: &Value) -> Result<Value, String> {
298 if !args.is_object() {
299 return Err("arguments must be an object".into());
300 }
301 match name {
302 "encode" => self.encode(args),
303 "decode" => self.decode(args),
304 "inspect" => self.inspect(args),
305 "compare" => self.compare(args),
306 "discover" => self.discover(args),
307 other => Err(format!("there is no tool {other:?}")),
308 }
309 }
310
311 pub fn handle(&self, request: &Value) -> Option<Value> {
313 let id = request.get("id").cloned();
314 let error_id = id.clone().unwrap_or(Value::Null);
315 let error = |code: i64, message: String| Some(json!({ "jsonrpc": "2.0", "id": error_id.clone(), "error": { "code": code, "message": message } }));
316 let Some(method) = request.get("method").and_then(Value::as_str) else {
317 return error(-32600, "not a JSON-RPC request: no method".into());
318 };
319 let id = id?; let empty = json!({});
321 let params = request.get("params").unwrap_or(&empty);
322 let result = match method {
323 "initialize" => json!({
324 "protocolVersion": MCP_PROTOCOL,
325 "capabilities": { "tools": {} },
326 "serverInfo": { "name": "kute", "version": kute::KUTE_VERSION },
327 "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.",
328 }),
329 "ping" => json!({}),
330 "tools/list" => json!({ "tools": Self::tools() }),
331 "tools/call" => {
332 let Some(name) = params.get("name").and_then(Value::as_str) else {
333 return error(-32602, "tools/call needs a name".into());
334 };
335 if !Self::tools().as_array().is_some_and(|tools| tools.iter().any(|t| t["name"] == name)) {
336 return error(-32602, format!("there is no tool {name:?}"));
337 }
338 match self.call(name, params.get("arguments").unwrap_or(&empty)) {
341 Ok(value) => json!({ "content": [{ "type": "text", "text": value.to_string() }], "structuredContent": value, "isError": false }),
342 Err(why) => json!({ "content": [{ "type": "text", "text": why }], "isError": true }),
343 }
344 }
345 other => return error(-32601, format!("method {other:?} is not supported")),
346 };
347 Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
348 }
349
350 pub fn serve(&self, mut input: impl BufRead, mut output: impl Write) -> kute::Result<u64> {
352 let mut answered = 0;
353 loop {
354 let mut line = Vec::new();
355 let read = (&mut input).take(self.limits.max_request_bytes + 1).read_until(b'\n', &mut line)?;
356 if read == 0 {
357 return Ok(answered);
358 }
359 let reply = if line.len() as u64 > self.limits.max_request_bytes && !line.ends_with(b"\n") {
360 let message = format!("the request is longer than {} bytes", self.limits.max_request_bytes);
363 serde_json::to_writer(&mut output, &json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": message } }))?;
364 output.write_all(b"\n")?;
365 output.flush()?;
366 return Err(KuteError::LimitExceeded("an MCP request exceeded the request limit".into()));
367 } else if line.iter().all(u8::is_ascii_whitespace) {
368 continue;
369 } else {
370 match serde_json::from_slice::<Value>(&line) {
371 Ok(request) if request.is_object() => self.handle(&request),
372 Ok(_) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": "a request must be one JSON object; batches are not supported" } })),
373 Err(e) => Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": format!("not JSON: {e}") } })),
374 }
375 };
376 if let Some(reply) = reply {
377 serde_json::to_writer(&mut output, &reply)?;
378 output.write_all(b"\n")?;
379 output.flush()?;
380 answered += 1;
381 }
382 }
383 }
384}