destructive_command_guard 0.5.4

An AI coding agent hook that blocks destructive commands before they execute
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! MCP server mode for direct agent integration.
//!
//! This exposes dcg as an MCP tool server over stdio, providing structured
//! checks without shell-hook overhead.

use crate::config::Config;
use crate::evaluator::{EvaluationDecision, evaluate_command};
use crate::packs::REGISTRY;
use crate::scan::{
    ScanEvalContext, ScanFailOn, ScanFormat, ScanOptions, ScanRedactMode, ScanReport, scan_paths,
};
use async_trait::async_trait;
use rust_mcp_sdk::mcp_server::{
    McpServerOptions, ServerHandler, ToMcpServerHandler, server_runtime,
};
use rust_mcp_sdk::schema::schema_utils::CallToolError;
use rust_mcp_sdk::schema::{
    CallToolRequestParams, CallToolResult, Implementation, InitializeResult, ListToolsResult,
    PaginatedRequestParams, ProtocolVersion, RpcError, ServerCapabilities, ServerCapabilitiesTools,
    TextContent, Tool, ToolInputSchema,
};
use rust_mcp_sdk::{McpServer, StdioTransport, TransportOptions};
use serde::Serialize;
use serde_json::{Map, Value};
use std::path::PathBuf;
use std::sync::Arc;

#[derive(Debug)]
pub struct DcgMcpServer {
    server_info: InitializeResult,
    config: Arc<Config>,
    scan_ctx: Arc<ScanEvalContext>,
}

#[derive(Serialize)]
struct AllowlistInfo {
    layer: String,
    reason: String,
}

#[derive(Serialize)]
struct CheckCommandResponse {
    allowed: bool,
    decision: String,
    mode: Option<String>,
    skipped_due_to_budget: bool,
    reason: Option<String>,
    rule_id: Option<String>,
    pack_id: Option<String>,
    pattern_name: Option<String>,
    severity: Option<String>,
    explanation: Option<String>,
    matched_text_preview: Option<String>,
    allowlist: Option<AllowlistInfo>,
}

#[derive(Serialize)]
struct ExplainPatternResponse {
    rule_id: String,
    pack_id: String,
    pattern_name: String,
    severity: String,
    reason: String,
    explanation: String,
}

impl DcgMcpServer {
    #[must_use]
    pub fn new() -> Self {
        let config = Config::load();
        let scan_ctx = ScanEvalContext::from_config(&config);
        let server_info = InitializeResult {
            protocol_version: ProtocolVersion::V2025_11_25.into(),
            server_info: Implementation {
                description: Some(
                    "Destructive Command Guard MCP server for command safety checks.".to_string(),
                ),
                icons: Vec::new(),
                name: "dcg".to_string(),
                title: Some("Destructive Command Guard".to_string()),
                version: env!("CARGO_PKG_VERSION").to_string(),
                website_url: None,
            },
            capabilities: ServerCapabilities {
                completions: None,
                experimental: None,
                logging: None,
                prompts: None,
                resources: None,
                tasks: None,
                tools: Some(ServerCapabilitiesTools {
                    list_changed: Some(false),
                }),
            },
            instructions: Some(
                "Destructive Command Guard MCP server. Tools: check_command, scan_file, explain_pattern."
                    .to_string(),
            ),
            meta: None,
        };

        Self {
            server_info,
            config: Arc::new(config),
            scan_ctx: Arc::new(scan_ctx),
        }
    }

    const fn default_scan_options() -> ScanOptions {
        ScanOptions {
            format: ScanFormat::Pretty,
            fail_on: ScanFailOn::Error,
            max_file_size_bytes: 1_048_576,
            max_findings: 100,
            redact: ScanRedactMode::None,
            truncate: 200,
        }
    }

    fn tool_input_schema(
        required: &[&str],
        props: Vec<(&str, Map<String, Value>)>,
    ) -> ToolInputSchema {
        let mut properties = std::collections::BTreeMap::new();
        for (name, schema) in props {
            properties.insert(name.to_string(), schema);
        }
        ToolInputSchema::new(
            required.iter().map(|s| (*s).to_string()).collect(),
            Some(properties),
            None,
        )
    }

    fn string_schema(description: &str) -> Map<String, Value> {
        let mut map = Map::new();
        map.insert("type".to_string(), Value::String("string".to_string()));
        map.insert(
            "description".to_string(),
            Value::String(description.to_string()),
        );
        map
    }

    fn tool(name: &str, description: &str, schema: ToolInputSchema) -> Tool {
        Tool {
            name: name.to_string(),
            description: Some(description.to_string()),
            execution: None,
            icons: Vec::new(),
            input_schema: schema,
            title: None,
            annotations: None,
            meta: None,
            output_schema: None,
        }
    }

    fn tool_result_json<T: Serialize>(value: &T) -> Result<CallToolResult, CallToolError> {
        let json = serde_json::to_string_pretty(value).map_err(CallToolError::new)?;
        Ok(CallToolResult::text_content(vec![TextContent::from(json)]))
    }

    fn call_tool_error(message: impl Into<String>) -> CallToolError {
        CallToolError::new(std::io::Error::other(message.into()))
    }

