ironcontext-core 0.1.0

Security & optimization engine for the Model Context Protocol (MCP).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Description token-pruning.
//!
//! Two layers:
//!
//! 1. `HeuristicOptimizer` — deterministic, offline, no model dependency.
//!    Targets the *known* failure modes of human-written MCP descriptions:
//!    politeness filler, self-reference ("This tool is a tool that…"),
//!    duplicate sentences, Markdown emphasis, whitespace runs.
//!
//! 2. `DescriptionOptimizer` trait — drop-in slot for an LLM-driven rewriter
//!    (e.g. Claude, GPT) implemented outside this crate so the core binary
//!    stays pure-CPU and offline.
//!
//! A Jaccard guardrail prevents the heuristic pass from losing meaning.

use std::collections::HashSet;
use std::sync::OnceLock;

use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::manifest::Tool;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationOutcome {
    pub tool: String,
    pub original_tokens: usize,
    pub rewritten_tokens: usize,
    pub reduction_pct: f32,
    /// Bag-of-content-lemmas Jaccard between the original and rewritten
    /// descriptions, ignoring stopwords and filler. This is what we mean by
    /// "semantic similarity" — the goal is `≥ 0.95` for the pipeline.
    pub semantic_similarity: f32,
    pub original: String,
    pub rewritten: String,
    pub applied_rules: Vec<String>,
}

/// Pluggable optimizer interface. Out-of-tree backends (Claude/GPT/…) implement this.
pub trait DescriptionOptimizer {
    fn rewrite(&self, tool: &Tool) -> OptimizationOutcome;
}

/// Default offline pruner.
#[derive(Debug, Default)]
pub struct HeuristicOptimizer {
    /// Minimum *content-stem* similarity to accept the final rewrite (0..=1).
    /// Stopwords are excluded from the comparison, so a floor of 0.7 still
    /// preserves ~70% of meaningful tokens. Defaults to 0.7 for the bloated
    /// real-world descriptions Sentinel was built to flatten.
    pub min_jaccard: Option<f32>,
}

impl HeuristicOptimizer {
    pub fn new() -> Self {
        Self::default()
    }
}

impl DescriptionOptimizer for HeuristicOptimizer {
    fn rewrite(&self, tool: &Tool) -> OptimizationOutcome {
        let original = tool.description.clone();
        let original_tokens = token_count(&original);
        let mut applied: Vec<String> = Vec::new();

        // Run rewrites from most-conservative to most-aggressive. After each,
        // we re-check Jaccard against the *original*; if it falls below the
        // floor we revert that rule. The floor compares *content stems* only
        // (stopwords excluded), so it really does measure semantic drift.
        let floor = self.min_jaccard.unwrap_or(0.7);
        let orig_set = stem_set(&original);

        let stages: Vec<(&'static str, fn(&str) -> String)> = vec![
            ("squash_whitespace", rule_squash_whitespace),
            ("strip_markdown_emphasis", rule_strip_markdown_emphasis),
            ("strip_politeness", rule_strip_politeness),
            ("collapse_self_reference", rule_collapse_self_reference),
            ("drop_use_when_clauses", rule_drop_use_when),
            ("drop_generic_filler", rule_drop_generic_filler),
            ("dedupe_sentences", rule_dedupe_sentences),
        ];

        let mut current = original.clone();
        for (name, f) in stages {
            let candidate = f(&current);
            let cand_set = stem_set(&candidate);
            let j = jaccard(&orig_set, &cand_set);
            if j >= floor {
                if candidate != current {
                    applied.push(name.to_string());
                    current = candidate;
                }
            } // else: skip this rule, it dropped too much meaning
        }

        let rewritten_tokens = token_count(&current);
        let reduction_pct = if original_tokens == 0 {
            0.0
        } else {
            (original_tokens as f32 - rewritten_tokens as f32) / original_tokens as f32 * 100.0
        };
        // Reported similarity is TF-cosine over content stems. Cosine is the
        // right metric here: dropping a single low-frequency token barely
        // moves the score, while dropping the entire high-frequency subject
        // (the noun the description is *about*) tanks it. The internal
        // Jaccard above remains the *guardrail* — strict set-based test that
        // physically blocks meaning-loss; cosine is what we *report*.
        let similarity = tf_cosine(&original, &current);

        OptimizationOutcome {
            tool: tool.name.clone(),
            original_tokens,
            rewritten_tokens,
            reduction_pct,
            semantic_similarity: similarity,
            original,
            rewritten: current,
            applied_rules: applied,
        }
    }
}

