rust-mcp-server 0.3.8

An MCP server for Rust development
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
417
418
419
420
421
422
423
424
425
use rmcp::ErrorData;

use crate::globals;

#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
#[serde(transparent)]
pub struct Registry {
    #[serde(deserialize_with = "deserialize_string")]
    value: Option<String>,
}

impl Registry {
    pub fn value(&self) -> Option<&str> {
        self.value
            .as_deref()
            .or_else(|| globals::get_default_registry())
    }
}

impl schemars::JsonSchema for Registry {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("string")
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("string")
    }

    fn inline_schema() -> bool {
        true
    }

    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({ "type": "string", "default": null })
    }
}

/// Utility function for parsing Option<String> fields in serde,
/// returning None if the string is "null" (case-insensitive) or empty.
pub fn deserialize_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;

    let opt = Option::<String>::deserialize(deserializer)?;
    match opt.as_deref() {
        Some("null") | Some("") => Ok(None),
        _ => Ok(opt),
    }
}

/// Utility function for parsing Option<Vec<String>> fields in serde,
/// returning None if the value is a string "null" (case-insensitive) or empty.
pub fn deserialize_string_vec<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    use serde_json::Value;

    let value = Value::deserialize(deserializer)?;
    match value {
        Value::Null => Ok(None),
        Value::String(s) if s.to_lowercase() == "null" || s.is_empty() => Ok(None),
        Value::String(s) => Ok(Some(vec![s])),
        Value::Array(arr) => {
            let strings: Result<Vec<String>, _> = arr
                .into_iter()
                .map(|v| match v {
                    Value::String(s) => Ok(s),
                    _ => Err(serde::de::Error::custom("Expected string in array")),
                })
                .collect();
            Ok(Some(strings?))
        }
        _ => Err(serde::de::Error::custom("Expected array or null")),
    }
}

/// Convert locking mode string to CLI flags for cargo commands.
/// Returns a vector of flags to add to the command.
///
/// Valid modes:
/// - "locked" (default): Assert that `Cargo.lock` will remain unchanged
/// - "unlocked": Allow `Cargo.lock` to be updated  
/// - "offline": Run without accessing the network
/// - "frozen": Equivalent to specifying both --locked and --offline
pub fn locking_mode_to_cli_flags(
    mode: Option<&str>,
    preferred: &str,
) -> Result<Vec<&'static str>, ErrorData> {
    Ok(match mode.unwrap_or(preferred) {
        "locked" => vec!["--locked"],
        "unlocked" => vec![], // No flags needed
        "offline" => vec!["--offline"],
        "frozen" => vec!["--frozen"],
        unknown => {
            return Err(ErrorData::invalid_params(
                format!(
                    "Unknown locking mode: {unknown}. Valid options are: locked, unlocked, offline, frozen"
                ),
                None,
            ));
        }
    })
}

/// Convert output verbosity string to CLI flags for cargo commands.
/// Returns a vector of flags to add to the command.
///
/// Valid modes:
/// - "quiet" (default): Show only the essential command output
/// - "normal": Show standard output (no additional flags)
/// - "verbose": Show detailed output including build information
pub fn output_verbosity_to_cli_flags(mode: Option<&str>) -> Result<Vec<&'static str>, ErrorData> {
    Ok(match mode.unwrap_or("quiet") {
        "quiet" => vec!["--quiet"],
        "normal" => vec![], // No flags needed
        "verbose" => vec!["--verbose"],
        unknown => {
            return Err(ErrorData::invalid_params(
                format!(
                    "Unknown output verbosity: {unknown}. Valid options are: quiet, normal, verbose"
                ),
                None,
            ));
        }
    })
}

/// A type that represents a package with an optional version.
/// When calling cargo commands, use `to_spec()` to get "package" or "package@version" format.
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, schemars::JsonSchema)]
pub struct PackageWithVersion {
    /// The package name
    pub package: String,
    /// Optional version specification
    #[serde(default, deserialize_with = "deserialize_string")]
    pub version: Option<String>,
}

