jarvy 0.0.5

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
//! MCP Audit Logging
//!
//! Logs all MCP requests to an audit file for security and debugging purposes.
//!
//! ## Log Format
//!
//! Each log entry is a JSON object on a single line:
//!
//! ```json
//! {"timestamp":"2024-01-15T10:30:00Z","action":"install","tool":"docker","success":true,"version":"24.0.7","duration_ms":45000,"client":"claude-desktop"}
//! ```

use crate::mcp::config::McpConfig;
use crate::mcp::error::{McpError, McpResult};
use serde::Serialize;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::SystemTime;

/// Audit logger for MCP operations
pub struct AuditLog {
    /// Path to the audit log file
    path: PathBuf,
    /// File handle (lazily opened)
    file: Mutex<Option<File>>,
    /// Whether logging is enabled
    enabled: bool,
}

impl AuditLog {
    /// Create a new audit logger from configuration
    pub fn new(config: &McpConfig) -> McpResult<Self> {
        let path = config.audit_log_path()?;

        Ok(Self {
            path,
            file: Mutex::new(None),
            enabled: true,
        })
    }

    /// Create a disabled audit logger (for testing)
    pub fn disabled() -> Self {
        Self {
            path: PathBuf::new(),
            file: Mutex::new(None),
            enabled: false,
        }
    }

    /// Log an audit entry
    pub fn log(&self, entry: AuditEntry) -> McpResult<()> {
        if !self.enabled {
            return Ok(());
        }

        let mut file_guard = self
            .file
            .lock()
            .map_err(|_| McpError::internal_error("Audit log lock poisoned"))?;

        // Lazy open the file
        if file_guard.is_none() {
            // Ensure parent directory exists
            if let Some(parent) = self.path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            let file = OpenOptions::new()
                .create(true)
                .append(true)
                .open(&self.path)?;

            *file_guard = Some(file);
        }

        if let Some(ref mut file) = *file_guard {
            let json = serde_json::to_string(&entry)?;
            writeln!(file, "{}", json)?;
            file.flush()?;
        }

        Ok(())
    }

    /// Log a tool list request
    pub fn log_list_tools(&self, client: Option<&str>, count: usize) {
        let _ = self.log(
            AuditEntry::new(AuditAction::ListTools)
                .with_client(client)
                .with_data("count", serde_json::json!(count)),
        );
    }

    /// Log a tool check request
    pub fn log_check_tool(
        &self,
        client: Option<&str>,
        tool: &str,
        installed: bool,
        version: Option<&str>,
    ) {
        let _ = self.log(
            AuditEntry::new(AuditAction::CheckTool)
                .with_client(client)
                .with_tool(tool)
                .with_success(installed)
                .with_version(version),
        );
    }

    /// Log a tool install request (dry run)
    pub fn log_install_dry_run(&self, client: Option<&str>, tool: &str, command: &str) {
        let _ = self.log(
            AuditEntry::new(AuditAction::InstallDryRun)
                .with_client(client)
                .with_tool(tool)
                .with_data("command", serde_json::json!(command)),
        );
    }

    /// Log a tool install request (actual)
    pub fn log_install(
        &self,
        client: Option<&str>,
        tool: &str,
        success: bool,
        version: Option<&str>,
        duration_ms: u64,
        error: Option<&str>,
    ) {
        let mut entry = AuditEntry::new(AuditAction::Install)
            .with_client(client)
            .with_tool(tool)
            .with_success(success)
            .with_duration(duration_ms);

        if let Some(v) = version {
            entry = entry.with_version(Some(v));
        }
        if let Some(e) = error {
            entry = entry.with_data("error", serde_json::json!(e));
        }

        let _ = self.log(entry);
    }

    /// Log a user cancellation
    pub fn log_cancelled(&self, client: Option<&str>, tool: &str) {
        let _ = self.log(
            AuditEntry::new(AuditAction::Cancelled)
                .with_client(client)
                .with_tool(tool),
        );
    }

    /// Log a rate limit hit
    pub fn log_rate_limited(&self, client: Option<&str>, action: &str) {
        let _ = self.log(
            AuditEntry::new(AuditAction::RateLimited)
                .with_client(client)
                .with_data("attempted_action", serde_json::json!(action)),
        );
    }

    /// Log a denied tool access
    #[allow(dead_code)] // Public API for MCP audit logging
    pub fn log_denied(&self, client: Option<&str>, tool: &str, reason: &str) {
        let _ = self.log(
            AuditEntry::new(AuditAction::Denied)
                .with_client(client)
                .with_tool(tool)
                .with_data("reason", serde_json::json!(reason)),
        );
    }
}

/// Actions that can be logged
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditAction {
    /// List available tools
    ListTools,
    /// Check a tool's status
    CheckTool,
    /// Dry-run install
    InstallDryRun,
    /// Actual install
    Install,
    /// User cancelled
    Cancelled,
    /// Rate limited
    RateLimited,
    /// Tool denied (allowlist/denylist)
    #[allow(dead_code)] // Used by log_denied
    Denied,
    /// Get tool info
    #[allow(dead_code)] // Reserved for MCP tool info logging
    GetTool,
    /// Read resource
    #[allow(dead_code)] // Reserved for MCP resource logging
    ReadResource,
    /// Get prompt
    #[allow(dead_code)] // Reserved for MCP prompt logging
    GetPrompt,
}

