kindly-guard-server 0.11.14

KindlyGuard MCP server - Enterprise-grade security for AI model interactions
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::fs;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Trait for writing MCP configurations to different file formats
pub trait ConfigWriter: Send + Sync {
    /// Write or update the configuration for kindly-guard
    fn write_config(&self, path: &Path, server_path: &str) -> Result<()>;

    /// Check if the configuration already exists
    fn config_exists(&self, path: &Path) -> Result<bool>;

    /// Create a backup of the existing configuration
    fn backup_config(&self, path: &Path) -> Result<Option<PathBuf>>;
}

/// JSON configuration writer for .mcp.json and claude_desktop_config.json
pub struct JsonConfigWriter {
    /// The server name to use in the configuration
    server_name: String,
}

impl JsonConfigWriter {
    pub fn new(server_name: impl Into<String>) -> Self {
        Self {
            server_name: server_name.into(),
        }
    }

    /// Create the kindly-guard server configuration
    fn create_server_config(&self, server_path: &str) -> Value {
        json!({
            "command": server_path,
            "args": ["--stdio"],
            "env": {}
        })
    }
}

impl ConfigWriter for JsonConfigWriter {
    fn write_config(&self, path: &Path, server_path: &str) -> Result<()> {
        info!("Writing JSON configuration to: {}", path.display());

        // Create backup if file exists
        if path.exists() {
            self.backup_config(path)?;
        }

        // Load existing config or create new
        let mut config = if path.exists() {
            let content = fs::read_to_string(path)
                .with_context(|| format!("Failed to read {}", path.display()))?;

            if content.trim().is_empty() {
                json!({})
            } else {
                serde_json::from_str(&content)
                    .with_context(|| format!("Failed to parse JSON in {}", path.display()))?
            }
        } else {
            // Create parent directory if needed
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("Failed to create directory {}", parent.display()))?;
            }
            json!({})
        };

        // Ensure mcpServers exists
        if !config.is_object() {
            config = json!({});
        }

        let obj = config.as_object_mut().unwrap();
        if !obj.contains_key("mcpServers") {
            obj.insert("mcpServers".to_string(), json!({}));
        }

        // Add kindly-guard configuration
        let servers = obj.get_mut("mcpServers").unwrap();
        if let Some(servers_obj) = servers.as_object_mut() {
            servers_obj.insert(
                self.server_name.clone(),
                self.create_server_config(server_path),
            );
        }

        // Write formatted JSON
        let formatted = serde_json::to_string_pretty(&config)?;
        fs::write(path, formatted)
            .with_context(|| format!("Failed to write configuration to {}", path.display()))?;

        info!("Successfully wrote configuration to {}", path.display());
        Ok(())
    }

    fn config_exists(&self, path: &Path) -> Result<bool> {
        if !path.exists() {
            return Ok(false);
        }

        let content = fs::read_to_string(path)?;
        if content.trim().is_empty() {
            return Ok(false);
        }

        let config: Value = serde_json::from_str(&content)?;

        // Check if kindly-guard is already configured
        if let Some(servers) = config.get("mcpServers").and_then(|s| s.as_object()) {
            Ok(servers.contains_key(&self.server_name))
        } else {
            Ok(false)
        }
    }

    fn backup_config(&self, path: &Path) -> Result<Option<PathBuf>> {
        let backup_path = path.with_extension("json.backup");

        debug!("Creating backup at: {}", backup_path.display());
        fs::copy(path, &backup_path)
            .with_context(|| format!("Failed to create backup of {}", path.display()))?;

        Ok(Some(backup_path))
    }
}

/// JSON configuration writer for settings.local.json (Windsurf variant)
pub struct JsonLocalConfigWriter {
    server_name: String,
}

impl JsonLocalConfigWriter {
    pub fn new(server_name: impl Into<String>) -> Self {
        Self {
            server_name: server_name.into(),
        }
    }

    fn create_server_config(&self, server_path: &str) -> Value {
        json!({
            "provider": "stdio",
            "command": server_path,
            "args": ["--stdio"],
            "env": {}
        })
    }
}

