Skip to main content

microclaw_engine/
tool_gate.rs

1//! Embedder-supplied tool gate: a callback consulted before (and after)
2//! every tool call at the registry choke point.
3//!
4//! Embedders such as MicroClaw Code use it for permission rules
5//! (`allow` / `ask` / `deny` per tool, path or command) and for user hooks
6//! (`pre_tool_use` / `post_tool_use`). The gate runs after the operator
7//! `tool_policy` and egress checks, so it can only tighten them, and before
8//! the high-risk approval gate:
9//!
10//! - [`ToolGateDecision::Allow`]: continue (the normal approval rules still
11//!   apply, e.g. `bash` still asks where approvals are required).
12//! - [`ToolGateDecision::Approve`]: continue without asking even where the
13//!   tool would normally need an approval (an explicit allow rule).
14//! - [`ToolGateDecision::Ask`]: the call needs a person's approval, whatever
15//!   the tool's risk; it goes through the same in-run approval flow as
16//!   high-risk tools.
17//! - [`ToolGateDecision::Deny`]: the call is not executed; the reason is
18//!   returned to the model.
19//!
20//! A decision may also replace the tool input (`updated_input`).
21
22use std::fmt;
23use std::sync::Arc;
24
25use async_trait::async_trait;
26use serde_json::Value;
27
28/// One tool call as seen by the gate.
29#[derive(Debug, Clone)]
30pub struct ToolGateCall<'a> {
31    pub tool: &'a str,
32    /// The tool input, without internal `__microclaw_*` keys.
33    pub input: &'a Value,
34    pub caller_channel: &'a str,
35    /// `main` for the main agent, otherwise the principal (`subagent:<id>`).
36    pub principal: &'a str,
37    pub chat_id: i64,
38    /// The person already approved this call (in-run approval retry).
39    pub approved: bool,
40}
41
42/// What to do with a tool call.
43#[derive(Debug, Clone, PartialEq)]
44pub enum ToolGateDecision {
45    Allow,
46    Approve { rule: Option<String> },
47    Ask { reason: Option<String> },
48    Deny { reason: String },
49}
50
51/// A decision plus an optional replacement input.
52#[derive(Debug, Clone, PartialEq)]
53pub struct ToolGateOutcome {
54    pub decision: ToolGateDecision,
55    pub updated_input: Option<Value>,
56}
57
58impl ToolGateOutcome {
59    pub fn allow() -> Self {
60        Self {
61            decision: ToolGateDecision::Allow,
62            updated_input: None,
63        }
64    }
65
66    pub fn with(decision: ToolGateDecision) -> Self {
67        Self {
68            decision,
69            updated_input: None,
70        }
71    }
72}
73
74/// The tool result as seen by [`ToolGate::after`].
75#[derive(Debug, Clone)]
76pub struct ToolGateResult<'a> {
77    pub content: &'a str,
78    pub is_error: bool,
79    pub error_type: Option<&'a str>,
80}
81
82#[async_trait]
83pub trait ToolGate: Send + Sync {
84    /// Decide on a call before it runs.
85    async fn before(&self, call: &ToolGateCall<'_>) -> ToolGateOutcome;
86
87    /// Observe a finished call. Returned text is appended to the tool result
88    /// the model sees (extra context, e.g. from a `post_tool_use` hook).
89    async fn after(
90        &self,
91        _call: &ToolGateCall<'_>,
92        _result: &ToolGateResult<'_>,
93    ) -> Option<String> {
94        None
95    }
96}
97
98/// Shared, optional gate stored in the configuration (not serialized).
99#[derive(Clone, Default)]
100pub struct ToolGateHandle(pub Option<Arc<dyn ToolGate>>);
101
102impl ToolGateHandle {
103    pub fn new(gate: Arc<dyn ToolGate>) -> Self {
104        Self(Some(gate))
105    }
106
107    pub fn get(&self) -> Option<&Arc<dyn ToolGate>> {
108        self.0.as_ref()
109    }
110}
111
112impl fmt::Debug for ToolGateHandle {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        f.write_str(if self.0.is_some() {
115            "ToolGateHandle(Some)"
116        } else {
117            "ToolGateHandle(None)"
118        })
119    }
120}
121
122/// Copy of `input` without internal `__microclaw_*` keys.
123pub fn public_input(input: &Value) -> Value {
124    match input {
125        Value::Object(map) => Value::Object(
126            map.iter()
127                .filter(|(k, _)| !k.starts_with("__microclaw"))
128                .map(|(k, v)| (k.clone(), v.clone()))
129                .collect(),
130        ),
131        other => other.clone(),
132    }
133}
134
135/// Re-attach the internal keys of `original` to a gate-supplied input.
136pub fn merge_internal_keys(original: &Value, updated: Value) -> Value {
137    match (original, updated) {
138        (Value::Object(orig), Value::Object(mut new)) => {
139            for (k, v) in orig {
140                if k.starts_with("__microclaw") {
141                    new.insert(k.clone(), v.clone());
142                }
143            }
144            Value::Object(new)
145        }
146        (_, updated) => updated,
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use serde_json::json;
154
155    #[test]
156    fn strips_and_restores_internal_keys() {
157        let input = json!({"command": "ls", "__microclaw_auth": {"x": 1}});
158        assert_eq!(public_input(&input), json!({"command": "ls"}));
159        let merged = merge_internal_keys(&input, json!({"command": "ls -la"}));
160        assert_eq!(merged["command"], "ls -la");
161        assert_eq!(merged["__microclaw_auth"]["x"], 1);
162    }
163}