mcp-trace-validator 0.5.1

Deterministic offline validator for recorded Model Context Protocol traces: requirement-level findings, machine-readable reports
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
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. (https://github.com/tomtom215)

//! Checks for the base JSON-RPC message requirements (`BASE-*`).
//!
//! These operate per message and rely on [`classify`]'s leniency: malformed messages
//! are reported precisely rather than aborting the run.
//!
//! Two groups live in submodules because they carry machinery of their own:
//! [`meta`] holds the `_meta` key grammar, and [`correlation`] the shared walk
//! that answers `BASE-004` and `BASE-009` together.

use std::collections::HashMap;

use mcp_conformance_core::canonical::to_canonical_string;
use mcp_conformance_core::message::{MessageKind, is_notification_method};
use mcp_conformance_core::trace::Direction;
use serde_json::Value;

use super::FindingSink;
use crate::context::TraceContext;

mod correlation;
mod meta;

pub(super) use correlation::{error_id_matches, result_id_matches};
pub(super) use meta::meta_key_format;
// The `_meta` key grammar is unchanged at `2026-07-28`, where VERS-004 reuses it
// for extension identifiers — the function, not `base.meta-key-format`, which
// reads envelope keys and would inspect no identifier at all.
#[cfg(feature = "draft-2026-07-28")]
pub(super) use meta::validate_meta_key;

/// Human name of a JSON value's type, for finding details.
fn type_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(number) => {
            if number.is_i64() || number.is_u64() {
                "an integer"
            } else {
                "a non-integer number"
            }
        }
        Value::String(_) => "a string",
        Value::Array(_) => "an array",
        Value::Object(_) => "an object",
    }
}

fn id_is_string_or_integer(id: &Value) -> bool {
    match id {
        Value::String(_) => true,
        Value::Number(number) => number.is_i64() || number.is_u64(),
        _ => false,
    }
}

/// `BASE-001`: "Requests MUST include a string or integer ID."
pub(super) fn request_id_type(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        let MessageKind::Request { method, id } = kind else {
            continue;
        };
        sink.examined();
        if !id_is_string_or_integer(id) {
            sink.push(
                    Some(event.seq),
                    format!(
                        "request {method:?} carries {} as its id; the ID must be a string or an integer",
                    type_name(id)
                ),
            );
        }
    }
}

/// `BASE-002`: "Unlike base JSON-RPC, the ID MUST NOT be `null`."
pub(super) fn request_id_not_null(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        let MessageKind::Request { method, id } = kind else {
            continue;
        };
        sink.examined();
        if id.is_null() {
            sink.push(
                Some(event.seq),
                format!("request {method:?} carries a null id, which MCP forbids"),
            );
        }
    }
}

/// `BASE-003`: "The request ID MUST NOT have been previously used by the requestor
/// within the same session."
pub(super) fn request_id_unique(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let mut first_use: HashMap<(Direction, String), u64> = HashMap::new();
    for (event, kind, _) in context.messages() {
        if let MessageKind::Request { method, id } = kind {
            if id.is_null() {
                continue; // BASE-002's finding; don't double-report.
            }
            sink.examined();
            let key = (event.direction, to_canonical_string(id));
            match first_use.get(&key) {
                Some(previous) => sink.push(
                    Some(event.seq),
                    format!(
                        "request {method:?} reuses id {}, already used by the same party at seq {previous}",
                        key.1
                    ),
                ),
                None => {
                    first_use.insert(key, event.seq);
                }
            }
        }
    }
}

/// `BASE-005`: "Notifications MUST NOT include an ID."
///
/// A message in the reserved `notifications/` namespace that carries an `id`
/// classifies structurally as a request; this check is what catches it.
pub(super) fn notification_no_id(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        let MessageKind::Request { method, .. } = kind else {
            continue;
        };
        sink.examined();
        if is_notification_method(method) {
            sink.push(
                    Some(event.seq),
                    format!(
                    "{method:?} is a notification method but the message carries an id; notifications must not include one"
                ),
            );
        }
    }
}

/// `BASE-006`: "Error responses MUST include an `error` field with a `code` and
/// `message`."
pub(super) fn error_shape(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        if let MessageKind::Error { error, .. } = kind {
            sink.examined();
            let Some(object) = error.as_object() else {
                sink.push(
                    Some(event.seq),
                    format!("error member is {}, expected an object", type_name(error)),
                );
                continue;
            };
            if !object.contains_key("code") {
                sink.push(
                    Some(event.seq),
                    "error object lacks a code member".to_owned(),
                );
            }
            match object.get("message") {
                None => sink.push(
                    Some(event.seq),
                    "error object lacks a message member".to_owned(),
                ),
                Some(message) if !message.is_string() => sink.push(
                    Some(event.seq),
                    format!(
                        "error message member is {}, expected a string",
                        type_name(message)
                    ),
                ),
                Some(_) => {}
            }
        }
    }
}