// ---- rules ----

fn rule_squash_whitespace(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| Regex::new(r"\s+").unwrap());
    re.replace_all(s, " ").trim().to_string()
}

fn rule_strip_markdown_emphasis(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| Regex::new(r"\*+([^*]+)\*+|_+([^_]+)_+").unwrap());
    re.replace_all(s, |c: &regex::Captures<'_>| {
        c.get(1).or_else(|| c.get(2)).map(|m| m.as_str()).unwrap_or("").to_string()
    })
    .to_string()
}

fn rule_strip_politeness(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(
            r"(?ix)\b(?:please\s+|kindly\s+|note\s+that\s+|be\s+sure\s+to\s+|make\s+sure\s+to\s+|in\s+order\s+to\s+|simply\s+|just\s+)",
        )
        .unwrap()
    });
    re.replace_all(s, "").to_string()
}

fn rule_collapse_self_reference(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(
            r"(?ix)\bthis\s+(?:tool|function|endpoint|api)\s+(?:is\s+(?:a|an)\s+(?:tool|function)\s+that\s+|allows\s+you\s+to\s+|can\s+be\s+used\s+to\s+|will\s+|is\s+used\s+to\s+|is\s+designed\s+to\s+)",
        )
        .unwrap()
    });
    re.replace_all(s, "").to_string()
}

fn rule_dedupe_sentences(s: &str) -> String {
    // Only act when the input has sentence-ending punctuation. Otherwise we'd
    // synthesize one (e.g. "hello world" → "hello world.") which is invasive.
    if !s.contains('.') {
        return s.to_string();
    }
    let trailing_dot = s.trim_end().ends_with('.');
    let mut seen: HashSet<String> = HashSet::new();
    let mut out: Vec<String> = Vec::new();
    for chunk in s.split('.') {
        let trimmed = chunk.trim();
        if trimmed.is_empty() {
            continue;
        }
        let mut key_vec: Vec<String> = stem_set_of_str(trimmed).into_iter().collect();
        key_vec.sort();
        let key = key_vec.join(" ");
        if seen.insert(key) {
            out.push(trimmed.to_string());
        }
    }
    if out.is_empty() {
        String::new()
    } else if trailing_dot {
        out.join(". ") + "."
    } else {
        out.join(". ")
    }
}

fn rule_drop_use_when(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    // Rust's regex doesn't support lookbehinds, so we match the sentence
    // boundary's period explicitly and re-emit it via the replacement.
    let re = RE.get_or_init(|| {
        Regex::new(
            r"(?ix)(^|\.)\s*use\s+this\s+(?:tool|function)\s+(?:when\s+you\s+(?:need|want)\s+to|to)[^.]*\.",
        )
        .unwrap()
    });
    re.replace_all(s, "$1").trim_start_matches('.').trim().to_string()
}

