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
// SPDX-License-Identifier: MIT
// Copyright 2026 Tom F. (https://github.com/tomtom215)

//! Checks for the `2025-11-25` session lifecycle requirements (`LIFE-*`).
//!
//! These lean on [`TraceContext`]'s precomputed phases: every check sees the lifecycle
//! phase *before* each event, which is exactly the state the spec's ordering rules are
//! written against.

use mcp_conformance_core::message::MessageKind;
use mcp_conformance_core::revision::ProtocolRevision;
use mcp_conformance_core::trace::Direction;
use serde_json::Value;

use super::FindingSink;
use crate::context::{Phase, TraceContext};

/// `LIFE-001`: "The initialization phase MUST be the first interaction between client
/// and server." — the first message in the trace must be the client's `initialize`
/// request. A trace with no messages examines nothing and reports *not observed*
/// (ADR-0012); the CLI declines such a trace outright, because it is a capture
/// that failed rather than a session that conformed.
pub(super) fn first_interaction_initialize(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let Some((event, kind, _)) = context.messages().next() else {
        return;
    };
    sink.examined();
    match (event.direction, kind) {
        (Direction::ClientToServer, MessageKind::Request { method, .. })
            if *method == "initialize" => {}
        (Direction::ClientToServer, MessageKind::Request { method, .. }) => sink.push(
            Some(event.seq),
            format!("first message is a {method:?} request, expected \"initialize\""),
        ),
        (direction, _) => sink.push(
            Some(event.seq),
            format!(
                "first message is {} ({}), expected the client's \"initialize\" request",
                describe_kind(kind),
                direction_name(direction)
            ),
        ),
    }
}

/// `LIFE-002`: the `initialize` request must carry `protocolVersion`, `capabilities`,
/// and `clientInfo` params.
pub(super) fn initialize_params(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let Some((seq, params)) = context.initialize().request else {
        return; // No initialize at all: LIFE-001's finding.
    };
    sink.examined();
    let Some(params) = params else {
        sink.push(
            Some(seq),
            "initialize request has no params; protocolVersion, capabilities, and clientInfo are required".to_owned(),
        );
        return;
    };
    expect_member(
        sink,
        seq,
        params,
        "protocolVersion",
        Value::is_string,
        "a string",
    );
    expect_member(
        sink,
        seq,
        params,
        "capabilities",
        Value::is_object,
        "an object",
    );
    expect_member(
        sink,
        seq,
        params,
        "clientInfo",
        Value::is_object,
        "an object",
    );
}

fn expect_member(
    sink: &mut FindingSink,
    seq: u64,
    params: &Value,
    member: &str,
    predicate: fn(&Value) -> bool,
    expected: &str,
) {
    match params.get(member) {
        None => sink.push(
            Some(seq),
            format!("initialize params lack the {member} member"),
        ),
        Some(value) if !predicate(value) => sink.push(
            Some(seq),
            format!("initialize params member {member} should be {expected}"),
        ),
        Some(_) => {}
    }
}

/// `LIFE-003`: "After successful initialization, the client MUST send an `initialized`
/// notification …".
pub(super) fn initialized_notification(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let init = context.initialize();
    let Some((result_seq, _)) = init.result else {
        return; // Nothing answered initialize, so nothing owes a follow-up.
    };
    sink.examined();
    if init.initialized.is_none() {
        sink.push(
            Some(result_seq),
            "the server answered initialize here, but no notifications/initialized notification follows in the trace".to_owned(),
        );
    }
}

/// `LIFE-004`: "The client SHOULD NOT send requests other than pings before the server
/// has responded to the `initialize` request."
pub(super) fn client_requests_before_init_response(
    context: &TraceContext<'_>,
    sink: &mut FindingSink,
) {
    for (event, kind, phase) in context.messages() {
        if event.direction != Direction::ClientToServer {
            continue;
        }
        if !matches!(
            phase,
            Phase::BeforeInitialize | Phase::AwaitingInitializeResult
        ) {
            continue;
        }
        // The subject is the window, not the request. This clause forbids a
        // request *existing* here, so sending none through a window the trace
        // actually shows is observable compliance — counting only requests
        // would report the compliant case as unjudged.
        sink.examined();
        let MessageKind::Request { method, .. } = kind else {
            continue;
        };
        if *method != "initialize" && *method != "ping" {
            sink.push(
                Some(event.seq),
                format!(
                    "client sent a {method:?} request before the server responded to initialize"
                ),
            );
        }
    }
}