impl ConfigWriter for JsonLocalConfigWriter {
    fn write_config(&self, path: &Path, server_path: &str) -> Result<()> {
        info!("Writing JSON local configuration to: {}", path.display());

        // Create backup if file exists
        if path.exists() {
            self.backup_config(path)?;
        }

        // Load existing config or create new
        let mut config = if path.exists() {
            let content = fs::read_to_string(path)
                .with_context(|| format!("Failed to read {}", path.display()))?;

            if content.trim().is_empty() {
                json!({})
            } else {
                serde_json::from_str(&content)
                    .with_context(|| format!("Failed to parse JSON in {}", path.display()))?
            }
        } else {
            // Create parent directory if needed
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("Failed to create directory {}", parent.display()))?;
            }
            json!({})
        };

        // Ensure correct structure
        if !config.is_object() {
            config = json!({});
        }

        let obj = config.as_object_mut().unwrap();

        // Initialize mcpServers if not present
        if !obj.contains_key("mcpServers") {
            obj.insert("mcpServers".to_string(), json!({}));
        }

        // Add kindly-guard configuration
        let servers = obj.get_mut("mcpServers").unwrap();
        if let Some(servers_obj) = servers.as_object_mut() {
            servers_obj.insert(
                self.server_name.clone(),
                self.create_server_config(server_path),
            );
        }

        // Write formatted JSON
        let formatted = serde_json::to_string_pretty(&config)?;
        fs::write(path, formatted)
            .with_context(|| format!("Failed to write configuration to {}", path.display()))?;

        info!("Successfully wrote configuration to {}", path.display());
        Ok(())
    }

    fn config_exists(&self, path: &Path) -> Result<bool> {
        if !path.exists() {
            return Ok(false);
        }

        let content = fs::read_to_string(path)?;
        if content.trim().is_empty() {
            return Ok(false);
        }

        let config: Value = serde_json::from_str(&content)?;

        // Check if kindly-guard is already configured
        if let Some(servers) = config.get("mcpServers").and_then(|s| s.as_object()) {
            Ok(servers.contains_key(&self.server_name))
        } else {
            Ok(false)
        }
    }

    fn backup_config(&self, path: &Path) -> Result<Option<PathBuf>> {
        let backup_path = path.with_extension("json.backup");

        debug!("Creating backup at: {}", backup_path.display());
        fs::copy(path, &backup_path)
            .with_context(|| format!("Failed to create backup of {}", path.display()))?;

        Ok(Some(backup_path))
    }
}

/// TOML configuration writer (future support)
#[allow(dead_code)]
pub struct TomlConfigWriter {
    server_name: String,
}

impl TomlConfigWriter {
    pub fn new(server_name: impl Into<String>) -> Self {
        Self {
            server_name: server_name.into(),
        }
    }
}

impl ConfigWriter for TomlConfigWriter {
    fn write_config(&self, _path: &Path, _server_path: &str) -> Result<()> {
        warn!("TOML configuration format not yet implemented");
        Ok(())
    }

    fn config_exists(&self, _path: &Path) -> Result<bool> {
        Ok(false)
    }

    fn backup_config(&self, _path: &Path) -> Result<Option<PathBuf>> {
        Ok(None)
    }
}

/// YAML configuration writer for VS Code variants
pub struct YamlConfigWriter {
    _server_name: String,
}

impl YamlConfigWriter {
    pub fn new(server_name: impl Into<String>) -> Self {
        Self {
            _server_name: server_name.into(),
        }
    }
}

impl ConfigWriter for YamlConfigWriter {
    fn write_config(&self, _path: &Path, _server_path: &str) -> Result<()> {
        warn!("YAML configuration format not yet implemented");
        Ok(())
    }

    fn config_exists(&self, _path: &Path) -> Result<bool> {
        Ok(false)
    }

    fn backup_config(&self, _path: &Path) -> Result<Option<PathBuf>> {
        Ok(None)
    }
}

