mcp-skill-framework 0.1.1

A small framework for building MCP (Model Context Protocol) servers as a uniform layer of self-contained tools ("skills"): a typed skill contract, declarative input validation, capability probes, family metadata, and a ready-made dispatcher.
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Structured input validation for the [`Skill`](crate::Skill) contract.
//!
//! Every skill declares a list of [`Rule`]s in its
//! [`Skill::validation_rules`](crate::Skill::validation_rules)
//! implementation. The dispatcher evaluates them after the arguments
//! arrive and BEFORE the call body runs; on failure the call returns a
//! structured `{"validation_failed": [...]}` payload describing exactly
//! which fields broke which rules, so an LLM caller can correct itself
//! without parsing English error strings.
//!
//! The same rule tree can be surfaced through an introspection tool (see
//! [`crate::describe`]) so a caller can audit the constraints up-front. It
//! complements the JSON Schema that comes from `schemars` derives — JSON
//! Schema tells the caller the shape (types, required fields),
//! `validation_rules` tells it the domain constraints (range, mutual
//! exclusion, allowed enum values, regex shape).
//!
//! ## Composability
//!
//! Rules nest with `All` (AND), `Any` (OR), and `Not`. `ExactlyOne` and
//! `AtLeastOne` over a set of field names express the common
//! mutually-exclusive / "supply one of" patterns natively, so skills
//! don't have to roll their own. The `Custom` variant is the escape
//! hatch for anything the declarative DSL can't express.

use rmcp::model::JsonObject;
use serde_json::{json, Value};

/// One field-level constraint violation, structured for a caller to read.
#[derive(Debug, Clone)]
pub struct FieldViolation {
    /// JSON-pointer-ish field path. Top-level field names ("`code`"), nested
    /// dotted paths ("`config.timeout`"), or array elements ("`items[2]`").
    pub field: String,
    /// Short rule identifier — `"range"`, `"one_of"`, `"regex"`, `"length"`,
    /// `"exactly_one"`, `"at_least_one"`, `"all_of"`, `"any_of"`, `"not"`,
    /// `"custom"`.
    pub rule: &'static str,
    /// Human-readable description of what's wrong.
    pub message: String,
    /// Machine-readable description of the expected shape, e.g.
    /// `{"min":100, "max":599}` or `{"one_of":["a","b"]}` — exactly what
    /// the rule asserts.
    pub expected: Value,
    /// The actual value that violated, when extractable.
    pub got: Option<Value>,
}

/// Outcome of [`Skill::validate`](crate::Skill::validate).
#[derive(Debug, Clone)]
pub enum ValidationResult {
    /// Args passed every rule.
    Pass,
    /// One or more rules failed. The list is preserved in declaration
    /// order so the dispatcher can surface them deterministically.
    Fail(Vec<FieldViolation>),
}

impl ValidationResult {
    /// `true` iff validation passed.
    pub fn is_pass(&self) -> bool {
        matches!(self, ValidationResult::Pass)
    }
    /// Render as the structured JSON the dispatcher returns to the caller.
    pub fn to_payload(&self) -> Value {
        match self {
            ValidationResult::Pass => json!({"validation": "pass"}),
            ValidationResult::Fail(violations) => {
                let arr: Vec<Value> = violations
                    .iter()
                    .map(|v| {
                        let mut obj = json!({
                            "field": v.field,
                            "rule": v.rule,
                            "message": v.message,
                            "expected": v.expected,
                        });
                        if let Some(g) = &v.got {
                            obj["got"] = g.clone();
                        }
                        obj
                    })
                    .collect();
                json!({"validation_failed": arr})
            }
        }
    }
}

