Skip to main content

codecov_rust_mcp/
tool_args.rs

1//! JSON-schema parameter structs for rmcp `Parameters<T>` tool handlers.
2
3use schemars::JsonSchema;
4use serde::Deserialize;
5
6// Spell out Unicode White_Space: ECMAScript \s differs from Rust's trim().
7const NON_WHITESPACE_PATTERN: &str =
8    r"[^\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]";
9const REPOSITORY_PATH_PATTERN: &str = r"^(?!/)(?![A-Za-z]:/)(?!.*\\)(?!.*[\x00-\x1F\x7F-\x9F])(?![\u0009-\u000D\u0020\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]*$)(?:(?!\.{1,2}(?:/|$))[^/]+)(?:/(?!\.{1,2}(?:/|$))[^/]+)*$";
10
11/// Shared owner/repo/branch/sha selectors for Codecov repo tools.
12#[derive(Debug, Deserialize, JsonSchema)]
13pub struct RepoArgs {
14    /// GitHub owner or org (e.g. `Interchouette-ITC`).
15    #[schemars(length(min = 1))]
16    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
17    pub owner: String,
18    /// Repository name (e.g. `rustashop`).
19    #[schemars(length(min = 1))]
20    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
21    pub repo: String,
22    /// Branch head to query when `sha` is omitted.
23    #[serde(default)]
24    #[schemars(length(min = 1))]
25    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
26    pub branch: Option<String>,
27    /// Commit SHA; when set, takes precedence over `branch` on the API.
28    #[serde(default)]
29    #[schemars(length(min = 1))]
30    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
31    pub sha: Option<String>,
32}
33
34impl RepoArgs {
35    /// Validates all repository selectors before making an API request.
36    ///
37    /// # Errors
38    ///
39    /// Returns an error when a required selector is empty or whitespace-only.
40    pub fn validate(&self) -> Result<(), String> {
41        validate_repo_fields(
42            &self.owner,
43            &self.repo,
44            self.branch.as_deref(),
45            self.sha.as_deref(),
46        )
47    }
48}
49
50/// Arguments for `codecov_miss_files`.
51#[derive(Debug, Deserialize, JsonSchema)]
52pub struct MissFilesArgs {
53    /// GitHub owner or org.
54    #[schemars(length(min = 1))]
55    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
56    pub owner: String,
57    /// Repository name.
58    #[schemars(length(min = 1))]
59    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
60    pub repo: String,
61    /// Branch head to query when `sha` is omitted.
62    #[serde(default)]
63    #[schemars(length(min = 1))]
64    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
65    pub branch: Option<String>,
66    /// Commit SHA.
67    #[serde(default)]
68    #[schemars(length(min = 1))]
69    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
70    pub sha: Option<String>,
71    /// Max files to return (default 30). Use `0` for uncapped; this limits output, not the Codecov report fetched.
72    #[serde(default)]
73    pub limit: Option<u32>,
74}
75
76impl MissFilesArgs {
77    /// Validates all repository selectors before making an API request.
78    ///
79    /// # Errors
80    ///
81    /// Returns an error when a required selector is empty or whitespace-only.
82    pub fn validate(&self) -> Result<(), String> {
83        validate_repo_fields(
84            &self.owner,
85            &self.repo,
86            self.branch.as_deref(),
87            self.sha.as_deref(),
88        )
89    }
90}
91
92/// Arguments for `codecov_file_report`.
93#[derive(Debug, Deserialize, JsonSchema)]
94pub struct FileReportArgs {
95    /// GitHub owner or org.
96    #[schemars(length(min = 1))]
97    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
98    pub owner: String,
99    /// Repository name.
100    #[schemars(length(min = 1))]
101    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
102    pub repo: String,
103    /// Slash-delimited repository-relative path; absolute paths, empty segments, dot segments, backslashes, and control characters are rejected.
104    #[schemars(length(min = 1))]
105    #[schemars(regex(pattern = REPOSITORY_PATH_PATTERN))]
106    pub path: String,
107    /// Branch head to query when `sha` is omitted.
108    #[serde(default)]
109    #[schemars(length(min = 1))]
110    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
111    pub branch: Option<String>,
112    /// Commit SHA.
113    #[serde(default)]
114    #[schemars(length(min = 1))]
115    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
116    pub sha: Option<String>,
117}
118
119impl FileReportArgs {
120    /// Validates all file-report selectors before making an API request.
121    ///
122    /// # Errors
123    ///
124    /// Returns an error when a required selector is empty or whitespace-only, or the path is not repository-relative.
125    pub fn validate(&self) -> Result<(), String> {
126        validate_repo_fields(
127            &self.owner,
128            &self.repo,
129            self.branch.as_deref(),
130            self.sha.as_deref(),
131        )?;
132        validate_repository_relative_path(&self.path)
133    }
134}
135
136/// Arguments for `codecov_pr_report`.
137#[derive(Debug, Deserialize, JsonSchema)]
138pub struct PullReportArgs {
139    /// GitHub owner or org (e.g. `Interchouette-ITC`).
140    #[schemars(length(min = 1))]
141    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
142    pub owner: String,
143    /// Repository name (e.g. `rangular`).
144    #[schemars(length(min = 1))]
145    #[schemars(regex(pattern = NON_WHITESPACE_PATTERN))]
146    pub repo: String,
147    /// Pull request number from the PR URL (e.g. `97`).
148    #[schemars(range(min = 1))]
149    pub pull_id: u64,
150}
151
152impl PullReportArgs {
153    /// Validates the pull request selector before making an API request.
154    ///
155    /// # Errors
156    ///
157    /// Returns an error when the repository selectors are empty or the pull ID is zero.
158    pub fn validate(&self) -> Result<(), String> {
159        validate_repo_fields(&self.owner, &self.repo, None, None)?;
160        if self.pull_id == 0 {
161            return Err("pull_id must be greater than zero".into());
162        }
163        Ok(())
164    }
165}
166
167fn validate_repo_fields(
168    owner: &str,
169    repo: &str,
170    branch: Option<&str>,
171    sha: Option<&str>,
172) -> Result<(), String> {
173    validate_nonempty("owner", owner)?;
174    validate_nonempty("repo", repo)?;
175    if let Some(branch) = branch {
176        validate_nonempty("branch", branch)?;
177    }
178    if let Some(sha) = sha {
179        validate_nonempty("sha", sha)?;
180    }
181    Ok(())
182}
183
184fn validate_nonempty(name: &str, value: &str) -> Result<(), String> {
185    if value.trim().is_empty() {
186        Err(format!("{name} must not be empty"))
187    } else {
188        Ok(())
189    }
190}
191
192fn validate_repository_relative_path(path: &str) -> Result<(), String> {
193    validate_nonempty("path", path)?;
194    let bytes = path.as_bytes();
195    let drive_absolute = bytes.len() >= 3
196        && bytes[0].is_ascii_alphabetic()
197        && bytes[1] == b':'
198        && matches!(bytes[2], b'/' | b'\\');
199    let invalid = path.starts_with('/')
200        || path.starts_with('\\')
201        || path.contains('\\')
202        || drive_absolute
203        || path.chars().any(char::is_control)
204        || path
205            .split('/')
206            .any(|segment| segment.is_empty() || matches!(segment, "." | ".."));
207    if invalid {
208        return Err(
209            "path must be a slash-delimited repository-relative path without control characters or empty, `.` or `..` segments"
210                .into(),
211        );
212    }
213    Ok(())
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn validates_required_and_optional_selectors() {
222        let args = RepoArgs {
223            owner: " ".into(),
224            repo: "repo".into(),
225            branch: Some("main".into()),
226            sha: None,
227        };
228        assert_eq!(args.validate().unwrap_err(), "owner must not be empty");
229
230        let args = RepoArgs {
231            owner: "owner".into(),
232            repo: "repo".into(),
233            branch: Some(" ".into()),
234            sha: None,
235        };
236        assert_eq!(args.validate().unwrap_err(), "branch must not be empty");
237
238        let args = RepoArgs {
239            owner: "owner".into(),
240            repo: "repo".into(),
241            branch: None,
242            sha: Some(String::new()),
243        };
244        assert_eq!(args.validate().unwrap_err(), "sha must not be empty");
245
246        let args = FileReportArgs {
247            owner: "owner".into(),
248            repo: "repo".into(),
249            path: String::new(),
250            branch: None,
251            sha: None,
252        };
253        assert_eq!(args.validate().unwrap_err(), "path must not be empty");
254
255        let args = PullReportArgs {
256            owner: "owner".into(),
257            repo: "repo".into(),
258            pull_id: 0,
259        };
260        assert_eq!(
261            args.validate().unwrap_err(),
262            "pull_id must be greater than zero"
263        );
264    }
265
266    #[test]
267    fn validates_file_paths_without_normalizing_them() {
268        let args = |path: &str| FileReportArgs {
269            owner: "owner".into(),
270            repo: "repo".into(),
271            path: path.into(),
272            branch: None,
273            sha: None,
274        };
275        assert!(args("src/dir with spaces/λ.rs").validate().is_ok());
276
277        for path in [
278            "/absolute/path",
279            "C:/absolute/path",
280            "../outside",
281            "src/../outside",
282            "src/./file.rs",
283            "src//file.rs",
284            "src/file.rs/",
285            r"src\file.rs",
286            "src/\nfile.rs",
287            " ",
288        ] {
289            assert!(
290                args(path).validate().is_err(),
291                "accepted invalid path {path:?}"
292            );
293        }
294    }
295
296    #[test]
297    fn schemas_include_string_and_pull_id_constraints() {
298        for schema in [
299            schemars::schema_for!(RepoArgs),
300            schemars::schema_for!(MissFilesArgs),
301            schemars::schema_for!(FileReportArgs),
302            schemars::schema_for!(PullReportArgs),
303        ] {
304            let schema = serde_json::to_value(schema).expect("serialize tool args schema");
305            for field in ["owner", "repo", "branch", "sha"] {
306                let Some(property) = schema["properties"].get(field) else {
307                    continue;
308                };
309                assert_eq!(property["minLength"], 1, "{field}");
310                assert_eq!(property["pattern"], NON_WHITESPACE_PATTERN, "{field}");
311                if matches!(field, "branch" | "sha") {
312                    assert_eq!(property["type"], serde_json::json!(["string", "null"]));
313                    assert!(!schema["required"]
314                        .as_array()
315                        .expect("required fields")
316                        .contains(&serde_json::json!(field)));
317                }
318            }
319        }
320
321        let pull_schema = serde_json::to_value(schemars::schema_for!(PullReportArgs))
322            .expect("serialize pull args schema");
323        assert_eq!(pull_schema["properties"]["pull_id"]["minimum"], 1);
324
325        let file_schema = serde_json::to_value(schemars::schema_for!(FileReportArgs))
326            .expect("serialize file args schema");
327        assert_eq!(file_schema["properties"]["path"]["minLength"], 1);
328        assert_eq!(
329            file_schema["properties"]["path"]["pattern"],
330            REPOSITORY_PATH_PATTERN
331        );
332    }
333
334    #[test]
335    fn schema_patterns_match_runtime_whitespace_validation() {
336        let selector = fancy_regex::Regex::new(NON_WHITESPACE_PATTERN).expect("selector pattern");
337        let path = fancy_regex::Regex::new(REPOSITORY_PATH_PATTERN).expect("path pattern");
338        let whitespace = "\u{0009}\u{000A}\u{000B}\u{000C}\u{000D}\u{0020}\u{0085}\u{00A0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}";
339        let mut values = vec![
340            String::new(),
341            whitespace.into(),
342            "owner".into(),
343            " feature/branch ".into(),
344            "\u{180E}".into(),
345            "\u{200B}".into(),
346            "\u{FEFF}".into(),
347            "src/λ.rs".into(),
348        ];
349        for character in whitespace.chars() {
350            values.push(character.to_string());
351            values.push(format!("{character}value{character}"));
352        }
353        for value in values {
354            assert_eq!(
355                selector.is_match(&value).expect("match selector"),
356                validate_nonempty("selector", &value).is_ok(),
357                "selector: {value:?}"
358            );
359            assert_eq!(
360                path.is_match(&value).expect("match path"),
361                validate_repository_relative_path(&value).is_ok(),
362                "path: {value:?}"
363            );
364        }
365    }
366}