/// Factory function to create appropriate config writer based on file extension
pub fn create_config_writer(path: &Path, server_name: &str) -> Box<dyn ConfigWriter> {
    let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("");

    match extension {
        "json" => {
            // Check if it's a local settings file
            if path
                .file_name()
                .and_then(|name| name.to_str())
                .map(|name| name.contains("local"))
                .unwrap_or(false)
            {
                Box::new(JsonLocalConfigWriter::new(server_name))
            } else {
                Box::new(JsonConfigWriter::new(server_name))
            }
        },
        "toml" => Box::new(TomlConfigWriter::new(server_name)),
        "yaml" | "yml" => Box::new(YamlConfigWriter::new(server_name)),
        _ => Box::new(JsonConfigWriter::new(server_name)), // Default to JSON
    }
}

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

    #[test]
    fn test_json_writer_new_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test.json");

        let writer = JsonConfigWriter::new("kindly-guard");
        writer
            .write_config(&config_path, "/usr/local/bin/kindly-guard")
            .unwrap();

        let content = fs::read_to_string(&config_path).unwrap();
        let config: Value = serde_json::from_str(&content).unwrap();

        assert!(config.get("mcpServers").is_some());
        let servers = config.get("mcpServers").unwrap();
        assert!(servers.get("kindly-guard").is_some());

        let kg_config = servers.get("kindly-guard").unwrap();
        assert_eq!(
            kg_config.get("command").unwrap(),
            "/usr/local/bin/kindly-guard"
        );
        assert_eq!(kg_config.get("args").unwrap(), &json!(["--stdio"]));
    }

    #[test]
    fn test_json_writer_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test.json");

        // Create existing config
        let existing = json!({
            "mcpServers": {
                "other-server": {
                    "command": "/path/to/other",
                    "args": []
                }
            }
        });
        fs::write(
            &config_path,
            serde_json::to_string_pretty(&existing).unwrap(),
        )
        .unwrap();

        let writer = JsonConfigWriter::new("kindly-guard");
        writer
            .write_config(&config_path, "/usr/local/bin/kindly-guard")
            .unwrap();

        let content = fs::read_to_string(&config_path).unwrap();
        let config: Value = serde_json::from_str(&content).unwrap();

        let servers = config.get("mcpServers").unwrap().as_object().unwrap();
        assert_eq!(servers.len(), 2);
        assert!(servers.contains_key("other-server"));
        assert!(servers.contains_key("kindly-guard"));
    }

    #[test]
    fn test_config_exists() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test.json");

        let writer = JsonConfigWriter::new("kindly-guard");

        // Should not exist initially
        assert!(!writer.config_exists(&config_path).unwrap());

        // Write config
        writer
            .write_config(&config_path, "/usr/local/bin/kindly-guard")
            .unwrap();

        // Should exist now
        assert!(writer.config_exists(&config_path).unwrap());
    }

    #[test]
    fn test_backup_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test.json");

        // Create initial file
        fs::write(&config_path, "{}").unwrap();

        let writer = JsonConfigWriter::new("kindly-guard");
        let backup_path = writer.backup_config(&config_path).unwrap().unwrap();

        assert!(backup_path.exists());
        assert_eq!(backup_path.extension().unwrap(), "backup");
    }

    #[test]
    fn test_local_settings_format() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("settings.local.json");

        let writer = JsonLocalConfigWriter::new("kindly-guard");
        writer
            .write_config(&config_path, "/usr/local/bin/kindly-guard")
            .unwrap();

        let content = fs::read_to_string(&config_path).unwrap();
        let config: Value = serde_json::from_str(&content).unwrap();

        let kg_config = config
            .get("mcpServers")
            .unwrap()
            .get("kindly-guard")
            .unwrap();
        assert_eq!(kg_config.get("provider").unwrap(), "stdio");
        assert_eq!(
            kg_config.get("command").unwrap(),
            "/usr/local/bin/kindly-guard"
        );
    }
}