/// `LIFE-005`: "The server SHOULD NOT send requests other than pings and logging before
/// receiving the `initialized` notification."
///
/// In `2025-11-25`, logging travels as `notifications/message` — a notification, which
/// this requests-only check never flags — so the spec's "and logging" allowance needs
/// no special case here.
pub(super) fn server_requests_before_initialized(
    context: &TraceContext<'_>,
    sink: &mut FindingSink,
) {
    for (event, kind, phase) in context.messages() {
        if event.direction != Direction::ServerToClient || phase == Phase::Ready {
            continue;
        }
        // The window is the subject, as in `LIFE-004` above: a server that
        // answered the handshake and asked for nothing has complied where the
        // trace could have shown otherwise.
        sink.examined();
        let MessageKind::Request { method, .. } = kind else {
            continue;
        };
        if *method != "ping" {
            sink.push(
                Some(event.seq),
                format!(
                    "server sent a {method:?} request before receiving the initialized notification"
                ),
            );
        }
    }
}

/// `LIFE-007`: "In the `initialize` request, the client MUST send a protocol version
/// it supports." — presence and string-ness of the version is the wire-observable
/// core; whether the client truly *supports* the version it sent is not in the trace.
pub(super) fn initialize_protocol_version(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let Some((seq, params)) = context.initialize().request else {
        return; // No initialize at all: LIFE-001's finding.
    };
    sink.examined();
    match params.and_then(|params| params.get("protocolVersion")) {
        None => sink.push(
            Some(seq),
            "initialize request sends no protocolVersion".to_owned(),
        ),
        Some(Value::String(_)) => {}
        Some(other) => sink.push(
            Some(seq),
            format!("initialize request protocolVersion is {other}, expected a version string"),
        ),
    }
}

/// `LIFE-006`: the server's `initialize` result must carry a `protocolVersion` that is
/// a dated revision identifier. Whether the *negotiation* (same-version-if-supported)
/// was honored is not judgeable from a single trace; the shape and format are.
pub(super) fn initialize_result_version(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let Some((seq, result)) = context.initialize().result else {
        return;
    };
    sink.examined();
    match result.get("protocolVersion") {
        None => sink.push(
            Some(seq),
            "initialize result lacks the protocolVersion member".to_owned(),
        ),
        Some(Value::String(version)) => {
            if version.parse::<ProtocolRevision>().is_err() {
                sink.push(
                    Some(seq),
                    format!(
                        "initialize result protocolVersion {version:?} is not a dated revision identifier (YYYY-MM-DD)"
                    ),
                );
            }
        }
        Some(other) => sink.push(
            Some(seq),
            format!("initialize result protocolVersion is {other}, expected a revision string"),
        ),
    }
}

/// `LIFE-010`: the initialize result must carry the server's capabilities and
/// implementation information (`capabilities` and `serverInfo` objects).
///
/// A missing or error-answered initialize exchange is owned by the handshake
/// checks (LIFE-001/003/006); this one judges only a result that exists.
pub(super) fn initialize_result_shape(context: &TraceContext<'_>, sink: &mut FindingSink) {
    let Some((seq, result)) = context.initialize().result else {
        return;
    };
    sink.examined();
    for (member, label) in [
        ("capabilities", "its capabilities"),
        ("serverInfo", "its implementation information (serverInfo)"),
    ] {
        match result.get(member) {
            None => sink.push(
                Some(seq),
                format!("initialize result lacks {label}: no {member} member"),
            ),
            Some(value) if !value.is_object() => sink.push(
                Some(seq),
                format!("initialize result {member} is {value}, expected an object"),
            ),
            Some(_) => {}
        }
    }
}