/// `BASE-007`: "Error codes MUST be integers."
pub(super) fn error_code_integer(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        let MessageKind::Error { error, .. } = kind else {
            continue;
        };
        // The subject is an error *carrying a code*: an error with none is
        // BASE-006's finding, and this clause has nothing to judge there.
        let Some(code) = error.get("code") else {
            continue;
        };
        sink.examined();
        if !code.is_i64() && !code.is_u64() {
            sink.push(
                Some(event.seq),
                format!("error code is {}, expected an integer", type_name(code)),
            );
        }
    }
}

/// `BASE-010`: "Result responses MUST include a `result` field." A message carrying
/// an `id` and no `method` is response-shaped; if it then carries neither `result`
/// nor `error`, it is a result response missing its `result` member (an error
/// response would carry `error` instead).
///
/// `Result`-classified messages are subjects too, and counting them is the point:
/// they carry the member, so they are this clause *complied with*. Examining only
/// the `Invalid` ones left the check unable to report a pass at all — a session
/// full of well-formed results reported `not observed`, which says the trace
/// carried nothing this clause binds to and was plainly untrue. An outcome a
/// check can never reach is a check nothing proves accepts conforming input.
pub(super) fn result_field(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        // An `Error` response is deliberately not a subject: the clause binds
        // *result* responses, and an error legitimately carries no `result`.
        if !matches!(
            kind,
            MessageKind::Invalid { .. } | MessageKind::Result { .. }
        ) {
            continue;
        }
        let Some(object) = event.message_payload().and_then(Value::as_object) else {
            continue;
        };
        if !object.contains_key("id") || object.contains_key("method") {
            continue;
        }
        sink.examined();
        // One member, not both, and the classifier is why. A message reaching
        // here is `Invalid` with an `id` and no `method`, and `classify`'s own
        // table leaves exactly two ways for that to happen: it carries *both*
        // `result` and `error` (ambiguous) or *neither* (this clause's
        // finding). The two tests can therefore never disagree, so asking both
        // is a condition no trace can vary independently — dead weight that
        // reads as thoroughness. The mutation gate found it.
        if !object.contains_key("result") {
            sink.push(
                Some(event.seq),
                "response-shaped message (id present, no method) carries no result field"
                    .to_owned(),
            );
        }
    }
}

