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    /// Names of the allowed tools.
17    pub allowed: Vec<String>,
18}
19
20impl ToolAllowList {
21    /// Allow exactly `tools`.
22    pub fn new(tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
23        Self { allowed: tools.into_iter().map(Into::into).collect() }
24    }
25
26    /// Whether `tool` is in the list.
27    #[must_use]
28    pub fn allows(&self, tool: &str) -> bool {
29        self.allowed.iter().any(|t| t == tool)
30    }
31
32    /// Register the `PreToolUse` hook that enforces the list.
33    pub fn install(self, hooks: &mut HookRegistry) {
34        hooks.on(HookEventKind::PreToolUse, None, move |payload| {
35            let verdict = match payload.tool_name.as_deref() {
36                Some(tool) if !self.allows(tool) => Some(format!(
37                    "Tool {tool} is not allowed here. Allowed tools: {}",
38                    self.allowed.join(", ")
39                )),
40                _ => None,
41            };
42            async move { verdict.map_or_else(HookOutput::allow, HookOutput::block) }
43        });
44    }
45}