    fn string_arg(args: Option<&Map<String, Value>>, key: &str) -> Result<String, CallToolError> {
        let args = args.ok_or_else(|| {
            Self::call_tool_error(format!("Missing arguments for tool (expected '{key}')"))
        })?;
        let value = args.get(key).and_then(|v| v.as_str()).ok_or_else(|| {
            Self::call_tool_error(format!("Missing or invalid '{key}' parameter"))
        })?;
        Ok(value.to_string())
    }

    fn rule_id_from_match(pack_id: Option<&str>, pattern_name: Option<&str>) -> Option<String> {
        match (pack_id, pattern_name) {
            (Some(pack), Some(name)) => Some(format!("{pack}:{name}")),
            _ => None,
        }
    }

    fn check_command(&self, command: &str) -> CheckCommandResponse {
        let result = evaluate_command(
            command,
            &self.config,
            &self.scan_ctx.enabled_keywords,
            &self.scan_ctx.compiled_overrides,
            &self.scan_ctx.allowlists,
        );

        let mode = result.effective_mode.map(|m| m.label().to_string());
        let allowed = result
            .effective_mode
            .map_or(result.decision != EvaluationDecision::Deny, |m| !m.blocks());

        let mut response = CheckCommandResponse {
            allowed,
            decision: match result.decision {
                EvaluationDecision::Allow => "allow".to_string(),
                EvaluationDecision::Deny => "deny".to_string(),
            },
            mode,
            skipped_due_to_budget: result.skipped_due_to_budget,
            reason: None,
            rule_id: None,
            pack_id: None,
            pattern_name: None,
            severity: None,
            explanation: None,
            matched_text_preview: None,
            allowlist: None,
        };

        if let Some(override_) = result.allowlist_override.as_ref() {
            response.allowlist = Some(AllowlistInfo {
                layer: override_.layer.label().to_string(),
                reason: override_.reason.clone(),
            });
        }

        let match_info = result
            .pattern_info
            .as_ref()
            .or_else(|| result.allowlist_override.as_ref().map(|o| &o.matched));

        if let Some(info) = match_info {
            response.reason = Some(info.reason.clone());
            response.rule_id =
                Self::rule_id_from_match(info.pack_id.as_deref(), info.pattern_name.as_deref());
            response.pack_id.clone_from(&info.pack_id);
            response.pattern_name.clone_from(&info.pattern_name);
            response.severity = info.severity.map(|s| s.label().to_string());
            response.explanation.clone_from(&info.explanation);
            response
                .matched_text_preview
                .clone_from(&info.matched_text_preview);
        }

        response
    }

    fn explain_pattern(rule_id: &str) -> Result<ExplainPatternResponse, CallToolError> {
        let (pack_id, pattern_name) = rule_id
            .split_once(':')
            .ok_or_else(|| Self::call_tool_error("rule_id must be in 'pack:pattern' format"))?;

        let pack = REGISTRY
            .get(pack_id)
            .ok_or_else(|| Self::call_tool_error(format!("Unknown pack '{pack_id}'")))?;

        let pattern = pack
            .destructive_patterns
            .iter()
            .find(|p| p.name == Some(pattern_name))
            .ok_or_else(|| {
                Self::call_tool_error(format!(
                    "Pattern '{pattern_name}' not found in pack '{pack_id}'"
                ))
            })?;

        let reason = pattern.reason.to_string();
        let explanation = pattern.explanation.unwrap_or(pattern.reason).to_string();

        Ok(ExplainPatternResponse {
            rule_id: rule_id.to_string(),
            pack_id: pack_id.to_string(),
            pattern_name: pattern_name.to_string(),
            severity: pattern.severity.label().to_string(),
            reason,
            explanation,
        })
    }

    async fn scan_file_report(&self, path: String) -> Result<ScanReport, CallToolError> {
        let config = Arc::clone(&self.config);
        let scan_ctx = Arc::clone(&self.scan_ctx);

        Self::run_blocking_scan(move || {
            let path_buf = PathBuf::from(path);
            let options = Self::default_scan_options();
            let include: Vec<String> = Vec::new();
            let exclude: Vec<String> = Vec::new();

            scan_paths(
                &[path_buf],
                &options,
                config.as_ref(),
                scan_ctx.as_ref(),
                &include,
                &exclude,
                None,
            )
        })
        .await
    }

    async fn scan_file_tool(&self, path: String) -> Result<CallToolResult, CallToolError> {
        let report = self.scan_file_report(path).await?;
        Self::tool_result_json(&report)
    }

    async fn run_blocking_scan<F>(scan: F) -> Result<ScanReport, CallToolError>
    where
        F: FnOnce() -> Result<ScanReport, String> + Send + 'static,
    {
        tokio::task::spawn_blocking(scan)
            .await
            .map_err(|err| Self::call_tool_error(format!("scan_file worker failed: {err}")))?
            .map_err(Self::call_tool_error)
    }
}