/// A single audit log entry
#[derive(Debug, Serialize)]
pub struct AuditEntry {
    /// ISO 8601 timestamp
    timestamp: String,
    /// The action performed
    action: AuditAction,
    /// Tool name (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    tool: Option<String>,
    /// Whether the operation succeeded
    #[serde(skip_serializing_if = "Option::is_none")]
    success: Option<bool>,
    /// Version (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    version: Option<String>,
    /// Duration in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    duration_ms: Option<u64>,
    /// MCP client identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    client: Option<String>,
    /// Additional data
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<serde_json::Value>,
}

impl AuditEntry {
    /// Create a new audit entry with the current timestamp
    pub fn new(action: AuditAction) -> Self {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| {
                // Simple ISO 8601 format
                let secs = d.as_secs();
                let (year, month, day, hour, min, sec) = unix_to_datetime(secs);
                format!(
                    "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
                    year, month, day, hour, min, sec
                )
            })
            .unwrap_or_else(|_| "unknown".to_string());

        Self {
            timestamp,
            action,
            tool: None,
            success: None,
            version: None,
            duration_ms: None,
            client: None,
            data: None,
        }
    }

    /// Add tool name
    pub fn with_tool(mut self, tool: &str) -> Self {
        self.tool = Some(tool.to_string());
        self
    }

    /// Add success status
    pub fn with_success(mut self, success: bool) -> Self {
        self.success = Some(success);
        self
    }

    /// Add version
    pub fn with_version(mut self, version: Option<&str>) -> Self {
        self.version = version.map(|s| s.to_string());
        self
    }

    /// Add duration
    pub fn with_duration(mut self, duration_ms: u64) -> Self {
        self.duration_ms = Some(duration_ms);
        self
    }

    /// Add client identifier
    pub fn with_client(mut self, client: Option<&str>) -> Self {
        self.client = client.map(|s| s.to_string());
        self
    }

    /// Add additional data
    pub fn with_data(mut self, key: &str, value: serde_json::Value) -> Self {
        let data = self.data.get_or_insert_with(|| serde_json::json!({}));
        if let Some(obj) = data.as_object_mut() {
            obj.insert(key.to_string(), value);
        }
        self
    }
}

/// Convert Unix timestamp to (year, month, day, hour, minute, second)
fn unix_to_datetime(secs: u64) -> (u32, u32, u32, u32, u32, u32) {
    // Simple algorithm for UTC conversion
    let days = secs / 86400;
    let time = secs % 86400;

    let hour = (time / 3600) as u32;
    let min = ((time % 3600) / 60) as u32;
    let sec = (time % 60) as u32;

    // Calculate year, month, day from days since epoch (1970-01-01)
    let mut year = 1970u32;
    let mut remaining_days = days;

    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if remaining_days < days_in_year {
            break;
        }
        remaining_days -= days_in_year;
        year += 1;
    }

    let leap = is_leap_year(year);
    let days_in_months: [u64; 12] = if leap {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    let mut month = 1u32;
    for days_in_month in days_in_months {
        if remaining_days < days_in_month {
            break;
        }
        remaining_days -= days_in_month;
        month += 1;
    }

    let day = (remaining_days + 1) as u32;

    (year, month, day, hour, min, sec)
}

fn is_leap_year(year: u32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

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

    #[test]
    fn test_audit_entry_serialization() {
        let entry = AuditEntry::new(AuditAction::Install)
            .with_tool("git")
            .with_success(true)
            .with_version(Some("2.43.0"))
            .with_duration(1234)
            .with_client(Some("claude-desktop"));

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"action\":\"install\""));
        assert!(json.contains("\"tool\":\"git\""));
        assert!(json.contains("\"success\":true"));
        assert!(json.contains("\"version\":\"2.43.0\""));
        assert!(json.contains("\"duration_ms\":1234"));
        assert!(json.contains("\"client\":\"claude-desktop\""));
    }

    #[test]
    fn test_audit_entry_with_data() {
        let entry =
            AuditEntry::new(AuditAction::ListTools).with_data("count", serde_json::json!(85));

        let json = serde_json::to_string(&entry).unwrap();
        assert!(json.contains("\"count\":85"));
    }

    #[test]
    fn test_unix_to_datetime() {
        // 2024-01-15T12:36:40Z
        let (year, month, day, hour, min, sec) = unix_to_datetime(1705322200);
        assert_eq!(year, 2024);
        assert_eq!(month, 1);
        assert_eq!(day, 15);
        assert_eq!(hour, 12);
        assert_eq!(min, 36);
        assert_eq!(sec, 40);
    }

    #[test]
    fn test_disabled_audit_log() {
        let log = AuditLog::disabled();
        // Should not error even when disabled
        log.log_list_tools(Some("test"), 10);
        log.log_check_tool(Some("test"), "git", true, Some("2.43.0"));
    }
}