assay-cli 3.26.0

Policy-as-code gate for MCP agent tool calls, with verifiable evidence and Linux kernel enforcement.
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
//! Config Path Detection & Integration Helper
//!
//! Detects MCP client config locations and generates ready-to-use configurations.
//! Supports: Claude Desktop, Cursor, and generic MCP clients.

use serde::{Deserialize, Serialize};
use serde_json::json;
use std::env;
use std::path::PathBuf;

/// Supported MCP clients
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum McpClient {
    Claude,
    Cursor,
}

impl McpClient {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().as_str() {
            "claude" | "claude-desktop" | "claude_desktop" => Some(Self::Claude),
            "cursor" => Some(Self::Cursor),
            _ => None,
        }
    }

    pub fn display_name(&self) -> &'static str {
        match self {
            Self::Claude => "Claude Desktop",
            Self::Cursor => "Cursor",
        }
    }
}

/// Result of config path detection
#[derive(Debug)]
pub struct ConfigDetection {
    pub config_path: PathBuf,
    pub exists: bool,
}

/// Generated MCP server configuration
#[derive(Debug, Serialize)]
pub struct GeneratedConfig {
    pub server_name: String,
    pub config: McpServerEntry,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerEntry {
    pub command: String,
    pub args: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<std::collections::HashMap<String, String>>,
}

// Path detection

/// Detect the config file path for a given MCP client
pub fn detect_config_path(client: McpClient) -> Option<PathBuf> {
    match client {
        McpClient::Claude => detect_claude_config_path(),
        McpClient::Cursor => detect_cursor_config_path(),
    }
}

fn detect_claude_config_path() -> Option<PathBuf> {
    #[cfg(target_os = "macos")]
    {
        dirs::home_dir()
            .map(|h| h.join("Library/Application Support/Claude/claude_desktop_config.json"))
    }

    #[cfg(target_os = "windows")]
    {
        dirs::data_dir().map(|d| d.join("Claude/claude_desktop_config.json"))
    }

    #[cfg(target_os = "linux")]
    {
        dirs::config_dir().map(|c| c.join("Claude/claude_desktop_config.json"))
    }

    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
    {
        None
    }
}

fn detect_cursor_config_path() -> Option<PathBuf> {
    #[cfg(target_os = "macos")]
    {
        dirs::home_dir().map(|h| {
            h.join("Library/Application Support/Cursor/User/globalStorage/cursor.mcp/config.json")
        })
    }

    #[cfg(target_os = "windows")]
    {
        dirs::data_dir().map(|d| d.join("Cursor/User/globalStorage/cursor.mcp/config.json"))
    }

    #[cfg(target_os = "linux")]
    {
        dirs::config_dir().map(|c| c.join("Cursor/User/globalStorage/cursor.mcp/config.json"))
    }

    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
    {
        None
    }
}

/// Detect the config file path and whether it currently exists.
pub fn detect_config(client: McpClient) -> Option<ConfigDetection> {
    let config_path = detect_config_path(client)?;
    let exists = config_path.exists();

    Some(ConfigDetection {
        config_path,
        exists,
    })
}

// Config generation

/// Generate an MCP server config entry for Assay wrapper
pub fn generate_assay_config(
    server_name: &str,
    policy_path: &str,
    wrapped_command: &str,
    wrapped_args: &[String],
    assay_binary: Option<&str>,
) -> GeneratedConfig {
    // Detect assay binary location
    let assay_cmd = assay_binary
        .map(String::from)
        .or_else(detect_assay_binary)
        .unwrap_or_else(|| "assay".to_string());

    // Build args: mcp wrap --policy <path> -- <command> <args...>
    let mut args = vec![
        "mcp".to_string(),
        "wrap".to_string(),
        "--policy".to_string(),
        policy_path.to_string(),
        "--".to_string(),
        wrapped_command.to_string(),
    ];
    args.extend(wrapped_args.iter().cloned());

    GeneratedConfig {
        server_name: server_name.to_string(),
        config: McpServerEntry {
            command: assay_cmd,
            args,
            env: None,
        },
    }
}

/// Generate a filesystem server config (common use case)
pub fn generate_filesystem_config(
    policy_path: &str,
    allowed_directory: &str,
    assay_binary: Option<&str>,
) -> GeneratedConfig {
    generate_assay_config(
        "filesystem-secure",
        policy_path,
        "npx",
        &[
            "-y".to_string(),
            "@modelcontextprotocol/server-filesystem".to_string(),
            allowed_directory.to_string(),
        ],
        assay_binary,
    )
}

/// Try to find the assay binary
fn detect_assay_binary() -> Option<String> {
    // 1. Check if we're running as assay (use current exe)
    if let Ok(exe) = env::current_exe() {
        if exe
            .file_name()
            .map(|n| n.to_string_lossy().contains("assay"))
            .unwrap_or(false)
        {
            return Some(exe.to_string_lossy().to_string());
        }
    }

    // 2. Check common install locations
    let candidates = [
        dirs::home_dir().map(|h| h.join(".cargo/bin/assay")),
        dirs::home_dir().map(|h| h.join(".local/bin/assay")),
        Some(PathBuf::from("/usr/local/bin/assay")),
    ];

    for candidate in candidates.into_iter().flatten() {
        if candidate.exists() {
            return Some(candidate.to_string_lossy().to_string());
        }
    }

    None
}

/// Get default policy path
pub fn default_policy_path() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("assay/policy.yaml")
}

// JSON output formatting

/// Format the generated config as a JSON snippet for mcpServers
pub fn format_as_mcp_servers_entry(config: &GeneratedConfig) -> String {
    let entry = json!({
        &config.server_name: &config.config
    });

    serde_json::to_string_pretty(&entry).unwrap_or_else(|_| "{}".to_string())
}