/// `BASE-008`: "All messages between MCP clients and servers MUST follow the JSON-RPC
/// 2.0 specification." — verified here as: the message classifies as a JSON-RPC shape
/// and carries `"jsonrpc": "2.0"`.
pub(super) fn jsonrpc_version(context: &TraceContext<'_>, sink: &mut FindingSink) {
    for (event, kind, _) in context.messages() {
        sink.examined();
        if let MessageKind::Invalid { reason } = kind {
            sink.push(
                Some(event.seq),
                format!("message is not a JSON-RPC request, notification, or response: {reason}"),
            );
            continue;
        }
        let version = event
            .message_payload()
            .and_then(|payload| payload.get("jsonrpc"));
        match version {
            Some(Value::String(version)) if version == "2.0" => {}
            Some(other) => sink.push(
                Some(event.seq),
                format!("jsonrpc member is {other}, expected the string \"2.0\""),
            ),
            None => sink.push(
                Some(event.seq),
                "message lacks the jsonrpc member; JSON-RPC 2.0 requires \"jsonrpc\": \"2.0\""
                    .to_owned(),
            ),
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use crate::checks;
    use crate::context::TraceContext;
    use crate::reader::{Limits, parse_trace};
    use crate::report::Finding;
    use mcp_conformance_core::trace::TraceEvent;

    fn run_check(check_id: &str, trace: &str) -> Vec<Finding> {
        let events: Vec<TraceEvent> = parse_trace(trace, &Limits::default()).unwrap();
        let context = TraceContext::new(&events);
        checks::find(check_id).unwrap().run(&context).findings
    }

    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"}}}}"#;

    #[test]
    fn a_response_shaped_message_is_judged_on_its_result_member_alone() {
        // The two cases `classify` can hand this check, and the reason it only
        // asks about `result`: an id-bearing, method-less message that it
        // called `Invalid` carries both members or neither.
        let neither = r#"{"seq":0,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1}}"#;
        let findings = run_check("base.result-field", neither);
        assert_eq!(findings.len(), 1, "{findings:?}");
        assert!(
            findings[0].detail.contains("no result field"),
            "{findings:?}"
        );

        // Both: ambiguous, and BASE-006's business rather than this clause's —
        // whatever else is wrong with it, a `result` member is present.
        let both = r#"{"seq":0,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1,"result":{},"error":{"code":-1,"message":"x"}}}"#;
        assert!(run_check("base.result-field", both).is_empty());

        // A well-formed result classifies as `Result` and never reaches here.
        let clean = r#"{"seq":0,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1,"result":{}}}"#;
        assert!(run_check("base.result-field", clean).is_empty());
    }

    #[test]
    fn result_response_with_null_id_gets_the_null_detail() {
        // A null-id result is its own finding, distinct from "no outstanding request".
        let trace = format!(
            "{INIT}\n{}",
            r#"{"seq":1,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":null,"result":{}}}"#
        );
        let findings = run_check("base.result-id-matches", &trace);
        assert_eq!(findings.len(), 1);
        assert!(
            findings[0].detail.contains("null id"),
            "{}",
            findings[0].detail
        );
    }

    #[test]
    fn error_message_member_type_is_named_precisely() {
        // -5 is i64-but-not-u64: the finding must call it an integer, which pins the
        // is_i64 || is_u64 disjunction in type_name.
        let trace = format!(
            "{INIT}\n{}",
            r#"{"seq":1,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1,"error":{"code":-32600,"message":-5}}}"#
        );
        let findings = run_check("base.error-shape", &trace);
        assert_eq!(findings.len(), 1);
        assert!(
            findings[0]
                .detail
                .contains("is an integer, expected a string"),
            "{}",
            findings[0].detail
        );
    }

    #[test]
    fn u64_only_request_ids_are_valid_integers() {
        // u64::MAX is not representable as i64; it must still count as an integer id.
        let trace = format!(
            "{INIT}\n{}",
            r#"{"seq":1,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":18446744073709551615,"method":"tools/list"}}"#
        );
        assert!(run_check("base.request-id-type", &trace).is_empty());
    }

    /// A request id=2 answered by both an error and a result. The SECOND answer
    /// has no outstanding request and must be flagged by its own flavor's check;
    /// the cross-flavor consume is what makes that true (without it both checks
    /// saw a clean 1:1 and the double-answer slipped through).
    const REQUEST: &str = r#"{"seq":1,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":2,"method":"tools/list"}}"#;
    const RESULT_2: &str = r#"{"seq":3,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":2,"result":{}}}"#;
    const ERROR_2: &str = r#"{"seq":2,"direction":"server-to-client","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"x"}}}"#;

    #[test]
    fn error_then_result_flags_the_second_answer_as_a_result() {
        // error (seq2) then result (seq3): the result is the double-answer, so
        // BASE-004 flags it and BASE-009 stays silent (the error was valid).
        let trace = format!("{INIT}\n{REQUEST}\n{ERROR_2}\n{RESULT_2}");
        let results = run_check("base.result-id-matches", &trace);
        assert_eq!(results.len(), 1, "{results:?}");
        assert_eq!(results[0].seq, Some(3));
        assert!(
            results[0].detail.contains("already answered"),
            "{results:?}"
        );
        assert!(
            run_check("base.error-id-matches", &trace).is_empty(),
            "the error was the legitimate first answer"
        );
    }

    #[test]
    fn result_then_error_flags_the_second_answer_as_an_error() {
        // Reverse order, so the fix cannot be order-specific: result (seq2) then
        // error (seq3) makes the error the double-answer.
        let result_seq2 = RESULT_2.replace("\"seq\":3", "\"seq\":2");
        let error_seq3 = ERROR_2.replace("\"seq\":2", "\"seq\":3");
        let trace = format!("{INIT}\n{REQUEST}\n{result_seq2}\n{error_seq3}");
        let errors = run_check("base.error-id-matches", &trace);
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert_eq!(errors[0].seq, Some(3));
        assert!(errors[0].detail.contains("already answered"), "{errors:?}");
        assert!(
            run_check("base.result-id-matches", &trace).is_empty(),
            "the result was the legitimate first answer"
        );
    }

    #[test]
    fn single_flavor_answer_is_not_flagged_by_the_other_pass() {
        // Guard against a cross-flavor consume that over-fires: a request
        // answered once by a result must leave BOTH passes clean.
        let trace = format!(
            "{INIT}\n{REQUEST}\n{}",
            RESULT_2.replace("\"seq\":3", "\"seq\":2")
        );
        assert!(run_check("base.result-id-matches", &trace).is_empty());
        assert!(run_check("base.error-id-matches", &trace).is_empty());
    }
}