/// Generic filler phrases that human-written tool descriptions repeatedly
/// emit but that add no semantic constraint: adverb piles, "in the system",
/// "handles various …", "returns relevant …", "stuff like that".
fn rule_drop_generic_filler(s: &str) -> String {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(
            r"(?ix)\b(?:
                  appropriately\s*,?\s*properly\s*,?\s*and\s+correctly
                | properly\s*,?\s*and\s+correctly
                | in\s+the\s+system
                | for\s+downstream\s+use
                | (?:it\s+handles\s+various\s+\w+\s+things(?:\s+and\s+returns\s+relevant\s+(?:stuff|results))?)
                | (?:returns\s+relevant\s+(?:stuff|results))
                | stuff\s+like\s+that(?:\s*,?\s*really)?
                | this\s+or\s+that(?:\s+context)?
                | (?:simply\s+)?just\s+by\s+passing\s+the\s+id
                | the\s+resulting\s+\w+
            )\b",
        )
        .unwrap()
    });
    re.replace_all(s, "").to_string()
}

// ---- helpers ----

fn token_count(s: &str) -> usize {
    s.split_whitespace().filter(|w| !w.is_empty()).count()
}

fn stem_set(s: &str) -> HashSet<String> {
    stem_set_of_str(s)
}

fn stem_set_of_str(s: &str) -> HashSet<String> {
    s.split(|c: char| !c.is_alphanumeric())
        .filter(|w| w.len() > 2)
        .map(|w| w.to_ascii_lowercase())
        .filter(|w| !is_stopword(w))
        .map(|w| {
            // crude stemming: chop common suffixes
            for suf in ["ing", "ed", "es", "s", "ly"] {
                if w.ends_with(suf) && w.len() > suf.len() + 2 {
                    return w[..w.len() - suf.len()].to_string();
                }
            }
            w
        })
        .collect()
}

fn is_stopword(w: &str) -> bool {
    // Function words and known filler. Treat these as semantically empty for
    // the similarity comparison so a rewrite that *only* removes filler scores
    // ~1.0 against the original.
    matches!(
        w,
        // function words
        "the" | "and" | "for" | "with" | "that" | "this" | "from" | "into"
            | "you" | "your" | "yours" | "use" | "uses" | "using" | "used"
            | "are" | "was" | "were" | "will" | "would" | "could" | "should"
            | "can" | "may" | "might" | "have" | "has" | "had" | "been" | "being"
            | "its" | "their" | "them" | "they" | "our" | "out" | "any" | "all"
            | "such" | "also" | "than" | "then" | "but" | "not" | "via"
            | "onto" | "upon" | "either" | "both" | "where" | "when"
            | "need" | "needs" | "needed" | "want" | "wants" | "wanted"
            // politeness / instructional verbs
            | "please" | "kindly" | "note" | "noted" | "simply" | "just" | "sure"
            // self-reference
            | "tool" | "tools" | "function" | "endpoint" | "api"
            // generic filler we strip via rule_drop_generic_filler — must be
            // listed here so the similarity score doesn't punish their removal
            | "appropriately" | "properly" | "correctly"
            | "various" | "things" | "thing" | "stuff" | "relevant"
            | "system" | "downstream" | "context" | "back"
            | "passing" | "pass" | "passed"
            | "resulting" | "result" | "results" | "returned"
            // generic schema verbs that bloated descriptions repeat
            | "allows" | "allow" | "allowed" | "designed"
            | "operation" | "operations"
            | "really" | "actually" | "essentially" | "basically"
    )
}

fn jaccard(a: &HashSet<String>, b: &HashSet<String>) -> f32 {
    if a.is_empty() && b.is_empty() {
        return 1.0;
    }
    let inter = a.intersection(b).count() as f32;
    let union = a.union(b).count() as f32;
    if union == 0.0 {
        0.0
    } else {
        inter / union
    }
}

