swarm repositories / source
aboutsummaryrefslogtreecommitdiff
path: root/crates/libmcp-testkit/src/lib.rs
blob: 3b61bd51f94dbda02929198d38d83bd4b77970ba (plain)
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
//! Shared test helpers for `libmcp` consumers.

use libmcp::{SurfaceKind, ToolProjection};
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::{
    fs::File,
    io::{self, BufRead, BufReader},
    path::Path,
};

/// Reads an append-only JSONL file into typed records.
pub fn read_json_lines<T>(path: &Path) -> io::Result<Vec<T>>
where
    T: DeserializeOwned,
{
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    let mut records = Vec::new();
    for line in reader.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let parsed = serde_json::from_str::<T>(line.as_str()).map_err(|error| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid JSONL test record: {error}"),
            )
        })?;
        records.push(parsed);
    }
    Ok(records)
}

/// Assertion failure for projection doctrine checks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectionAssertion {
    path: String,
    message: String,
}

impl ProjectionAssertion {
    fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            message: message.into(),
        }
    }
}

impl std::fmt::Display for ProjectionAssertion {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}: {}", self.path, self.message)
    }
}

impl std::error::Error for ProjectionAssertion {}

/// Asserts that a projection obeys the doctrine implied by its surface policy.
pub fn assert_projection_doctrine<T>(projection: &T) -> Result<(), ProjectionAssertion>
where
    T: ToolProjection,
{
    let concise = projection
        .concise_projection()
        .map_err(|error| ProjectionAssertion::new("$concise", error.to_string()))?;
    let full = projection
        .full_projection()
        .map_err(|error| ProjectionAssertion::new("$full", error.to_string()))?;
    let policy = projection.projection_policy();
    if policy.forbid_opaque_ids {
        assert_no_opaque_ids(&concise)?;
        assert_no_opaque_ids(&full)?;
    }
    if policy.reference_only {
        assert_reference_only(&concise)?;
        assert_reference_only(&full)?;
    }
    if matches!(policy.kind, SurfaceKind::List) {
        assert_list_shape(&concise)?;
        assert_list_shape(&full)?;
    }
    Ok(())
}

/// Asserts that a JSON value does not leak opaque database identifiers.
pub fn assert_no_opaque_ids(value: &Value) -> Result<(), ProjectionAssertion> {
    walk(value, "$", &mut |path, value| {
        if let Value::Object(object) = value {
            for key in object.keys() {
                if key == "id" || key.ends_with("_id") {
                    return Err(ProjectionAssertion::new(
                        format!("{path}.{key}"),
                        "opaque identifier field leaked into model-facing projection",
                    ));
                }
            }
        }
        Ok(())
    })
}

/// Asserts that a list-like surface does not inline prose bodies.
pub fn assert_list_shape(value: &Value) -> Result<(), ProjectionAssertion> {
    walk(value, "$", &mut |path, value| {
        if let Value::Object(object) = value {
            for key in object.keys() {
                if matches!(
                    key.as_str(),
                    "body" | "payload_preview" | "analysis" | "rationale"
                ) {
                    return Err(ProjectionAssertion::new(
                        format!("{path}.{key}"),
                        "list surface leaked body-like content",
                    ));
                }
            }
        }
        Ok(())
    })
}

/// Asserts that a reference-only surface does not inline large textual content.
pub fn assert_reference_only(value: &Value) -> Result<(), ProjectionAssertion> {
    walk(value, "$", &mut |path, value| match value {
        Value::Object(object) => {
            for key in object.keys() {
                if matches!(key.as_str(), "body" | "content" | "text" | "bytes") {
                    return Err(ProjectionAssertion::new(
                        format!("{path}.{key}"),
                        "reference-only surface inlined artifact content",
                    ));
                }
            }
            Ok(())
        }
        _ => Ok(()),
    })
}

fn walk(
    value: &Value,
    path: &str,
    visitor: &mut impl FnMut(&str, &Value) -> Result<(), ProjectionAssertion>,
) -> Result<(), ProjectionAssertion> {
    visitor(path, value)?;
    match value {
        Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                walk(item, format!("{path}[{index}]").as_str(), visitor)?;
            }
        }
        Value::Object(object) => {
            for (key, child) in object {
                walk(child, format!("{path}.{key}").as_str(), visitor)?;
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
    Ok(())
}