1use std::collections::{BTreeMap, BTreeSet};
2
3use chrono::DateTime;
4use rmcp::ErrorData;
5use rmcp::model::Tool;
6use serde_json::{Map, Value, json};
7
8use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput};
9use crate::tool_defs::tool_def;
10
11const DEFAULT_MAX_ITEMS: usize = 5;
12const MAX_ITEMS_LIMIT: usize = 1_000;
13const MAX_STRING_CHARS: usize = 160;
14const MAX_ARRAY_VALUES_TO_FLATTEN: usize = 10;
15const ANOMALY_KEYWORDS: &[&str] = &[
16 "error",
17 "warning",
18 "warn",
19 "fail",
20 "critical",
21 "timeout",
22 "timed out",
23 "exception",
24 "panic",
25];
26
27pub struct CtxCrushTool;
28
29impl McpTool for CtxCrushTool {
30 fn name(&self) -> &'static str {
31 "ctx_crush"
32 }
33
34 fn tool_def(&self) -> Tool {
35 tool_def(
36 "ctx_crush",
37 "Compress JSON arrays, nested JSON objects, and logs while preserving schema, anomalies, and representative samples.",
38 json!({
39 "type": "object",
40 "properties": {
41 "content": {
42 "type": "string",
43 "description": "JSON, log output, or structured text to compress"
44 },
45 "mode": {
46 "type": "string",
47 "enum": ["auto", "json", "array", "log"],
48 "default": "auto",
49 "description": "Input type; auto detects JSON arrays, JSON objects, and log text"
50 },
51 "keep_anomalies": {
52 "type": "boolean",
53 "default": true,
54 "description": "Keep entries containing errors, warnings, failures, critical events, timeouts, or exceptions"
55 },
56 "max_items": {
57 "type": "integer",
58 "minimum": 1,
59 "maximum": 1000,
60 "default": 5,
61 "description": "Maximum normal sample entries; anomaly entries are retained in addition"
62 }
63 },
64 "required": ["content"]
65 }),
66 )
67 }
68
69 fn handle(
70 &self,
71 args: &Map<String, Value>,
72 _ctx: &ToolContext,
73 ) -> Result<ToolOutput, ErrorData> {
74 let content = required_string(args, "content")?;
75 let mode = optional_mode(args)?;
76 let keep_anomalies = optional_bool(args, "keep_anomalies", true)?;
77 let max_items = optional_max_items(args)?;
78 let result = crush(content, mode, keep_anomalies, max_items)?;
79
80 let response = json!({
81 "compressed": result.compressed,
82 "stats": {
83 "original_tokens": result.original_tokens,
84 "compressed_tokens": result.compressed_tokens,
85 "ratio": result.ratio,
86 "items_total": result.items_total,
87 "items_shown": result.items_shown,
88 "anomalies_found": result.anomalies_found,
89 "delta_encoded": result.delta_encoded,
90 }
91 })
92 .to_string();
93
94 Ok(ToolOutput::with_savings(
95 response,
96 result.original_tokens,
97 result
98 .original_tokens
99 .saturating_sub(result.compressed_tokens),
100 ))
101 }
102
103 fn produces_machine_readable(&self, _args: Option<&Map<String, Value>>) -> bool {
104 true
105 }
106}
107
108#[derive(Clone, Copy, Debug, Eq, PartialEq)]
109enum CrushMode {
110 Auto,
111 Json,
112 Array,
113 Log,
114}
115
116struct CrushResult {
117 compressed: String,
118 original_tokens: usize,
119 compressed_tokens: usize,
120 ratio: f64,
121 items_total: usize,
122 items_shown: usize,
123 anomalies_found: usize,
124 delta_encoded: bool,
125}
126
127struct RenderedContent {
128 text: String,
129 items_total: usize,
130 items_shown: usize,
131 anomalies_found: usize,
132 delta_encoded: bool,
133}
134
135#[derive(Clone, Copy, Debug, Eq, PartialEq)]
136pub enum SequentialDirection {
137 Ascending,
138 Descending,
139}
140
141pub type Direction = SequentialDirection;
142
143#[derive(Clone, Debug, PartialEq)]
144pub struct SequentialPattern {
145 pub key_field: String,
146 pub direction: SequentialDirection,
147 pub step: f64,
148}
149
150#[derive(Clone, Debug, PartialEq)]
151pub struct DeltaResult {
152 pub header: String,
153 pub deltas: Vec<String>,
154 pub original_tokens: u64,
155 pub compressed_tokens: u64,
156}
157
158#[derive(Clone, Debug)]
159struct SchemaCompressedField {
160 name: String,
161 types: String,
162 values: usize,
163 samples: Vec<String>,
164}
165
166fn required_string<'a>(args: &'a Map<String, Value>, key: &str) -> Result<&'a str, ErrorData> {
167 args.get(key)
168 .and_then(Value::as_str)
169 .ok_or_else(|| ErrorData::invalid_params(format!("{key} must be a string"), None))
170}
171
172fn optional_mode(args: &Map<String, Value>) -> Result<CrushMode, ErrorData> {
173 let Some(value) = args.get("mode") else {
174 return Ok(CrushMode::Auto);
175 };
176 match value.as_str() {
177 Some("auto") => Ok(CrushMode::Auto),
178 Some("json") => Ok(CrushMode::Json),
179 Some("array") => Ok(CrushMode::Array),
180 Some("log") => Ok(CrushMode::Log),
181 _ => Err(ErrorData::invalid_params(
182 "mode must be one of: auto, json, array, log",
183 None,
184 )),
185 }
186}
187
188fn optional_bool(args: &Map<String, Value>, key: &str, default: bool) -> Result<bool, ErrorData> {
189 match args.get(key) {
190 None => Ok(default),
191 Some(Value::Bool(value)) => Ok(*value),
192 Some(_) => Err(ErrorData::invalid_params(
193 format!("{key} must be a boolean"),
194 None,
195 )),
196 }
197}
198
199fn optional_max_items(args: &Map<String, Value>) -> Result<usize, ErrorData> {
200 let Some(value) = args.get("max_items") else {
201 return Ok(DEFAULT_MAX_ITEMS);
202 };
203 let Some(value) = value.as_u64() else {
204 return Err(ErrorData::invalid_params(
205 "max_items must be an unsigned 32-bit integer",
206 None,
207 ));
208 };
209 let Ok(value) = u32::try_from(value) else {
210 return Err(ErrorData::invalid_params(
211 "max_items must be an unsigned 32-bit integer",
212 None,
213 ));
214 };
215 let value = value as usize;
216 if value == 0 || value > MAX_ITEMS_LIMIT {
217 return Err(ErrorData::invalid_params(
218 format!("max_items must be between 1 and {MAX_ITEMS_LIMIT}"),
219 None,
220 ));
221 }
222 Ok(value)
223}
224
225fn crush(
226 content: &str,
227 mode: CrushMode,
228 keep_anomalies: bool,
229 max_items: usize,
230) -> Result<CrushResult, ErrorData> {
231 let rendered = match mode {
232 CrushMode::Log => crush_logs(content, keep_anomalies, max_items),
233 CrushMode::Array => {
234 let value = parse_json(content, "array")?;
235 let Value::Array(values) = value else {
236 return Err(ErrorData::invalid_params(
237 "content must be a JSON array",
238 None,
239 ));
240 };
241 crush_array(&values, keep_anomalies, max_items)
242 }
243 CrushMode::Json => crush_json(parse_json(content, "json")?, keep_anomalies, max_items),
244 CrushMode::Auto => match serde_json::from_str(content) {
245 Ok(value) => crush_json(value, keep_anomalies, max_items),
246 Err(_) => crush_logs(content, keep_anomalies, max_items),
247 },
248 };
249
250 let original_tokens = crate::core::tokens::count_tokens(content);
251 let compressed_tokens = crate::core::tokens::count_tokens(&rendered.text);
252 let ratio = if original_tokens == 0 {
253 1.0
254 } else {
255 compressed_tokens as f64 / original_tokens as f64
256 };
257
258 Ok(CrushResult {
259 compressed: rendered.text,
260 original_tokens,
261 compressed_tokens,
262 ratio,
263 items_total: rendered.items_total,
264 items_shown: rendered.items_shown,
265 anomalies_found: rendered.anomalies_found,
266 delta_encoded: rendered.delta_encoded,
267 })
268}
269
270fn parse_json(content: &str, expected: &str) -> Result<Value, ErrorData> {
271 serde_json::from_str(content).map_err(|error| {
272 ErrorData::invalid_params(
273 format!("content must be valid JSON for mode={expected}: {error}"),
274 None,
275 )
276 })
277}
278
279fn crush_json(value: Value, keep_anomalies: bool, max_items: usize) -> RenderedContent {
280 match value {
281 Value::Array(values) => crush_array(&values, keep_anomalies, max_items),
282 Value::Object(object) => crush_object(&object),
283 scalar => {
284 let text = format!(
285 "value = {}\n[JSON scalar preserved]",
286 render_scalar(&scalar)
287 );
288 RenderedContent {
289 text,
290 items_total: 1,
291 items_shown: 1,
292 anomalies_found: usize::from(value_has_anomaly(&scalar)),
293 delta_encoded: false,
294 }
295 }
296 }
297}
298
299fn crush_array(values: &[Value], keep_anomalies: bool, max_items: usize) -> RenderedContent {
300 if values.iter().all(Value::is_object) {
301 if let Some(pattern) = is_sequential(values) {
302 return crush_sequential_array(values, &pattern);
303 }
304 return crush_object_array(values, keep_anomalies, max_items);
305 }
306 crush_generic_array(values, keep_anomalies, max_items)
307}
308
309fn crush_object_array(values: &[Value], keep_anomalies: bool, max_items: usize) -> RenderedContent {
310 let total = values.len();
311 let anomalies: BTreeSet<usize> = values
312 .iter()
313 .enumerate()
314 .filter_map(|(index, value)| value_has_anomaly(value).then_some(index))
315 .collect();
316 let constant_fields = constant_fields(values);
317 let mut shown = if total > 10 {
318 sample_indices(total, max_items, true)
319 } else {
320 (0..total).collect()
321 };
322 if keep_anomalies {
323 shown.extend(anomalies.iter().copied());
324 }
325
326 let schema_count = if total > 10 { 1 } else { total.min(2) };
327 let mut lines = Vec::new();
328 if schema_count == 0 {
329 lines.push("schema: []".to_string());
330 } else {
331 lines.push(format!("schema ({schema_count} of {total}):"));
332 for (index, value) in values.iter().enumerate().take(schema_count) {
333 lines.push(format!(
334 "#{} {}",
335 index + 1,
336 compact_sample_object(value, &constant_fields)
337 ));
338 }
339 }
340
341 if !constant_fields.is_empty() {
342 lines.push("constants:".to_string());
343 for (field, value, count) in &constant_fields {
344 lines.push(format!(" {field}={value} ({count}/{total})"));
345 }
346 }
347
348 let sample_indices: Vec<usize> = shown
349 .iter()
350 .copied()
351 .filter(|index| *index >= schema_count)
352 .collect();
353 if !sample_indices.is_empty() {
354 lines.push("samples:".to_string());
355 for index in sample_indices {
356 let rendered = if anomalies.contains(&index) {
357 compact_json(&values[index])
358 } else {
359 compact_sample_object(&values[index], &constant_fields)
360 };
361 lines.push(format!("#{} {rendered}", index + 1));
362 }
363 }
364 lines.push(format!(
365 "[{total} items, {} shown, schema preserved]",
366 shown.len()
367 ));
368
369 RenderedContent {
370 text: lines.join("\n"),
371 items_total: total,
372 items_shown: shown.len(),
373 anomalies_found: anomalies.len(),
374 delta_encoded: false,
375 }
376}
377
378fn crush_sequential_array(values: &[Value], pattern: &SequentialPattern) -> RenderedContent {
379 let schema_fields = schema_compressed_fields(values, pattern);
380 let schema_field_names: BTreeSet<String> = schema_fields
381 .iter()
382 .map(|field| field.name.clone())
383 .collect();
384 let delta = delta_compress_with_schema(values, pattern, &schema_field_names);
385 let anomalies_found = values
386 .iter()
387 .filter(|value| value_has_anomaly(value))
388 .count();
389
390 let mut lines = Vec::with_capacity(delta.deltas.len() + schema_fields.len() + 2);
391 lines.push(delta.header);
392 lines.extend(delta.deltas);
393 if !schema_fields.is_empty() {
394 let fields = schema_fields
395 .iter()
396 .map(|field| {
397 let samples = field.samples.join(", ");
398 format!(
399 "{}:{} ({} values; samples {samples})",
400 field.name, field.types, field.values
401 )
402 })
403 .collect::<Vec<_>>()
404 .join("; ");
405 lines.push(format!("[schema-compressed varying fields: {fields}]"));
406 }
407 lines.push(format!(
408 "[{} items total, {} delta entries, {anomalies_found} anomalies retained]",
409 values.len(),
410 values.len().saturating_sub(1)
411 ));
412
413 RenderedContent {
414 text: lines.join("\n"),
415 items_total: values.len(),
416 items_shown: values.len(),
417 anomalies_found,
418 delta_encoded: true,
419 }
420}
421
422pub fn is_sequential(items: &[Value]) -> Option<SequentialPattern> {
424 if items.len() < 5 || !items.iter().all(Value::is_object) {
425 return None;
426 }
427
428 let mut patterns: Vec<SequentialPattern> = shared_object_fields(items)
429 .into_iter()
430 .filter_map(|field| sequential_pattern_for_field(items, &field))
431 .collect();
432 patterns.sort_by(|left, right| {
433 sequence_key_rank(&left.key_field)
434 .cmp(&sequence_key_rank(&right.key_field))
435 .then_with(|| left.key_field.cmp(&right.key_field))
436 });
437 patterns.into_iter().next()
438}
439
440pub fn delta_compress(items: &[Value], pattern: &SequentialPattern) -> DeltaResult {
442 delta_compress_with_schema(items, pattern, &BTreeSet::new())
443}
444
445fn delta_compress_with_schema(
446 items: &[Value],
447 pattern: &SequentialPattern,
448 schema_compressed: &BTreeSet<String>,
449) -> DeltaResult {
450 let base = items
451 .first()
452 .map(compact_json)
453 .unwrap_or_else(|| "[]".to_string());
454 let header = format!(
455 "[DELTA base={base}; key={} {}; step={}; count={}]",
456 pattern.key_field,
457 direction_name(pattern.direction),
458 format_number(pattern.step),
459 items.len()
460 );
461 let sequential_fields = sequential_field_names(items, pattern);
462
463 let anomaly_indices: Vec<usize> = items
464 .iter()
465 .enumerate()
466 .filter(|(_, item)| value_has_anomaly(item))
467 .map(|(index, _)| index)
468 .collect();
469
470 let non_anomaly_deltas_all_predictable = items.len() > 5
471 && anomaly_indices.len() <= items.len() / 4
472 && non_anomaly_fields_are_predictable(items, &sequential_fields, schema_compressed);
473
474 let mut deltas = Vec::new();
475
476 if non_anomaly_deltas_all_predictable {
477 let varying = collect_varying_field_ranges(items, &sequential_fields, schema_compressed);
478 if !varying.is_empty() {
479 deltas.push(format!("varying: {}", varying.join(", ")));
480 }
481 for &index in &anomaly_indices {
482 deltas.push(format!("#{}: {}", index + 1, compact_json(&items[index])));
483 }
484 } else {
485 for index in 1..items.len() {
486 let previous = items[index - 1]
487 .as_object()
488 .expect("delta encoding requires object entries");
489 let current = items[index]
490 .as_object()
491 .expect("delta encoding requires object entries");
492 let preserve_schema_fields =
493 value_has_anomaly(&items[index - 1]) || value_has_anomaly(&items[index]);
494 let mut changes = Vec::new();
495
496 for field in &sequential_fields {
497 let (Some(previous), Some(current)) = (previous.get(field), current.get(field))
498 else {
499 continue;
500 };
501 if previous != current {
502 changes.push(format!(
503 "{field}:{}",
504 render_sequence_delta(previous, current)
505 ));
506 }
507 }
508
509 let mut other_fields = object_field_union(previous, current);
510 other_fields.retain(|field| !sequential_fields.contains(field));
511 for field in other_fields {
512 if schema_compressed.contains(&field) && !preserve_schema_fields {
513 continue;
514 }
515 let previous = previous.get(&field);
516 let current = current.get(&field);
517 if previous != current {
518 changes.push(format!(
519 "{field}:{}->{}",
520 render_optional_scalar(previous),
521 render_optional_scalar(current)
522 ));
523 }
524 }
525
526 deltas.push(format!("D{index}: {{{}}}", changes.join(",")));
527 }
528 }
529
530 let original = compact_json(&Value::Array(items.to_vec()));
531 let mut compressed = Vec::with_capacity(deltas.len() + 1);
532 compressed.push(header.clone());
533 compressed.extend(deltas.iter().cloned());
534 DeltaResult {
535 header,
536 deltas,
537 original_tokens: token_count_u64(&original),
538 compressed_tokens: token_count_u64(&compressed.join("\n")),
539 }
540}
541
542fn non_anomaly_fields_are_predictable(
543 items: &[Value],
544 sequential_fields: &[String],
545 schema_compressed: &BTreeSet<String>,
546) -> bool {
547 for index in 1..items.len() {
548 if value_has_anomaly(&items[index]) || value_has_anomaly(&items[index - 1]) {
549 continue;
550 }
551 let (Some(prev), Some(curr)) = (items[index - 1].as_object(), items[index].as_object())
552 else {
553 return false;
554 };
555 for (field, current_val) in curr {
556 if sequential_fields.contains(field) || schema_compressed.contains(field) {
557 continue;
558 }
559 let prev_val = prev.get(field);
560 if prev_val != Some(current_val) && prev_val.is_some() {
561 return false;
562 }
563 }
564 }
565 true
566}
567
568fn collect_varying_field_ranges(
569 items: &[Value],
570 sequential_fields: &[String],
571 schema_compressed: &BTreeSet<String>,
572) -> Vec<String> {
573 let Some(first) = items.first().and_then(Value::as_object) else {
574 return Vec::new();
575 };
576 let Some(last) = items.last().and_then(Value::as_object) else {
577 return Vec::new();
578 };
579 let mut ranges = Vec::new();
580 for (field, first_val) in first {
581 if sequential_fields.contains(field) || schema_compressed.contains(field) {
582 continue;
583 }
584 if let Some(last_val) = last.get(field) {
585 if first_val != last_val {
586 ranges.push(format!(
587 "{field}=[{}..{}]",
588 render_optional_scalar(Some(first_val)),
589 render_optional_scalar(Some(last_val))
590 ));
591 }
592 }
593 }
594 ranges
595}
596
597fn shared_object_fields(items: &[Value]) -> BTreeSet<String> {
598 let Some(first) = items.first().and_then(Value::as_object) else {
599 return BTreeSet::new();
600 };
601 let mut fields: BTreeSet<String> = first.keys().cloned().collect();
602 for item in &items[1..] {
603 let Some(object) = item.as_object() else {
604 return BTreeSet::new();
605 };
606 fields.retain(|field| object.contains_key(field));
607 }
608 fields
609}
610
611fn sequential_pattern_for_field(items: &[Value], field: &str) -> Option<SequentialPattern> {
612 let values: Vec<&Value> = items
613 .iter()
614 .map(|item| item.as_object()?.get(field))
615 .collect::<Option<_>>()?;
616 let numbers = values
617 .iter()
618 .map(|value| numeric_value(value))
619 .collect::<Option<Vec<_>>>();
620 let timestamps = values
621 .iter()
622 .map(|value| timestamp_value(value))
623 .collect::<Option<Vec<_>>>();
624
625 let (direction, step) = numbers
626 .as_deref()
627 .and_then(sequence_step)
628 .or_else(|| timestamps.as_deref().and_then(sequence_step))?;
629 Some(SequentialPattern {
630 key_field: field.to_string(),
631 direction,
632 step,
633 })
634}
635
636fn sequence_step(values: &[f64]) -> Option<(SequentialDirection, f64)> {
637 let (&first, &second) = values.first().zip(values.get(1))?;
638 let difference = second - first;
639 if !difference.is_finite() || difference == 0.0 {
640 return None;
641 }
642 let step = difference.abs();
643 if values
644 .windows(2)
645 .all(|pair| approximately_equal(pair[1] - pair[0], difference))
646 {
647 Some((
648 if difference.is_sign_positive() {
649 SequentialDirection::Ascending
650 } else {
651 SequentialDirection::Descending
652 },
653 step,
654 ))
655 } else {
656 None
657 }
658}
659
660fn approximately_equal(left: f64, right: f64) -> bool {
661 (left - right).abs() <= 1e-9 * left.abs().max(right.abs()).max(1.0)
662}
663
664fn timestamp_value(value: &Value) -> Option<f64> {
665 let timestamp = DateTime::parse_from_rfc3339(value.as_str()?).ok()?;
666 Some(timestamp.timestamp() as f64 + f64::from(timestamp.timestamp_subsec_nanos()) / 1e9)
667}
668
669fn numeric_value(value: &Value) -> Option<f64> {
670 value
671 .as_f64()
672 .or_else(|| value.as_str()?.parse::<f64>().ok())
673 .filter(|value| value.is_finite())
674}
675
676fn sequence_key_rank(field: &str) -> u8 {
677 let lower = field.to_ascii_lowercase();
678 u8::from(
679 ![
680 "id",
681 "timestamp",
682 "time",
683 "date",
684 "ts",
685 "counter",
686 "count",
687 "sequence",
688 "seq",
689 "index",
690 ]
691 .iter()
692 .any(|hint| lower == *hint || lower.contains(hint)),
693 )
694}
695
696fn direction_name(direction: SequentialDirection) -> &'static str {
697 match direction {
698 SequentialDirection::Ascending => "ascending",
699 SequentialDirection::Descending => "descending",
700 }
701}
702
703fn sequential_field_names(items: &[Value], pattern: &SequentialPattern) -> Vec<String> {
704 let mut fields: BTreeSet<String> = shared_object_fields(items)
705 .into_iter()
706 .filter(|field| sequential_pattern_for_field(items, field).is_some())
707 .collect();
708 fields.insert(pattern.key_field.clone());
709
710 let mut ordered = vec![pattern.key_field.clone()];
711 ordered.extend(
712 fields
713 .into_iter()
714 .filter(|field| field != &pattern.key_field),
715 );
716 ordered
717}
718
719fn schema_compressed_fields(
720 items: &[Value],
721 pattern: &SequentialPattern,
722) -> Vec<SchemaCompressedField> {
723 let sequential_fields: BTreeSet<String> =
724 sequential_field_names(items, pattern).into_iter().collect();
725 let mut result = Vec::new();
726
727 for field in object_fields(items) {
728 if sequential_fields.contains(&field) {
729 continue;
730 }
731 let values: Vec<&Value> = items
732 .iter()
733 .filter_map(|item| item.as_object()?.get(&field))
734 .collect();
735 let unique: BTreeSet<String> = values.iter().map(|value| compact_json(value)).collect();
736 if values.len() < 3 || unique.len() < 3 || unique.len() * 5 < values.len() * 4 {
737 continue;
738 }
739
740 let types: BTreeSet<&str> = values.iter().map(|value| value_kind(value)).collect();
741 let mut samples = Vec::new();
742 if let Some(first) = values.first() {
743 samples.push(compact_json(first));
744 }
745 if let Some(last) = values.last() {
746 let last = compact_json(last);
747 if samples.last() != Some(&last) {
748 samples.push(last);
749 }
750 }
751 result.push(SchemaCompressedField {
752 name: field,
753 types: types.into_iter().collect::<Vec<_>>().join("|"),
754 values: values.len(),
755 samples,
756 });
757 }
758 result
759}
760
761fn object_fields(items: &[Value]) -> BTreeSet<String> {
762 items
763 .iter()
764 .filter_map(Value::as_object)
765 .flat_map(|object| object.keys().cloned())
766 .collect()
767}
768
769fn object_field_union(
770 previous: &Map<String, Value>,
771 current: &Map<String, Value>,
772) -> BTreeSet<String> {
773 previous.keys().chain(current.keys()).cloned().collect()
774}
775
776fn value_kind(value: &Value) -> &'static str {
777 match value {
778 Value::Null => "null",
779 Value::Bool(_) => "bool",
780 Value::Number(_) => "number",
781 Value::String(_) => "string",
782 Value::Array(_) => "array",
783 Value::Object(_) => "object",
784 }
785}
786
787fn render_sequence_delta(previous: &Value, current: &Value) -> String {
788 if let (Some(previous), Some(current)) = (numeric_value(previous), numeric_value(current)) {
789 return format_signed_number(current - previous);
790 }
791 if let (Some(previous), Some(current)) = (timestamp_value(previous), timestamp_value(current)) {
792 return format!("{}s", format_signed_number(current - previous));
793 }
794 format!("{}->{}", render_scalar(previous), render_scalar(current))
795}
796
797fn render_optional_scalar(value: Option<&Value>) -> String {
798 value.map_or_else(|| "<absent>".to_string(), render_scalar)
799}
800
801fn format_signed_number(value: f64) -> String {
802 if value >= 0.0 {
803 format!("+{}", format_number(value))
804 } else {
805 format_number(value)
806 }
807}
808
809fn format_number(value: f64) -> String {
810 if value == 0.0 {
811 return "0".to_string();
812 }
813 if value.fract() == 0.0 {
814 return format!("{value:.0}");
815 }
816 value.to_string()
817}
818
819fn token_count_u64(text: &str) -> u64 {
820 u64::try_from(crate::core::tokens::count_tokens(text)).unwrap_or(u64::MAX)
821}
822
823fn crush_generic_array(
824 values: &[Value],
825 keep_anomalies: bool,
826 max_items: usize,
827) -> RenderedContent {
828 let total = values.len();
829 let anomalies: BTreeSet<usize> = values
830 .iter()
831 .enumerate()
832 .filter_map(|(index, value)| value_has_anomaly(value).then_some(index))
833 .collect();
834 let mut shown = if total > 10 {
835 sample_indices(total, max_items, false)
836 } else {
837 (0..total).collect()
838 };
839 if keep_anomalies {
840 shown.extend(anomalies.iter().copied());
841 }
842
843 let mut lines = vec!["array samples:".to_string()];
844 for index in &shown {
845 lines.push(format!("#{} {}", index + 1, compact_json(&values[*index])));
846 }
847 lines.push(format!(
848 "[{total} items total, {} shown, representative sample preserved]",
849 shown.len()
850 ));
851
852 RenderedContent {
853 text: lines.join("\n"),
854 items_total: total,
855 items_shown: shown.len(),
856 anomalies_found: anomalies.len(),
857 delta_encoded: false,
858 }
859}
860
861fn sample_indices(total: usize, max_items: usize, preserve_schema: bool) -> BTreeSet<usize> {
862 if total == 0 {
863 return BTreeSet::new();
864 }
865
866 let minimum = if preserve_schema { total.min(2) } else { 1 };
867 let mut capacity = max_items.max(minimum).min(total);
868 if total > capacity {
869 let boundary_count = if preserve_schema {
870 total.min(4)
871 } else {
872 total.min(2)
873 };
874 capacity = capacity.max(boundary_count);
875 }
876 if total <= capacity {
877 return (0..total).collect();
878 }
879
880 let mut selected = BTreeSet::new();
881 if preserve_schema {
882 selected.insert(0);
883 if total > 1 {
884 selected.insert(1);
885 }
886 } else {
887 selected.insert(0);
888 }
889 selected.insert(total - 1);
890 if preserve_schema && total > 2 {
891 selected.insert(total - 2);
892 }
893
894 let needed = capacity.saturating_sub(selected.len());
895 let start = if preserve_schema { 2 } else { 1 };
896 let end = if preserve_schema {
897 total.saturating_sub(2)
898 } else {
899 total.saturating_sub(1)
900 };
901 for slot in 1..=needed {
902 let span = end.saturating_sub(start);
903 let index = start + (span * slot / (needed + 1));
904 selected.insert(index);
905 }
906 for index in start..end {
907 if selected.len() >= capacity {
908 break;
909 }
910 selected.insert(index);
911 }
912 selected
913}
914
915fn constant_fields(values: &[Value]) -> Vec<(String, String, usize)> {
916 let total = values.len();
917 let mut fields: BTreeMap<String, BTreeMap<String, usize>> = BTreeMap::new();
918
919 for value in values {
920 let Some(object) = value.as_object() else {
921 continue;
922 };
923 for (field, value) in object {
924 if value.is_null() || value.as_str().is_some_and(|text| text.trim().is_empty()) {
925 continue;
926 }
927 if value.is_object() || value.is_array() {
928 continue;
929 }
930 *fields
931 .entry(field.clone())
932 .or_default()
933 .entry(compact_json(value))
934 .or_default() += 1;
935 }
936 }
937
938 fields
939 .into_iter()
940 .filter_map(|(field, values)| {
941 values.into_iter().find_map(|(value, count)| {
942 ((count as f64 / total.max(1) as f64) > 0.8).then_some((
943 field.clone(),
944 value,
945 count,
946 ))
947 })
948 })
949 .collect()
950}
951
952fn compact_sample_object(value: &Value, constant_fields: &[(String, String, usize)]) -> String {
953 let Some(object) = value.as_object() else {
954 return compact_json(value);
955 };
956 let mut compacted = object.clone();
957 for (field, _, _) in constant_fields {
958 compacted.remove(field);
959 }
960 compact_json(&Value::Object(compacted))
961}
962
963fn crush_object(object: &Map<String, Value>) -> RenderedContent {
964 let mut lines = Vec::new();
965 flatten_value("", &Value::Object(object.clone()), &mut lines);
966 let shown = lines.len();
967 lines.push(format!("[object flattened: {shown} values shown]"));
968
969 RenderedContent {
970 text: lines.join("\n"),
971 items_total: 1,
972 items_shown: 1,
973 anomalies_found: usize::from(value_has_anomaly(&Value::Object(object.clone()))),
974 delta_encoded: false,
975 }
976}
977
978fn flatten_value(path: &str, value: &Value, lines: &mut Vec<String>) {
979 match value {
980 Value::Null => {}
981 Value::String(text) if text.trim().is_empty() => {}
982 Value::Object(object) => {
983 for (key, value) in object {
984 let child_path = if path.is_empty() {
985 key.clone()
986 } else {
987 format!("{path}.{key}")
988 };
989 flatten_value(&child_path, value, lines);
990 }
991 }
992 Value::Array(values) => {
993 if values.is_empty() {
994 return;
995 }
996 let shown = values.len().min(MAX_ARRAY_VALUES_TO_FLATTEN);
997 if shown < values.len() {
998 lines.push(format!(
999 "{path} = [{} items; first {shown} shown]",
1000 values.len()
1001 ));
1002 }
1003 for (index, value) in values.iter().take(shown).enumerate() {
1004 flatten_value(&format!("{path}[{index}]"), value, lines);
1005 }
1006 }
1007 scalar => lines.push(format!("{path} = {}", render_scalar(scalar))),
1008 }
1009}
1010
1011fn render_scalar(value: &Value) -> String {
1012 match value {
1013 Value::String(text) => compact_json(&Value::String(abbreviate(text))),
1014 _ => compact_json(value),
1015 }
1016}
1017
1018fn abbreviate(text: &str) -> String {
1019 let length = text.chars().count();
1020 if length <= MAX_STRING_CHARS {
1021 return text.to_string();
1022 }
1023 let prefix: String = text.chars().take(MAX_STRING_CHARS).collect();
1024 format!("{prefix}… (+{} chars)", length - MAX_STRING_CHARS)
1025}
1026
1027fn compact_json(value: &Value) -> String {
1028 serde_json::to_string(value).unwrap_or_else(|_| "<unserializable JSON>".to_string())
1029}
1030
1031fn crush_logs(content: &str, keep_anomalies: bool, max_items: usize) -> RenderedContent {
1032 let mut groups = Vec::<LogGroup>::new();
1033 let mut positions = BTreeMap::<String, usize>::new();
1034 let mut anomalies_found = 0;
1035
1036 for line in content
1037 .lines()
1038 .map(str::trim)
1039 .filter(|line| !line.is_empty())
1040 {
1041 let anomaly = text_has_anomaly(line);
1042 anomalies_found += usize::from(anomaly);
1043 let pattern = log_pattern(line);
1044 if let Some(index) = positions.get(&pattern) {
1045 groups[*index].count += 1;
1046 groups[*index].anomaly |= anomaly;
1047 } else {
1048 positions.insert(pattern, groups.len());
1049 groups.push(LogGroup {
1050 line: line.to_string(),
1051 count: 1,
1052 anomaly,
1053 });
1054 }
1055 }
1056
1057 let normal_indices: Vec<usize> = groups
1058 .iter()
1059 .enumerate()
1060 .filter_map(|(index, group)| (!group.anomaly || !keep_anomalies).then_some(index))
1061 .collect();
1062 let mut shown: BTreeSet<usize> = sample_positions(&normal_indices, max_items);
1063 if keep_anomalies {
1064 shown.extend(
1065 groups
1066 .iter()
1067 .enumerate()
1068 .filter_map(|(index, group)| group.anomaly.then_some(index)),
1069 );
1070 }
1071
1072 let mut lines = vec!["log samples:".to_string()];
1073 for index in &shown {
1074 let group = &groups[*index];
1075 let suffix = (group.count > 1).then(|| format!(" [x{}]", group.count));
1076 lines.push(format!("{}{}", group.line, suffix.unwrap_or_default()));
1077 }
1078 let total_lines: usize = groups.iter().map(|group| group.count).sum();
1079 let collapsed = total_lines.saturating_sub(groups.len());
1080 lines.push(format!(
1081 "[{total_lines} lines total, {} patterns shown, {collapsed} duplicate lines collapsed]",
1082 shown.len()
1083 ));
1084
1085 RenderedContent {
1086 text: lines.join("\n"),
1087 items_total: total_lines,
1088 items_shown: shown.len(),
1089 anomalies_found,
1090 delta_encoded: false,
1091 }
1092}
1093
1094struct LogGroup {
1095 line: String,
1096 count: usize,
1097 anomaly: bool,
1098}
1099
1100fn sample_positions(positions: &[usize], max_items: usize) -> BTreeSet<usize> {
1101 if positions.len() <= max_items {
1102 return positions.iter().copied().collect();
1103 }
1104 let sampled = sample_indices(positions.len(), max_items, false);
1105 sampled
1106 .into_iter()
1107 .filter_map(|index| positions.get(index).copied())
1108 .collect()
1109}
1110
1111fn log_pattern(line: &str) -> String {
1112 let mut pattern = String::with_capacity(line.len());
1113 let mut in_digits = false;
1114 for character in line.chars() {
1115 if character.is_ascii_digit() {
1116 if !in_digits {
1117 pattern.push_str("<n>");
1118 in_digits = true;
1119 }
1120 } else {
1121 pattern.push(character);
1122 in_digits = false;
1123 }
1124 }
1125 pattern
1126}
1127
1128fn value_has_anomaly(value: &Value) -> bool {
1129 text_has_anomaly(&compact_json(value))
1130}
1131
1132fn text_has_anomaly(text: &str) -> bool {
1133 let lower = text.to_ascii_lowercase();
1134 ANOMALY_KEYWORDS
1135 .iter()
1136 .any(|keyword| lower.contains(keyword))
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141 use super::*;
1142 use crate::server::tool_trait::McpTool;
1143
1144 fn crush_auto(content: &str) -> CrushResult {
1145 crush(content, CrushMode::Auto, true, DEFAULT_MAX_ITEMS).unwrap()
1146 }
1147
1148 #[test]
1149 fn array_compression_preserves_schema_samples_and_repetitive_fields() {
1150 let values: Vec<Value> = (1..=15)
1151 .map(|id| json!({"id": id * id, "status": "ok", "source": "search"}))
1152 .collect();
1153 let input = serde_json::to_string(&values).unwrap();
1154
1155 let result = crush_auto(&input);
1156
1157 assert!(result.compressed.contains("schema ("));
1158 assert!(result.compressed.contains("status=") && result.compressed.contains("15/15"));
1159 assert!(
1160 result.compressed.contains("[15 items")
1161 && result.compressed.contains("schema preserved]")
1162 );
1163 assert_eq!(result.items_total, 15);
1164 assert_eq!(result.items_shown, 5);
1165 assert!(result.compressed_tokens < result.original_tokens);
1166 }
1167
1168 #[test]
1169 fn sequential_ids_are_detected_with_their_step_and_direction() {
1170 let values: Vec<Value> = (10..15)
1171 .map(|id| json!({"id": id, "status": "ok"}))
1172 .collect();
1173
1174 let pattern = is_sequential(&values).expect("sequential IDs should be detected");
1175
1176 assert_eq!(pattern.key_field, "id");
1177 assert_eq!(pattern.direction, SequentialDirection::Ascending);
1178 assert_eq!(pattern.step, 1.0);
1179 }
1180
1181 #[test]
1182 fn iso_timestamps_are_detected_as_sequential() {
1183 let values: Vec<Value> = (0..5)
1184 .map(|offset| {
1185 json!({"timestamp": format!("2026-08-13T10:{offset:02}:00Z"), "event": "tick"})
1186 })
1187 .collect();
1188
1189 let pattern = is_sequential(&values).expect("regular timestamps should be detected");
1190
1191 assert_eq!(pattern.key_field, "timestamp");
1192 assert_eq!(pattern.direction, SequentialDirection::Ascending);
1193 assert_eq!(pattern.step, 60.0);
1194 }
1195
1196 #[test]
1197 fn delta_compression_is_smaller_than_schema_sampling_for_sequential_entries() {
1198 let values: Vec<Value> = (1..=5)
1199 .map(|id| json!({"id": id, "status": "ok", "ts": id * 100}))
1200 .collect();
1201 let pattern = is_sequential(&values).expect("sequential IDs should be detected");
1202
1203 let delta = delta_compress(&values, &pattern);
1204 let schema = crush_object_array(&values, true, DEFAULT_MAX_ITEMS);
1205
1206 assert!(delta.header.starts_with("[DELTA base={"));
1207 assert!(delta.deltas[0].contains("id:+1"));
1208 assert!(delta.deltas[1].contains("ts:+100"));
1209 assert!(delta.compressed_tokens < token_count_u64(&schema.text));
1210 }
1211
1212 #[test]
1213 fn non_sequential_data_uses_the_existing_schema_compressor() {
1214 let values = json!([
1215 {"id": 1, "status": "ok"},
1216 {"id": 3, "status": "ok"},
1217 {"id": 8, "status": "ok"},
1218 {"id": 14, "status": "ok"},
1219 {"id": 23, "status": "ok"},
1220 {"id": 37, "status": "ok"}
1221 ]);
1222 let input = values.to_string();
1223
1224 let result = crush_auto(&input);
1225
1226 assert!(!result.delta_encoded);
1227 assert!(result.compressed.contains("schema ("));
1228 }
1229
1230 #[test]
1231 fn mixed_sequential_and_random_fields_use_delta_and_schema_compression() {
1232 let values: Vec<Value> = (1..=8)
1233 .map(|id| {
1234 let score = [4, 9, 2, 8, 1, 7, 3, 6][id as usize - 1];
1235 json!({
1236 "id": id,
1237 "status": if id % 2 == 0 { "retry" } else { "ok" },
1238 "request_id": format!("request-{:02x}", id * 37),
1239 "score": score
1240 })
1241 })
1242 .collect();
1243 let input = serde_json::to_string(&values).unwrap();
1244
1245 let result = crush_auto(&input);
1246
1247 assert!(result.delta_encoded);
1248 assert!(
1249 result
1250 .compressed
1251 .contains("D1: {id:+1,status:\"ok\"->\"retry\"}")
1252 );
1253 assert!(
1254 result
1255 .compressed
1256 .contains("[schema-compressed varying fields:")
1257 );
1258 assert!(result.compressed.contains("request_id:string (8 values;"));
1259 assert!(result.compressed.contains("score:number (8 values;"));
1260 }
1261
1262 #[test]
1263 fn object_flattening_omits_empty_values_and_abbreviates_long_strings() {
1264 let input = json!({
1265 "user": {"name": "Ada", "profile": {"bio": "x".repeat(200), "empty": ""}},
1266 "missing": null,
1267 "tags": ["rust", "mcp"]
1268 })
1269 .to_string();
1270
1271 let result = crush_auto(&input);
1272
1273 assert!(result.compressed.contains("user.name = \"Ada\""));
1274 assert!(result.compressed.contains("user.profile.bio ="));
1275 assert!(result.compressed.contains("… (+40 chars)"));
1276 assert!(result.compressed.contains("tags[0] = \"rust\""));
1277 assert!(!result.compressed.contains("missing"));
1278 assert!(!result.compressed.contains("empty"));
1279 }
1280
1281 #[test]
1282 fn anomaly_entries_are_retained_beyond_the_normal_sample_limit() {
1283 let values: Vec<Value> = (1..=20)
1284 .map(|id| {
1285 if id == 9 {
1286 json!({"id": id, "status": "error", "message": "timeout contacting API"})
1287 } else {
1288 json!({"id": id, "status": "ok"})
1289 }
1290 })
1291 .collect();
1292 let input = serde_json::to_string(&values).unwrap();
1293
1294 let result = crush_auto(&input);
1295
1296 assert!(
1297 result.compressed.contains("error") && result.compressed.contains("timeout"),
1298 "anomaly entry with error/timeout must be preserved in output"
1299 );
1300 assert_eq!(result.anomalies_found, 1);
1301 assert!(result.items_shown > DEFAULT_MAX_ITEMS);
1302 }
1303
1304 #[test]
1305 fn log_deduplication_collapses_repeated_patterns_and_keeps_anomalies() {
1306 let input = "INFO worker 101 started\nINFO worker 102 started\nWARN cache miss\nERROR request timed out\n";
1307
1308 let result = crush_auto(input);
1309
1310 assert!(result.compressed.contains("INFO worker 101 started [x2]"));
1311 assert!(result.compressed.contains("WARN cache miss"));
1312 assert!(result.compressed.contains("ERROR request timed out"));
1313 assert!(
1314 result
1315 .compressed
1316 .contains("[4 lines total, 3 patterns shown, 1 duplicate lines collapsed]")
1317 );
1318 assert_eq!(result.anomalies_found, 2);
1319 }
1320
1321 #[test]
1322 fn auto_detection_routes_json_arrays_and_plain_text_to_the_right_compressor() {
1323 let array = crush_auto(r#"[{"kind":"result"},{"kind":"result"}]"#);
1324 let logs = crush_auto("INFO ready\nINFO ready");
1325
1326 assert!(array.compressed.contains("schema ("));
1327 assert!(logs.compressed.starts_with("log samples:"));
1328 }
1329
1330 #[test]
1331 fn schema_and_handler_return_machine_readable_stats() {
1332 let tool = CtxCrushTool;
1333 let schema = serde_json::to_value(tool.tool_def().input_schema).unwrap();
1334 assert_eq!(schema["required"], json!(["content"]));
1335 assert_eq!(schema["properties"]["mode"]["default"], "auto");
1336
1337 let mut args = Map::new();
1338 args.insert("content".to_string(), json!("INFO ready\nINFO ready"));
1339 let output = tool.handle(&args, &ToolContext::default()).unwrap();
1340 let response: Value = serde_json::from_str(&output.text).unwrap();
1341 assert!(response["compressed"].is_string());
1342 assert!(response["stats"]["original_tokens"].is_u64());
1343 assert!(response["stats"]["ratio"].is_number());
1344 assert!(response["stats"]["delta_encoded"].is_boolean());
1345 }
1346
1347 #[test]
1348 fn measure_compression_ratio_20_items() {
1349 let input: Vec<Value> = (1..=20)
1350 .map(|id| {
1351 if id == 4 {
1352 json!({"id": id, "status": "error", "timestamp": "2026-08-13T10:03:00Z", "user": "dave", "action": "login", "error": "timeout"})
1353 } else {
1354 json!({"id": id, "status": "ok", "timestamp": format!("2026-08-13T10:{:02}:00Z", id - 1), "user": format!("user{id}"), "action": "login"})
1355 }
1356 })
1357 .collect();
1358 let json_str = serde_json::to_string(&input).unwrap();
1359 let result = crush_auto(&json_str);
1360 let orig_tokens = json_str.len() / 4;
1361 let compressed_tokens = result.compressed.len() / 4;
1362 let ratio = 1.0 - (compressed_tokens as f64 / orig_tokens as f64);
1363 eprintln!("\n=== ctx_crush Performance ===");
1364 eprintln!(
1365 " Input: {} chars ({} est. tokens)",
1366 json_str.len(),
1367 orig_tokens
1368 );
1369 eprintln!(
1370 " Output: {} chars ({} est. tokens)",
1371 result.compressed.len(),
1372 compressed_tokens
1373 );
1374 eprintln!(" Compression: {:.1}%", ratio * 100.0);
1375 eprintln!(
1376 " Items: {}/{} shown, {} anomalies",
1377 result.items_shown, result.items_total, result.anomalies_found
1378 );
1379 eprintln!(" Headroom SmartCrusher target: 60-95%");
1380 eprintln!("===========================\n");
1381 assert!(
1382 ratio > 0.60,
1383 "should achieve >60% compression on 20-item array (got {:.1}%)",
1384 ratio * 100.0
1385 );
1386 }
1387
1388 #[test]
1389 fn homogeneous_100_items_achieves_seventy_percent() {
1390 let input: Vec<Value> = (1..=100)
1391 .map(|id| {
1392 json!({
1393 "id": id,
1394 "status": "ok",
1395 "region": "eu-west-1",
1396 "timestamp": format!("2026-08-13T{:02}:{:02}:00Z", id / 60, id % 60),
1397 "latency_ms": 42,
1398 "method": "POST",
1399 "path": "/v1/chat/completions"
1400 })
1401 })
1402 .collect();
1403 let json_str = serde_json::to_string(&input).unwrap();
1404 let result = crush_auto(&json_str);
1405 let ratio = 1.0 - (result.compressed.len() as f64 / json_str.len() as f64);
1406 eprintln!(
1407 "\n=== 100-item homogeneous: {:.1}% compression ({} -> {} chars) ===\n",
1408 ratio * 100.0,
1409 json_str.len(),
1410 result.compressed.len()
1411 );
1412 assert!(
1413 ratio > 0.70,
1414 "homogeneous 100-item array should achieve >70% compression (got {:.1}%)",
1415 ratio * 100.0
1416 );
1417 }
1418}