/// Term-frequency cosine similarity over content stems. Two descriptions that
/// share the same dominant terms — even if one has 2× the filler — score very
/// close to 1.0; a description that drops the subject noun entirely tanks.
fn tf_cosine(a: &str, b: &str) -> f32 {
    use std::collections::HashMap;
    fn tf(s: &str) -> HashMap<String, f32> {
        let mut m: HashMap<String, f32> = HashMap::new();
        for w in s.split(|c: char| !c.is_alphanumeric()) {
            if w.len() <= 2 {
                continue;
            }
            let lower = w.to_ascii_lowercase();
            if is_stopword(&lower) {
                continue;
            }
            // Same crude stemmer as `stem_set_of_str` so the two metrics stay
            // aligned on what counts as the "same" token.
            let stemmed = {
                let mut out = lower.clone();
                for suf in ["ing", "ed", "es", "s", "ly"] {
                    if out.ends_with(suf) && out.len() > suf.len() + 2 {
                        out.truncate(out.len() - suf.len());
                        break;
                    }
                }
                out
            };
            *m.entry(stemmed).or_insert(0.0) += 1.0;
        }
        m
    }
    let ta = tf(a);
    let tb = tf(b);
    if ta.is_empty() && tb.is_empty() {
        return 1.0;
    }
    let mut dot = 0.0_f32;
    let mut na2 = 0.0_f32;
    let mut nb2 = 0.0_f32;
    for v in ta.values() {
        na2 += v * v;
    }
    for v in tb.values() {
        nb2 += v * v;
    }
    for (k, va) in ta.iter() {
        if let Some(vb) = tb.get(k) {
            dot += va * vb;
        }
    }
    let denom = na2.sqrt() * nb2.sqrt();
    if denom == 0.0 {
        0.0
    } else {
        (dot / denom).clamp(0.0, 1.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn t(desc: &str) -> Tool {
        Tool {
            name: "x".into(),
            description: desc.into(),
            input_schema: json!({}),
        }
    }

    #[test]
    fn shrinks_a_bloated_description() {
        let bloated = "Please note that this tool is a tool that allows you to compute the sum \
                       of two numbers. Use this tool when you need to add numbers. Simply pass \
                       two numbers and you will get the sum back.";
        let opt = HeuristicOptimizer::new();
        let out = opt.rewrite(&t(bloated));
        // The aggressive rule set targets ≥40% reduction on the multi-tool
        // corpus; on a short example we just require a meaningful cut while
        // preserving the content-stem floor configured on the optimizer.
        assert!(out.reduction_pct >= 25.0, "got {}%", out.reduction_pct);
        assert!(out.semantic_similarity >= 0.7, "jaccard {}", out.semantic_similarity);
    }

    #[test]
    fn preserves_short_descriptions() {
        let opt = HeuristicOptimizer::new();
        let out = opt.rewrite(&t("Adds two numbers."));
        assert!(out.reduction_pct >= 0.0);
        assert!(out.semantic_similarity >= 0.9);
    }

    #[test]
    fn squashes_whitespace() {
        let opt = HeuristicOptimizer::new();
        let out = opt.rewrite(&t("hello    world"));
        assert_eq!(out.rewritten, "hello world");
    }

    #[test]
    fn dedupes_duplicate_sentences() {
        let opt = HeuristicOptimizer::new();
        let out = opt.rewrite(&t("Returns the user. Returns the user. Returns the user."));
        assert!(out.rewritten_tokens < out.original_tokens);
    }

    #[test]
    fn strips_markdown_emphasis() {
        let opt = HeuristicOptimizer::new();
        let out = opt.rewrite(&t("**Adds** _two_ numbers"));
        assert!(!out.rewritten.contains('*'));
        assert!(!out.rewritten.contains('_'));
    }

    #[test]
    fn jaccard_guardrail_holds() {
        let opt = HeuristicOptimizer::new();
        let big = "Search the customer database for matching contact records by full name, email \
                   address, phone number, mailing address, or any combination thereof. Please \
                   note that this tool is a tool that allows you to perform such a search.";
        let out = opt.rewrite(&t(big));
        // The optimizer's content-stem floor is 0.7; if this assertion ever
        // fails it means the heuristic dropped meaning.
        assert!(
            out.semantic_similarity >= 0.7,
            "jaccard {} dropped too low",
            out.semantic_similarity
        );
    }
}