Skip to main content

mcp_trace_validator/checks/base/
meta.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2026 Tom F. (https://github.com/tomtom215)
3
4//! The `_meta` key-grammar check (`BASE-019`/`BASE-020`).
5
6use serde_json::Value;
7
8use super::super::FindingSink;
9use crate::context::TraceContext;
10
11/// `BASE-019`/`BASE-020`: `_meta` key grammar — an optional dotted-label
12/// prefix ending in `/`, then a name that begins and ends alphanumeric.
13///
14/// Scope: the `params._meta` and `result._meta` objects — the
15/// "property/parameter" positions the clauses name on the message envelope.
16/// `_meta` objects nested deeper (content items, tool definitions) share the
17/// grammar but collide with user-defined data (a tool's `arguments` may
18/// legitimately contain a member spelled `_meta`), so the envelope positions
19/// are the sound, false-positive-free scope.
20pub(in crate::checks) fn meta_key_format(context: &TraceContext<'_>, sink: &mut FindingSink) {
21    for (event, _, _) in context.messages() {
22        let Some(payload) = event.message_payload() else {
23            continue;
24        };
25        for envelope in ["params", "result"] {
26            let meta = payload
27                .get(envelope)
28                .and_then(|member| member.get("_meta"))
29                .and_then(Value::as_object);
30            let Some(meta) = meta else { continue };
31            for key in meta.keys() {
32                if let Err(reason) = validate_meta_key(key) {
33                    sink.push(
34                        Some(event.seq),
35                        format!("{envelope}._meta key {key:?} {reason}"),
36                    );
37                }
38            }
39        }
40    }
41}
42
43/// Validates one `_meta` key against the `2025-11-25` grammar: an optional
44/// `label(.label)*/` prefix (labels start with a letter, end with a letter or
45/// digit, interior letters/digits/hyphens) and a name that, unless empty,
46/// begins and ends alphanumeric with `-`/`_`/`.`/alphanumerics between.
47fn validate_meta_key(key: &str) -> Result<(), String> {
48    let (prefix, name) = match key.split_once('/') {
49        Some((prefix, name)) => (Some(prefix), name),
50        None => (None, key),
51    };
52    if let Some(prefix) = prefix {
53        for label in prefix.split('.') {
54            let bytes = label.as_bytes();
55            let shape_ok = bytes.first().is_some_and(u8::is_ascii_alphabetic)
56                && bytes.last().is_some_and(u8::is_ascii_alphanumeric)
57                && bytes
58                    .iter()
59                    .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-');
60            if !shape_ok {
61                return Err(format!(
62                    "has prefix label {label:?}; labels must start with a letter, end with \
63                     a letter or digit, and contain only letters, digits, or hyphens"
64                ));
65            }
66        }
67    }
68    if !name.is_empty() {
69        let bytes = name.as_bytes();
70        if !bytes.first().is_some_and(u8::is_ascii_alphanumeric)
71            || !bytes.last().is_some_and(u8::is_ascii_alphanumeric)
72        {
73            return Err(
74                "has a name that does not begin and end with an alphanumeric character".to_owned(),
75            );
76        }
77        if !bytes
78            .iter()
79            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
80        {
81            return Err(
82                "has a name with characters outside alphanumerics, hyphens, underscores, \
83                 and dots"
84                    .to_owned(),
85            );
86        }
87    }
88    Ok(())
89}
90
91#[cfg(test)]
92#[allow(clippy::unwrap_used)]
93mod tests {
94    use crate::checks;
95    use crate::context::TraceContext;
96    use crate::reader::{Limits, parse_trace};
97    use crate::report::Finding;
98    use mcp_conformance_core::trace::TraceEvent;
99
100    fn run_check(check_id: &str, trace: &str) -> Vec<Finding> {
101        let events: Vec<TraceEvent> = parse_trace(trace, &Limits::default()).unwrap();
102        let context = TraceContext::new(&events);
103        checks::find(check_id).unwrap().run(&context)
104    }
105
106    const INIT: &str = r#"{"seq":0,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}}"#;
107
108    #[test]
109    fn meta_key_grammar_table() {
110        use super::validate_meta_key;
111        for valid in [
112            "progressToken",
113            "x",
114            "n.a-me_0",
115            "com.example/key",
116            "com.example/",
117            "a/b",
118            "a1-b/n",
119            "io.modelcontextprotocol/x",
120        ] {
121            assert!(
122                validate_meta_key(valid).is_ok(),
123                "{valid:?} should be valid"
124            );
125        }
126        for invalid in [
127            "1bad/x", // label starts with a digit
128            "bad-/x", // label ends with a hyphen
129            "a..b/x", // empty interior label
130            "/x",     // empty prefix label
131            "a_b/x",  // underscore not allowed in labels
132            "a/-x",   // name starts with a hyphen
133            "a/x.",   // name ends with a dot
134            "a/x y",  // space in name
135            "a/b/c",  // slash in name
136            "",       // empty bare name… is an empty name, which is allowed
137        ] {
138            if invalid.is_empty() {
139                // Documented edge: an empty name is allowed ("Unless empty…"),
140                // and a bare empty key has no prefix either.
141                assert!(validate_meta_key(invalid).is_ok());
142            } else {
143                assert!(
144                    validate_meta_key(invalid).is_err(),
145                    "{invalid:?} should be invalid"
146                );
147            }
148        }
149    }
150
151    #[test]
152    fn meta_key_format_scopes_to_envelope_meta_only() {
153        // params._meta violations are findings; identical spellings inside
154        // user data (tool arguments) are not.
155        let trace = format!(
156            "{INIT}\n{}\n{}",
157            r#"{"seq":1,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":2,"method":"ping","params":{"_meta":{"1bad./t":1}}}}"#,
158            r#"{"seq":2,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"_meta":{"1bad./t":1}}}}}"#
159        );
160        let findings = run_check("base.meta-key-format", &trace);
161        assert_eq!(findings.len(), 1, "{findings:?}");
162        assert!(findings[0].detail.contains("params._meta"), "{findings:?}");
163        assert_eq!(findings[0].seq, Some(1));
164    }
165}