Skip to main content

claude_code_agent/
middleware.rs

1//! Ready-made hook policies.
2use crate::hooks::HookRegistry;
3use crate::protocol::{HookEventKind, HookOutput};
4
5/// Block every tool call whose tool is not in the list (PreToolUse hook).
6///
7/// ```rust,no_run
8/// use claude_code_agent::HookRegistry;
9/// use claude_code_agent::middleware::ToolAllowList;
10///
11/// let mut hooks = HookRegistry::new();
12/// ToolAllowList::new(["Read", "Grep", "Glob"]).install(&mut hooks);
13/// ```
14#[derive(Debug, Clone)]
15pub struct ToolAllowList {
16    pub allowed: Vec<String>,
17}
18
19impl ToolAllowList {
20    pub fn new(tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
21        Self { allowed: tools.into_iter().map(Into::into).collect() }
22    }
23
24    pub fn allows(&self, tool: &str) -> bool {
25        self.allowed.iter().any(|t| t == tool)
26    }
27
28    /// Register the PreToolUse hook that enforces the list.
29    pub fn install(self, hooks: &mut HookRegistry) {
30        hooks.on(HookEventKind::PreToolUse, None, move |payload| {
31            let verdict = match payload.tool_name.as_deref() {
32                Some(tool) if !self.allows(tool) => Some(format!(
33                    "Tool {tool} is not allowed here. Allowed tools: {}",
34                    self.allowed.join(", ")
35                )),
36                _ => None,
37            };
38            async move { verdict.map(HookOutput::block).unwrap_or_else(HookOutput::allow) }
39        });
40    }
41}