const fn describe_kind(kind: &MessageKind<'_>) -> &'static str {
    match kind {
        MessageKind::Request { .. } => "a request",
        MessageKind::Notification { .. } => "a notification",
        MessageKind::Result { .. } => "a result response",
        MessageKind::Error { .. } => "an error response",
        MessageKind::Invalid { .. } => "not a valid JSON-RPC message",
        // MessageKind is #[non_exhaustive]; future shapes still deserve a description.
        _ => "an unrecognized message kind",
    }
}

const fn direction_name(direction: Direction) -> &'static str {
    match direction {
        Direction::ClientToServer => "client to server",
        Direction::ServerToClient => "server to client",
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn describe_kind_names_every_shape_exactly() {
        // These strings appear verbatim in findings; mutating any arm must fail here.
        let request = json!({"id": 1, "method": "x"});
        let notification = json!({"method": "x"});
        let result = json!({"id": 1, "result": {}});
        let error = json!({"id": 1, "error": {}});
        let invalid = json!([]);
        let cases = [
            (&request, "a request"),
            (&notification, "a notification"),
            (&result, "a result response"),
            (&error, "an error response"),
            (&invalid, "not a valid JSON-RPC message"),
        ];
        for (payload, expected) in cases {
            let kind = mcp_conformance_core::message::classify(payload);
            assert_eq!(describe_kind(&kind), expected, "for {payload}");
        }
    }

    #[test]
    fn direction_name_is_exact() {
        assert_eq!(
            direction_name(Direction::ClientToServer),
            "client to server"
        );
        assert_eq!(
            direction_name(Direction::ServerToClient),
            "server to client"
        );
    }

    #[test]
    fn initialize_params_with_wrong_types_are_flagged() {
        // Present-but-mistyped members must be findings, not silent passes — this
        // pins the type-predicate guard in expect_member.
        use crate::context::TraceContext;
        use crate::reader::{Limits, parse_trace};
        let doc = r#"{"seq":0,"direction":"client-to-server","transport":"stdio","kind":"message","payload":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":123,"capabilities":[],"clientInfo":"nope"}}}"#;
        let events = parse_trace(doc, &Limits::default()).expect("valid trace");
        let context = TraceContext::new(&events);
        let findings = crate::checks::find("lifecycle.initialize-params")
            .expect("check exists")
            .run(&context)
            .findings;
        assert_eq!(findings.len(), 3, "{findings:?}");
        assert!(
            findings[0]
                .detail
                .contains("protocolVersion should be a string")
        );
        assert!(
            findings[1]
                .detail
                .contains("capabilities should be an object")
        );
        assert!(
            findings[2]
                .detail
                .contains("clientInfo should be an object")
        );
    }

    #[test]
    fn initialize_result_shape_demands_capability_and_serverinfo_objects() {
        fn handshake_with_result(result: &str) -> String {
            let request = 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"}}}}"#;
            format!(
                "{request}\n{{\"seq\":1,\"direction\":\"server-to-client\",\"transport\":\"stdio\",\"kind\":\"message\",\"payload\":{{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{result}}}}}"
            )
        }
        let run = |result: &str| {
            let trace = handshake_with_result(result);
            let events = crate::reader::parse_trace(&trace, &crate::reader::Limits::default())
                .expect("trace parses");
            let context = TraceContext::new(&events);
            crate::checks::find("lifecycle.initialize-result-shape")
                .expect("check registered")
                .run(&context)
                .findings
        };

        // Complete shape: no findings.
        assert!(
            run(r#"{"protocolVersion":"2025-11-25","capabilities":{},"serverInfo":{"name":"s","version":"0"}}"#)
                .is_empty()
        );
        // Missing capabilities only.
        let missing_caps =
            run(r#"{"protocolVersion":"2025-11-25","serverInfo":{"name":"s","version":"0"}}"#);
        assert_eq!(missing_caps.len(), 1, "{missing_caps:?}");
        assert!(missing_caps[0].detail.contains("capabilities"));
        // Missing serverInfo only.
        let missing_info = run(r#"{"protocolVersion":"2025-11-25","capabilities":{}}"#);
        assert_eq!(missing_info.len(), 1, "{missing_info:?}");
        assert!(missing_info[0].detail.contains("serverInfo"));
        // Wrong types are findings too, one per member.
        let wrong = run(r#"{"capabilities":7,"serverInfo":"s"}"#);
        assert_eq!(wrong.len(), 2, "{wrong:?}");
        // No initialize result at all: the handshake checks own that case.
        let events = crate::reader::parse_trace("", &crate::reader::Limits::default()).unwrap();
        let context = TraceContext::new(&events);
        assert!(
            crate::checks::find("lifecycle.initialize-result-shape")
                .unwrap()
                .run(&context)
                .findings
                .is_empty()
        );
    }
}