/// Declarative validation rule. Built once per skill (typically as a
/// `&'static [Rule]`) so there's no per-call allocation cost.
#[derive(Debug, Clone)]
pub enum Rule {
    /// Numeric `field` must satisfy `min <= value <= max`. Either bound is
    /// optional. Works for any field that parses as `f64`.
    Range {
        field: &'static str,
        min: Option<f64>,
        max: Option<f64>,
    },
    /// String `field` must equal one of the listed values (case-sensitive).
    OneOf {
        field: &'static str,
        values: &'static [&'static str],
    },
    /// String `field` must match the given Rust regex. `summary` is a
    /// short human description ("ISO-3166 alpha-2") shown in the error.
    Regex {
        field: &'static str,
        pattern: &'static str,
        summary: &'static str,
    },
    /// String / array `field` length bounds (Unicode chars for strings, len for arrays).
    Length {
        field: &'static str,
        min: Option<usize>,
        max: Option<usize>,
    },
    /// Exactly one of the named fields must be present + non-null.
    ExactlyOne { fields: &'static [&'static str] },
    /// At least one of the named fields must be present + non-null.
    AtLeastOne { fields: &'static [&'static str] },
    /// Conjunction — every sub-rule must pass.
    All(&'static [Rule]),
    /// Disjunction — at least one sub-rule must pass. Failures are reported
    /// only when EVERY branch fails (aggregated).
    Any(&'static [Rule]),
    /// Negation — the inner rule must NOT match. Useful as the dual of `OneOf`.
    Not(&'static Rule),
    /// Custom validator. Receives the full args object, returns Ok or one
    /// FieldViolation. Use sparingly — declarative variants are preferred
    /// because [`crate::describe`] can render them.
    Custom {
        /// Stable identifier shown in error output and introspection.
        name: &'static str,
        /// One-line summary shown in introspection.
        summary: &'static str,
        eval: fn(&JsonObject) -> Result<(), FieldViolation>,
    },
}

/// Evaluate every rule against the parsed arg object.
pub fn evaluate(rules: &[Rule], args: &JsonObject) -> ValidationResult {
    let mut out: Vec<FieldViolation> = Vec::new();
    for r in rules {
        if let Err(mut v) = eval_one(r, args) {
            out.append(&mut v);
        }
    }
    if out.is_empty() {
        ValidationResult::Pass
    } else {
        ValidationResult::Fail(out)
    }
}

fn eval_one(rule: &Rule, args: &JsonObject) -> Result<(), Vec<FieldViolation>> {
    match rule {
        Rule::Range { field, min, max } => {
            let v = lookup(args, field);
            // None / null is treated as "absent" — skip; let required-field shape catch it.
            let Some(value) = v else { return Ok(()) };
            let n = match value.as_f64() {
                Some(n) => n,
                None => {
                    return Err(vec![FieldViolation {
                        field: (*field).to_string(),
                        rule: "range",
                        message: format!("`{field}` must be a number"),
                        expected: json!({"type": "number"}),
                        got: Some(value.clone()),
                    }]);
                }
            };
            let lo = min.unwrap_or(f64::NEG_INFINITY);
            let hi = max.unwrap_or(f64::INFINITY);
            if n < lo || n > hi {
                return Err(vec![FieldViolation {
                    field: (*field).to_string(),
                    rule: "range",
                    message: format!(
                        "`{field}` must be in [{}..{}], got {n}",
                        min.map(|x| x.to_string()).unwrap_or_else(|| "-∞".into()),
                        max.map(|x| x.to_string()).unwrap_or_else(|| "+∞".into()),
                    ),
                    expected: json!({"min": min, "max": max}),
                    got: Some(json!(n)),
                }]);
            }
            Ok(())
        }
        Rule::OneOf { field, values } => {
            let v = lookup(args, field);
            let Some(value) = v else { return Ok(()) };
            let s = match value.as_str() {
                Some(s) => s,
                None => {
                    return Err(vec![FieldViolation {
                        field: (*field).to_string(),
                        rule: "one_of",
                        message: format!("`{field}` must be a string"),
                        expected: json!({"one_of": values}),
                        got: Some(value.clone()),
                    }]);
                }
            };
            if values.contains(&s) {
                Ok(())
            } else {
                Err(vec![FieldViolation {
                    field: (*field).to_string(),
                    rule: "one_of",
                    message: format!("`{field}` must be one of {values:?}, got `{s}`"),
                    expected: json!({"one_of": values}),
                    got: Some(json!(s)),
                }])
            }
        }
        Rule::Regex {
            field,
            pattern,
            summary,
        } => {
            let v = lookup(args, field);
            let Some(value) = v else { return Ok(()) };
            let s = match value.as_str() {
                Some(s) => s,
                None => {
                    return Err(vec![FieldViolation {
                        field: (*field).to_string(),
                        rule: "regex",
                        message: format!("`{field}` must be a string"),
                        expected: json!({"pattern": pattern, "summary": summary}),
                        got: Some(value.clone()),
                    }]);
                }
            };
            // Compile per-call; regex caching across calls is a follow-up.
            match regex::Regex::new(pattern) {
                Ok(re) if re.is_match(s) => Ok(()),
                Ok(_) => Err(vec![FieldViolation {
                    field: (*field).to_string(),
                    rule: "regex",
                    message: format!("`{field}` must match {summary} (regex `{pattern}`)"),
                    expected: json!({"pattern": pattern, "summary": summary}),
                    got: Some(json!(s)),
                }]),
                Err(_) => Ok(()), // bad pattern at code time — don't reject the user
            }
        }
        Rule::Length { field, min, max } => {
            let v = lookup(args, field);
            let Some(value) = v else { return Ok(()) };
            let n = if let Some(s) = value.as_str() {
                s.chars().count()
            } else if let Some(arr) = value.as_array() {
                arr.len()
            } else {
                return Err(vec![FieldViolation {
                    field: (*field).to_string(),
                    rule: "length",
                    message: format!("`{field}` must be a string or array"),
                    expected: json!({"min": min, "max": max}),
                    got: Some(value.clone()),
                }]);
            };
            let lo = min.unwrap_or(0);
            let hi = max.unwrap_or(usize::MAX);
            if n < lo || n > hi {
                return Err(vec![FieldViolation {
                    field: (*field).to_string(),
                    rule: "length",
                    message: format!(
                        "`{field}` length must be in [{}..{}], got {n}",
                        min.map(|x| x.to_string()).unwrap_or_else(|| "0".into()),
                        max.map(|x| x.to_string()).unwrap_or_else(|| "".into()),
                    ),
                    expected: json!({"min": min, "max": max}),
                    got: Some(json!(n)),
                }]);
            }
            Ok(())
        }
        Rule::ExactlyOne { fields } => {
            let present: Vec<&&str> = fields
                .iter()
                .filter(|f| lookup(args, f).is_some_and(|v| !v.is_null()))
                .collect();
            if present.len() == 1 {
                Ok(())
            } else {
                Err(vec![FieldViolation {
                    field: fields.join(", "),
                    rule: "exactly_one",
                    message: format!("exactly one of {fields:?} must be supplied; got {present:?}"),
                    expected: json!({"exactly_one": fields}),
                    got: Some(json!(present)),
                }])
            }
        }
        Rule::AtLeastOne { fields } => {
            let present: Vec<&&str> = fields
                .iter()
                .filter(|f| lookup(args, f).is_some_and(|v| !v.is_null()))
                .collect();
            if !present.is_empty() {
                Ok(())
            } else {
                Err(vec![FieldViolation {
                    field: fields.join(", "),
                    rule: "at_least_one",
                    message: format!("at least one of {fields:?} must be supplied"),
                    expected: json!({"at_least_one": fields}),
                    got: Some(json!([])),
                }])
            }
        }
        Rule::All(sub) => {
            // Every sub-rule must pass. Aggregate all failures so the caller
            // sees the full list, not just the first.
            let mut out: Vec<FieldViolation> = Vec::new();
            for r in *sub {
                if let Err(mut v) = eval_one(r, args) {
                    out.append(&mut v);
                }
            }
            if out.is_empty() {
                Ok(())
            } else {
                Err(out)
            }
        }
        Rule::Any(sub) => {
            // At least one branch must pass. Only surface failures when
            // every branch fails — and then surface ALL of them as a hint
            // about which paths were tried.
            let mut all_failures: Vec<FieldViolation> = Vec::new();
            for r in *sub {
                match eval_one(r, args) {
                    Ok(()) => return Ok(()),
                    Err(mut v) => all_failures.append(&mut v),
                }
            }
            Err(all_failures)
        }
        Rule::Not(inner) => {
            // The inner rule must NOT match. We swallow its failure list
            // and emit a single "not matched the negated rule" hint.
            match eval_one(inner, args) {
                Ok(()) => Err(vec![FieldViolation {
                    field: "<combinator>".into(),
                    rule: "not",
                    message: "negated rule unexpectedly matched".into(),
                    expected: json!({"not": format!("{inner:?}")}),
                    got: None,
                }]),
                Err(_) => Ok(()),
            }
        }
        Rule::Custom { eval, .. } => match eval(args) {
            Ok(()) => Ok(()),
            Err(v) => Err(vec![v]),
        },
    }
}

/// Dotted-path lookup. `"foo"` -> top-level; `"a.b"` -> nested; array
/// elements aren't supported by the path syntax yet (caller can write a
/// `Custom` rule for those rare cases).
fn lookup<'a>(args: &'a JsonObject, path: &str) -> Option<&'a Value> {
    // Fast path: single-segment lookup against the original object.
    if !path.contains('.') {
        return args.get(path);
    }
    // Multi-segment: walk the nested objects. Deep paths are rare.
    let mut cur: Option<&Value> = args.get(path.split('.').next().unwrap_or(""));
    for seg in path.split('.').skip(1) {
        cur = cur.and_then(|v| v.get(seg));
    }
    cur
}