impl PackageWithVersion {
    /// Create a new PackageWithVersion with just a package name
    #[cfg(test)]
    pub fn new(package: String) -> Self {
        Self {
            package,
            version: None,
        }
    }

    /// Create a new PackageWithVersion with a package name and version
    #[cfg(test)]
    pub fn with_version(package: String, version: String) -> Self {
        Self {
            package,
            version: Some(version),
        }
    }

    /// Get the formatted string representation (package or package@version)
    pub fn to_spec(&self) -> String {
        match &self.version {
            Some(version) => format!("{}@{}", self.package, version),
            None => self.package.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct TestString {
        #[serde(deserialize_with = "deserialize_string")]
        value: Option<String>,
    }

    #[derive(Debug, serde::Deserialize, PartialEq)]
    struct TestStringVec {
        #[serde(deserialize_with = "deserialize_string_vec")]
        value: Option<Vec<String>>,
    }

    #[test]
    fn test_deserialize_string_some() {
        let json = r#"{ "value": "hello" }"#;
        let result: TestString = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, Some("hello".to_string()));
    }

    #[test]
    fn test_deserialize_string_null_string() {
        let json = r#"{ "value": "null" }"#;
        let result: TestString = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_null_value() {
        let json = r#"{ "value": null }"#;
        let result: TestString = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_empty_string() {
        let json = r#"{ "value": "" }"#;
        let result: TestString = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_vec_some() {
        let json = r#"{ "value": ["a", "b", "c"] }"#;
        let result: TestStringVec = serde_json::from_str(json).unwrap();
        assert_eq!(
            result.value,
            Some(vec!["a".to_string(), "b".to_string(), "c".to_string()])
        );
    }

    #[test]
    fn test_deserialize_string_vec_null_string() {
        let json = r#"{ "value": "null" }"#;
        let result: TestStringVec = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_vec_null_value() {
        let json = r#"{ "value": null }"#;
        let result: TestStringVec = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_vec_empty_string() {
        let json = r#"{ "value": "" }"#;
        let result: TestStringVec = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, None);
    }

    #[test]
    fn test_deserialize_string_vec_empty_array() {
        let json = r#"{ "value": [] }"#;
        let result: TestStringVec = serde_json::from_str(json).unwrap();
        assert_eq!(result.value, Some(vec![]));
    }

    #[test]
    fn test_deserialize_string_vec_invalid_element() {
        let json = r#"{ "value": [1, 2, 3] }"#;
        let result: Result<TestStringVec, _> = serde_json::from_str(json);
        assert!(result.is_err());
    }

    // PackageWithVersion tests

    #[test]
    fn test_package_with_version_new() {
        let pkg = PackageWithVersion::new("serde".to_string());
        assert_eq!(pkg.package, "serde");
        assert_eq!(pkg.version, None);
        assert_eq!(pkg.to_spec(), "serde");
    }

    #[test]
    fn test_package_with_version_with_version() {
        let pkg = PackageWithVersion::with_version("serde".to_string(), "1.0.0".to_string());
        assert_eq!(pkg.package, "serde");
        assert_eq!(pkg.version, Some("1.0.0".to_string()));
        assert_eq!(pkg.to_spec(), "serde@1.0.0");
    }

    #[test]
    fn test_package_with_version_deserialize_package_only() {
        let json = r#"{"package":"serde"}"#;
        let result: PackageWithVersion = serde_json::from_str(json).unwrap();
        assert_eq!(result.package, "serde");
        assert_eq!(result.version, None);
    }

    #[test]
    fn test_package_with_version_deserialize_package_with_version() {
        let json = r#"{"package":"serde","version":"1.0.0"}"#;
        let result: PackageWithVersion = serde_json::from_str(json).unwrap();
        assert_eq!(result.package, "serde");
        assert_eq!(result.version, Some("1.0.0".to_string()));
    }

    #[test]
    fn test_package_with_version_deserialize_null_version() {
        let json = r#"{"package":"serde","version":null}"#;
        let result: PackageWithVersion = serde_json::from_str(json).unwrap();
        assert_eq!(result.package, "serde");
        assert_eq!(result.version, None);
    }

    #[test]
    fn test_package_with_version_deserialize_version_null_string() {
        let json = r#"{"package":"serde","version":"null"}"#;
        let result: PackageWithVersion = serde_json::from_str(json).unwrap();
        assert_eq!(result.package, "serde");
        assert_eq!(result.version, None); // "null" string is treated as None by deserialize_string
    }

    #[test]
    fn test_package_with_version_to_spec() {
        let pkg1 = PackageWithVersion::new("serde".to_string());
        assert_eq!(pkg1.to_spec(), "serde");

        let pkg2 = PackageWithVersion::with_version("tokio".to_string(), "1.0.0".to_string());
        assert_eq!(pkg2.to_spec(), "tokio@1.0.0");

        let pkg3 = PackageWithVersion::with_version("clap".to_string(), "4.0.0-beta.1".to_string());
        assert_eq!(pkg3.to_spec(), "clap@4.0.0-beta.1");
    }

    #[test]
    fn test_locking_mode_cli_flags() {
        // Test default (locked)
        assert_eq!(
            locking_mode_to_cli_flags(None, "locked").unwrap(),
            vec!["--locked"]
        );

        // Test explicit modes
        assert_eq!(
            locking_mode_to_cli_flags(Some("locked"), "locked").unwrap(),
            vec!["--locked"]
        );
        assert_eq!(
            locking_mode_to_cli_flags(Some("unlocked"), "locked").unwrap(),
            Vec::<&str>::new()
        );
        assert_eq!(
            locking_mode_to_cli_flags(Some("offline"), "locked").unwrap(),
            vec!["--offline"]
        );
        assert_eq!(
            locking_mode_to_cli_flags(Some("frozen"), "locked").unwrap(),
            vec!["--frozen"]
        );

        // Test unknown values return error
        assert!(locking_mode_to_cli_flags(Some("invalid"), "locked").is_err());
        let error = locking_mode_to_cli_flags(Some("invalid"), "locked").unwrap_err();
        assert!(error.to_string().contains("Unknown locking mode: invalid"));

        // Test with unlocked as preferred
        assert_eq!(
            locking_mode_to_cli_flags(None, "unlocked").unwrap(),
            Vec::<&str>::new()
        );
        assert_eq!(
            locking_mode_to_cli_flags(Some("locked"), "unlocked").unwrap(),
            vec!["--locked"]
        );
    }

    #[test]
    fn test_output_verbosity_to_cli_flags() {
        // Test default (quiet)
        assert_eq!(
            output_verbosity_to_cli_flags(None).unwrap(),
            vec!["--quiet"]
        );

        // Test explicit modes
        assert_eq!(
            output_verbosity_to_cli_flags(Some("quiet")).unwrap(),
            vec!["--quiet"]
        );
        assert_eq!(
            output_verbosity_to_cli_flags(Some("normal")).unwrap(),
            Vec::<&str>::new()
        );
        assert_eq!(
            output_verbosity_to_cli_flags(Some("verbose")).unwrap(),
            vec!["--verbose"]
        );

        // Test unknown values return error
        assert!(output_verbosity_to_cli_flags(Some("invalid")).is_err());
        let error = output_verbosity_to_cli_flags(Some("invalid")).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("Unknown output verbosity: invalid")
        );
    }

    #[test]
    fn test_output_verbosity_cli_flags() {
        // Test default (quiet)
        assert_eq!(
            output_verbosity_to_cli_flags(None).unwrap(),
            vec!["--quiet"]
        );

        // Test explicit quiet
        assert_eq!(
            output_verbosity_to_cli_flags(Some("quiet")).unwrap(),
            vec!["--quiet"]
        );

        // Test normal (no flags)
        assert_eq!(
            output_verbosity_to_cli_flags(Some("normal")).unwrap(),
            Vec::<&'static str>::new()
        );

        // Test verbose
        assert_eq!(
            output_verbosity_to_cli_flags(Some("verbose")).unwrap(),
            vec!["--verbose"]
        );

        // Test invalid option
        assert!(output_verbosity_to_cli_flags(Some("invalid")).is_err());
    }
}