// CLI output helper

/// Generate the full CLI output for `assay mcp config-path`
pub fn generate_cli_output(
    client: McpClient,
    policy_path: Option<&str>,
    wrapped_server: Option<(&str, &[String])>,
) -> String {
    let detection = detect_config(client);
    let policy = policy_path
        .map(String::from)
        .unwrap_or_else(|| default_policy_path().to_string_lossy().to_string());

    let home_dir = dirs::home_dir()
        .map(|h| h.to_string_lossy().to_string())
        .unwrap_or_else(|| "~".to_string());

    // Generate config
    let config = if let Some((cmd, args)) = wrapped_server {
        generate_assay_config("mcp-secure", &policy, cmd, args, None)
    } else {
        generate_filesystem_config(&policy, &home_dir, None)
    };

    let mut output = String::new();

    // Header
    output.push_str(&format!("┌─ {} Configuration\n", client.display_name()));
    output.push_str("│\n");

    // Config path status
    if let Some(ref det) = detection {
        output.push_str(&format!("│  Config file: {}\n", det.config_path.display()));
        if det.exists {
            output.push_str("│  Status: ✓ Found\n");
        } else {
            output.push_str("│  Status: ✗ Not found (will be created)\n");
        }
    } else {
        output.push_str("│  Config file: Could not detect path\n");
        output.push_str("│  Status: ✗ Unknown OS or client not installed\n");
    }

    output.push_str("│\n");
    output.push_str("├─ Policy file\n");
    output.push_str("│\n");
    output.push_str(&format!("│  {}\n", policy));
    output.push_str("│\n");

    // Generated config
    output.push_str("├─ Add this to your mcpServers:\n");
    output.push_str("│\n");

    let json_snippet = format_as_mcp_servers_entry(&config);
    for line in json_snippet.lines() {
        output.push_str(&format!("│  {}\n", line));
    }

    output.push_str("│\n");
    output.push_str("└─ Next steps:\n");
    output.push_str("   1. Create your policy file\n");
    output.push_str("   2. Add the above JSON to your config file\n");
    output.push_str(&format!("   3. Restart {}\n", client.display_name()));

    output
}

// Entry point

pub fn run(args: crate::cli::args::ConfigPathArgs) {
    let client = match McpClient::from_str(&args.client) {
        Some(c) => c,
        None => {
            eprintln!(
                "Error: Unknown client '{}'. Supported: claude, cursor",
                args.client
            );
            std::process::exit(1);
        }
    };

    let wrapped_tuple = args.server.as_deref().and_then(|server_cmd| {
        let mut parts = server_cmd.split_whitespace();
        let cmd = parts.next()?;
        // Collect remaining parts as args
        let args: Vec<String> = parts.map(String::from).collect();
        Some((cmd.to_string(), args))
    });

    // Hold owned values, then take references for downstream helpers.
    let (server_cmd_owned, server_args_owned) = match wrapped_tuple {
        Some((cmd, args)) => (Some(cmd), args),
        None => (None, vec![]),
    };

    let wrapped_tuple_ref = server_cmd_owned
        .as_deref()
        .map(|cmd| (cmd, server_args_owned.as_slice()));

    if args.json {
        let detection = detect_config(client);
        let policy = args
            .policy
            .clone()
            .unwrap_or_else(|| default_policy_path().to_string_lossy().to_string());

        // Use home dir for allowlist if no wrapped server specified
        let home_dir = dirs::home_dir()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_else(|| "~".to_string());

        let config = if let Some((cmd, args)) = wrapped_tuple_ref {
            generate_assay_config("mcp-secure", &policy, cmd, args, None)
        } else {
            generate_filesystem_config(&policy, &home_dir, None)
        };

        let output = json!({
            "client": client.display_name(),
            "config_path": detection.as_ref().map(|d| d.config_path.clone()),
            "config_exists": detection.as_ref().map(|d| d.exists).unwrap_or(false),
            "generated_server": config
        });
        println!("{}", serde_json::to_string_pretty(&output).unwrap());
    } else {
        println!(
            "{}",
            generate_cli_output(client, args.policy.as_deref(), wrapped_tuple_ref)
        );
    }
}

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

    #[test]
    fn test_client_from_str() {
        assert_eq!(McpClient::from_str("claude"), Some(McpClient::Claude));
        assert_eq!(McpClient::from_str("Claude"), Some(McpClient::Claude));
        assert_eq!(
            McpClient::from_str("claude-desktop"),
            Some(McpClient::Claude)
        );
        assert_eq!(McpClient::from_str("cursor"), Some(McpClient::Cursor));
        assert_eq!(McpClient::from_str("vscode"), None);
    }

    #[test]
    fn test_generate_filesystem_config() {
        let config = generate_filesystem_config(
            "/home/user/.config/assay/policy.yaml",
            "/home/user",
            Some("/usr/local/bin/assay"),
        );

        assert_eq!(config.server_name, "filesystem-secure");
        assert_eq!(config.config.command, "/usr/local/bin/assay");
        assert!(config.config.args.contains(&"mcp".to_string()));
        assert!(config.config.args.contains(&"wrap".to_string()));
        assert!(config.config.args.contains(&"--policy".to_string()));
    }

    #[test]
    fn test_format_as_mcp_servers_entry() {
        let config = GeneratedConfig {
            server_name: "test-server".to_string(),
            config: McpServerEntry {
                command: "assay".to_string(),
                args: vec!["mcp".to_string(), "wrap".to_string()],
                env: None,
            },
        };

        let output = format_as_mcp_servers_entry(&config);
        assert!(output.contains("test-server"));
        assert!(output.contains("assay"));
    }
}