impl Default for DcgMcpServer {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ServerHandler for DcgMcpServer {
    async fn handle_list_tools_request(
        &self,
        _params: Option<PaginatedRequestParams>,
        _runtime: Arc<dyn McpServer>,
    ) -> Result<ListToolsResult, RpcError> {
        let tools = vec![
            Self::tool(
                "check_command",
                "Evaluate a command using dcg policy",
                Self::tool_input_schema(
                    &["command"],
                    vec![("command", Self::string_schema("Command to evaluate"))],
                ),
            ),
            Self::tool(
                "scan_file",
                "Scan a file or directory for destructive commands",
                Self::tool_input_schema(
                    &["path"],
                    vec![(
                        "path",
                        Self::string_schema("File or directory path to scan"),
                    )],
                ),
            ),
            Self::tool(
                "explain_pattern",
                "Explain a dcg rule by rule_id",
                Self::tool_input_schema(
                    &["rule_id"],
                    vec![(
                        "rule_id",
                        Self::string_schema("Rule id in the form 'pack:pattern'"),
                    )],
                ),
            ),
        ];

        Ok(ListToolsResult {
            tools,
            next_cursor: None,
            meta: None,
        })
    }

    async fn handle_call_tool_request(
        &self,
        params: CallToolRequestParams,
        _runtime: Arc<dyn McpServer>,
    ) -> Result<CallToolResult, CallToolError> {
        match params.name.as_str() {
            "check_command" => {
                let command = Self::string_arg(params.arguments.as_ref(), "command")?;
                let response = self.check_command(&command);
                Self::tool_result_json(&response)
            }
            "scan_file" => {
                let path = Self::string_arg(params.arguments.as_ref(), "path")?;
                self.scan_file_tool(path).await
            }
            "explain_pattern" => {
                let rule_id = Self::string_arg(params.arguments.as_ref(), "rule_id")?;
                let response = Self::explain_pattern(&rule_id)?;
                Self::tool_result_json(&response)
            }
            other => Err(Self::call_tool_error(format!("Unknown tool '{other}'"))),
        }
    }
}

/// # Errors
///
/// Returns an error when the MCP server fails to initialize or run.
pub async fn run_mcp_server_async() -> Result<(), Box<dyn std::error::Error>> {
    let handler = DcgMcpServer::new();
    let server_details = handler.server_info.clone();
    let transport = StdioTransport::new(TransportOptions::default())?;
    let server = server_runtime::create_server(McpServerOptions {
        transport,
        handler: handler.to_mcp_server_handler(),
        server_details,
        task_store: None,
        client_task_store: None,
        message_observer: None,
    });
    server.start().await?;
    Ok(())
}

/// # Errors
///
/// Returns an error when the async runtime or MCP server fails to start.
pub fn run_mcp_server() -> Result<(), Box<dyn std::error::Error>> {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    runtime.block_on(run_mcp_server_async())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scan::{SCAN_SCHEMA_VERSION, ScanDecisionCounts, ScanSeverityCounts, ScanSummary};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    fn empty_scan_report() -> ScanReport {
        ScanReport {
            schema_version: SCAN_SCHEMA_VERSION,
            summary: ScanSummary {
                files_scanned: 0,
                files_skipped: 0,
                skipped: Vec::new(),
                paths_skipped: Vec::new(),
                commands_extracted: 0,
                findings_total: 0,
                decisions: ScanDecisionCounts::default(),
                severities: ScanSeverityCounts::default(),
                max_findings_reached: false,
                elapsed_ms: Some(0),
            },
            findings: Vec::new(),
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn blocking_scan_worker_does_not_starve_lightweight_checks() {
        let server = DcgMcpServer::new();
        let scan_started = Arc::new(AtomicBool::new(false));
        let scan_started_in_worker = Arc::clone(&scan_started);

        let scan_future = DcgMcpServer::run_blocking_scan(move || {
            scan_started_in_worker.store(true, Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(150));
            Ok(empty_scan_report())
        });
        let quick_future = async {
            let quick_check = tokio::time::timeout(Duration::from_millis(50), async {
                while !scan_started.load(Ordering::SeqCst) {
                    tokio::task::yield_now().await;
                }
                server.check_command("git status")
            })
            .await
            .expect("blocking scan should not starve the async runtime");

            assert!(quick_check.allowed);
        };

        let (scan_result, ()) = tokio::join!(scan_future, quick_future);
        let report = scan_result.expect("blocking scan should succeed");
        assert_eq!(report.schema_version, SCAN_SCHEMA_VERSION);
    }

    #[tokio::test]
    async fn scan_file_report_scans_path_on_blocking_worker() {
        let temp_dir = tempfile::tempdir().unwrap();
        let script = temp_dir.path().join("danger.sh");
        std::fs::write(&script, "#!/bin/sh\nrm -rf /\n").unwrap();

        let server = DcgMcpServer::new();
        let report = server
            .scan_file_report(script.to_string_lossy().into_owned())
            .await
            .unwrap();

        assert_eq!(report.summary.files_scanned, 1);
        assert!(report.summary.commands_extracted >= 1);
        assert!(
            report
                .findings
                .iter()
                .any(|finding| finding.extracted_command.contains("rm -rf /"))
        );
    }
}