/// Render a rule tree as a JSON shape suitable for an introspection tool.
pub fn rules_to_json(rules: &[Rule]) -> Value {
    Value::Array(rules.iter().map(rule_to_json).collect())
}

fn rule_to_json(r: &Rule) -> Value {
    match r {
        Rule::Range { field, min, max } => {
            json!({"rule": "range", "field": field, "min": min, "max": max})
        }
        Rule::OneOf { field, values } => {
            json!({"rule": "one_of", "field": field, "values": values})
        }
        Rule::Regex {
            field,
            pattern,
            summary,
        } => {
            json!({"rule": "regex", "field": field, "pattern": pattern, "summary": summary})
        }
        Rule::Length { field, min, max } => {
            json!({"rule": "length", "field": field, "min": min, "max": max})
        }
        Rule::ExactlyOne { fields } => json!({"rule": "exactly_one", "fields": fields}),
        Rule::AtLeastOne { fields } => json!({"rule": "at_least_one", "fields": fields}),
        Rule::All(sub) => {
            json!({"rule": "all_of", "rules": sub.iter().map(rule_to_json).collect::<Vec<_>>()})
        }
        Rule::Any(sub) => {
            json!({"rule": "any_of", "rules": sub.iter().map(rule_to_json).collect::<Vec<_>>()})
        }
        Rule::Not(inner) => json!({"rule": "not", "inner": rule_to_json(inner)}),
        Rule::Custom { name, summary, .. } => {
            json!({"rule": "custom", "name": name, "summary": summary})
        }
    }
}

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

    fn args(json: Value) -> JsonObject {
        let Value::Object(m) = json else {
            panic!("not an object")
        };
        m.into_iter().collect::<Map<_, _>>()
    }

    #[test]
    fn range_in_bounds_passes() {
        let r = [Rule::Range {
            field: "code",
            min: Some(100.0),
            max: Some(599.0),
        }];
        let a = args(json!({"code": 200}));
        assert!(evaluate(&r, &a).is_pass());
    }

    #[test]
    fn range_out_of_bounds_fails() {
        let r = [Rule::Range {
            field: "code",
            min: Some(100.0),
            max: Some(599.0),
        }];
        let a = args(json!({"code": 700}));
        match evaluate(&r, &a) {
            ValidationResult::Fail(v) => {
                assert_eq!(v[0].rule, "range");
                assert_eq!(v[0].field, "code");
            }
            _ => panic!(),
        }
    }

    #[test]
    fn one_of_passes() {
        let r = [Rule::OneOf {
            field: "kind",
            values: &["a", "b", "c"],
        }];
        let a = args(json!({"kind": "b"}));
        assert!(evaluate(&r, &a).is_pass());
    }

    #[test]
    fn one_of_rejects() {
        let r = [Rule::OneOf {
            field: "kind",
            values: &["a", "b"],
        }];
        let a = args(json!({"kind": "x"}));
        let res = evaluate(&r, &a);
        assert!(matches!(res, ValidationResult::Fail(_)));
    }

    #[test]
    fn length_bounds_enforced() {
        let r = [Rule::Length {
            field: "name",
            min: Some(2),
            max: Some(4),
        }];
        assert!(evaluate(&r, &args(json!({"name": "abc"}))).is_pass());
        assert!(matches!(
            evaluate(&r, &args(json!({"name": "a"}))),
            ValidationResult::Fail(_)
        ));
        assert!(matches!(
            evaluate(&r, &args(json!({"name": "abcde"}))),
            ValidationResult::Fail(_)
        ));
    }

    #[test]
    fn regex_matches_and_rejects() {
        let r = [Rule::Regex {
            field: "cc",
            pattern: "^[A-Z]{2}$",
            summary: "ISO-3166 alpha-2",
        }];
        assert!(evaluate(&r, &args(json!({"cc": "US"}))).is_pass());
        assert!(matches!(
            evaluate(&r, &args(json!({"cc": "usa"}))),
            ValidationResult::Fail(_)
        ));
    }

    #[test]
    fn nested_dotted_path_resolves() {
        let r = [Rule::Range {
            field: "config.timeout",
            min: Some(1.0),
            max: Some(60.0),
        }];
        assert!(evaluate(&r, &args(json!({"config": {"timeout": 30}}))).is_pass());
        assert!(matches!(
            evaluate(&r, &args(json!({"config": {"timeout": 120}}))),
            ValidationResult::Fail(_)
        ));
    }

    #[test]
    fn exactly_one_enforced() {
        let r = [Rule::ExactlyOne {
            fields: &["a", "b"],
        }];
        // Both → fail.
        let two = args(json!({"a": 1, "b": 2}));
        assert!(matches!(evaluate(&r, &two), ValidationResult::Fail(_)));
        // None → fail.
        let zero = args(json!({}));
        assert!(matches!(evaluate(&r, &zero), ValidationResult::Fail(_)));
        // Exactly one → pass.
        let one = args(json!({"a": 1}));
        assert!(evaluate(&r, &one).is_pass());
    }

    #[test]
    fn any_or_passes_when_one_branch_does() {
        static SUB: &[Rule] = &[
            Rule::OneOf {
                field: "kind",
                values: &["x"],
            },
            Rule::Range {
                field: "code",
                min: Some(0.0),
                max: Some(10.0),
            },
        ];
        let r = [Rule::Any(SUB)];
        let a = args(json!({"kind": "wrong", "code": 5}));
        assert!(evaluate(&r, &a).is_pass());
    }

    #[test]
    fn any_or_fails_when_all_branches_do() {
        static SUB: &[Rule] = &[
            Rule::OneOf {
                field: "kind",
                values: &["x"],
            },
            Rule::Range {
                field: "code",
                min: Some(0.0),
                max: Some(10.0),
            },
        ];
        let r = [Rule::Any(SUB)];
        let a = args(json!({"kind": "wrong", "code": 100}));
        match evaluate(&r, &a) {
            ValidationResult::Fail(v) => assert_eq!(v.len(), 2),
            _ => panic!(),
        }
    }

    #[test]
    fn payload_shape() {
        let r = [Rule::Range {
            field: "p",
            min: Some(0.0),
            max: Some(100.0),
        }];
        let a = args(json!({"p": 150}));
        let p = evaluate(&r, &a).to_payload();
        assert!(p["validation_failed"].is_array());
        assert_eq!(p["validation_failed"][0]["field"], "p");
        assert_eq!(p["validation_failed"][0]["rule"], "range");
    }

    #[test]
    fn rules_to_json_round_trips_shape() {
        let r = [
            Rule::OneOf {
                field: "style",
                values: &["a", "b"],
            },
            Rule::Range {
                field: "n",
                min: Some(0.0),
                max: None,
            },
        ];
        let j = rules_to_json(&r);
        assert_eq!(j[0]["rule"], "one_of");
        assert_eq!(j[0]["field"], "style");
        assert_eq!(j[1]["rule"], "range");
    }
}