trusty_code/tools/registry.rs
1//! Tool registry — HashMap dispatcher + schema emitter.
2//!
3//! Why: Replaces hardcoded `if name == "delegate_to_agent"` dispatch with a
4//! polymorphic registry so new tools (`web_search`, `load_skill`, etc.) plug in
5//! without touching the PM loop. This is the SOA seam.
6//! What: `ToolRegistry` holds `Arc<dyn ToolExecutor>` keyed by name; emits a
7//! vector of JSON schemas for the LLM request; dispatches named tool calls to
8//! the right executor. RBAC-gated dispatch via `dispatch_for_user`.
9//! Test: Unit tests construct a registry with a `MockTool` and assert that
10//! `dispatch("mock")` returns the mock's output and `schemas()` contains the
11//! mock's schema.
12
13use std::collections::HashMap;
14use std::sync::Arc;
15
16use serde_json::Value;
17
18use crate::rbac::UserIdentity;
19use crate::tools::traits::{ToolExecutor, ToolResult};
20
21/// Registry of tools available to an LLM session.
22///
23/// Why: Centralizes tool lookup and schema emission so the PM loop and
24/// multi-turn sub-agent loop stay short and test-friendly.
25/// What: `HashMap<String, Arc<dyn ToolExecutor>>` with `register`, `dispatch`,
26/// `dispatch_gated`, `dispatch_for_user`, `schemas`, and `filter_tools_for_user`.
27/// Test: See unit tests below.
28#[derive(Default)]
29pub struct ToolRegistry {
30 tools: HashMap<String, Arc<dyn ToolExecutor>>,
31}
32
33impl ToolRegistry {
34 /// Construct an empty registry.
35 ///
36 /// Why: Callers build up the registry incrementally via `register`.
37 /// What: Returns a `ToolRegistry` with no tools registered.
38 /// Test: `new_registry_is_empty`.
39 pub fn new() -> Self {
40 Self {
41 tools: HashMap::new(),
42 }
43 }
44
45 /// Register a tool by its `name()`.
46 ///
47 /// Why: Using the tool's own name prevents mismatches between registered
48 /// key and schema-declared function name.
49 /// What: Inserts into the map. A `debug_assert!` panics in debug builds on
50 /// duplicate names so collisions surface during development.
51 /// Test: `register_then_dispatch_succeeds`, `register_panics_on_duplicate_in_debug`.
52 pub fn register(&mut self, tool: Arc<dyn ToolExecutor>) {
53 let name = tool.name().to_string();
54 debug_assert!(
55 !self.tools.contains_key(&name),
56 "duplicate tool registration for '{name}' — collisions overwrite and cause dispatch bugs"
57 );
58 self.tools.insert(name, tool);
59 }
60
61 /// Whether a tool with the given name is registered.
62 ///
63 /// Why: Lets callers skip registration when a tool already exists.
64 /// What: HashMap membership check.
65 /// Test: `contains_after_register`.
66 pub fn contains(&self, name: &str) -> bool {
67 self.tools.contains_key(name)
68 }
69
70 /// Dispatch a named tool call.
71 ///
72 /// Why: Single place where missing-tool errors are surfaced as a structured
73 /// `ToolResult::Error` so the LLM loop can continue.
74 /// What: Looks up `name`, calls `execute(args)`, returns the `ToolResult`.
75 /// Test: Dispatch to an unregistered name returns `ToolResult::Error`;
76 /// dispatch to a registered one returns `ToolResult::Success`.
77 pub async fn dispatch(&self, name: &str, args: Value) -> ToolResult {
78 let Some(tool) = self.tools.get(name) else {
79 return ToolResult::err(format!("no tool registered with name '{name}'"));
80 };
81 tool.execute(args).await
82 }
83
84 /// Dispatch with an optional per-agent allowlist.
85 ///
86 /// Why: Per-agent tool gating prevents, e.g., the plan-agent from shelling
87 /// out or the research-agent from delegating. Allowlist is checked
88 /// centrally so every call site inherits the same policy.
89 /// What: If `allowed` is `Some` and does not contain `name`, returns a
90 /// recoverable `ToolResult::Error` naming what is permitted. Otherwise
91 /// delegates to `dispatch`.
92 /// Test: `dispatch_gated_rejects_disallowed`.
93 pub async fn dispatch_gated(
94 &self,
95 name: &str,
96 args: Value,
97 allowed: Option<&[String]>,
98 ) -> ToolResult {
99 if let Some(list) = allowed
100 && !list.iter().any(|a| a == name)
101 {
102 return ToolResult::err(format!(
103 "Tool '{name}' is not permitted for this agent. Allowed: {}",
104 list.join(", ")
105 ));
106 }
107 self.dispatch(name, args).await
108 }
109
110 /// Dispatch honoring a `UserIdentity`'s `ServiceTier`.
111 ///
112 /// Why: Some tools must be denied to less-trusted transports (Slack guest
113 /// users, unauthenticated HTTP) even if the LLM tries to call them.
114 /// Enforcing the tier check at the dispatch boundary means transport authors
115 /// can't accidentally bypass RBAC by forgetting to pre-filter the tool list.
116 /// What: If the tool is registered AND `user.can_access_tier` is `false`,
117 /// returns `ToolResult::Error`. Otherwise delegates to `dispatch_gated`.
118 /// Test: `dispatch_for_user_blocks_restricted_tier`.
119 pub async fn dispatch_for_user(
120 &self,
121 name: &str,
122 args: Value,
123 allowed: Option<&[String]>,
124 user: &UserIdentity,
125 ) -> ToolResult {
126 if let Some(tool) = self.tools.get(name)
127 && !user.can_access_tier(tool.restricted_tiers())
128 {
129 return ToolResult::err("This tool is not available for your access tier.");
130 }
131 self.dispatch_gated(name, args, allowed).await
132 }
133
134 /// Build a new registry containing only the tools named in `allowed`.
135 ///
136 /// Why: The agent loop calls `dispatch_gated(name, args, None)` — it does
137 /// not thread a per-agent allowlist through every dispatch. The robust place
138 /// to enforce an agent's `tools.allowed` (issue #1029 acceptance criterion)
139 /// is therefore *before* the loop runs: hand the loop a registry that simply
140 /// does not contain the denied tools, so a denied call surfaces as the same
141 /// structured "no tool registered" error and the model can self-correct.
142 /// Unknown names in `allowed` are ignored (they register nothing); this keeps
143 /// a typo in an agent config from being a hard error.
144 /// What: Returns a fresh `ToolRegistry` whose map holds cloned `Arc`s for
145 /// exactly the registered tools whose `name()` appears in `allowed`,
146 /// preserving the shared executors (no re-construction). Order-independent.
147 /// Test: `gated_keeps_only_allowed`, `gated_ignores_unknown_names`.
148 pub fn gated(&self, allowed: &[String]) -> ToolRegistry {
149 let tools = self
150 .tools
151 .iter()
152 .filter(|(name, _)| allowed.iter().any(|a| a == *name))
153 .map(|(name, tool)| (name.clone(), Arc::clone(tool)))
154 .collect();
155 ToolRegistry { tools }
156 }
157
158 /// Emit all registered tool schemas as raw JSON values.
159 ///
160 /// Why: The sub-agent tool-calling loop attaches raw JSON schemas to LLM
161 /// requests; the OpenAI-compatible schema is produced by each tool.
162 /// What: Collects `tool.schema()` for every registered tool.
163 /// Test: Registering two tools returns a vector of length 2.
164 pub fn schemas(&self) -> Vec<Value> {
165 self.tools.values().map(|t| t.schema()).collect()
166 }
167
168 /// Return the raw schema for a single registered tool by name.
169 ///
170 /// Why: `llm::ToolCallExtractor` (#1023) validates one tool call's
171 /// arguments at a time; looking up exactly one schema is cheaper and
172 /// simpler than enumerating and filtering the full `schemas()` vector on
173 /// every dispatch.
174 /// What: Returns `Some(tool.schema())` for a registered `name`, else `None`.
175 /// Test: `schema_for_returns_registered_tool_schema`, `schema_for_none_when_missing`.
176 pub fn schema_for(&self, name: &str) -> Option<Value> {
177 self.tools.get(name).map(|t| t.schema())
178 }
179
180 /// Return the subset of registered tools that `user` may invoke.
181 ///
182 /// Why: Schema emission for the LLM request must reflect what the user can
183 /// actually call, otherwise the model will hallucinate denied calls.
184 /// What: Returns cloned `Arc`s for tools where `user.can_access_tier` is true.
185 /// Test: `filter_tools_for_user_drops_restricted`.
186 pub fn filter_tools_for_user(&self, user: &UserIdentity) -> Vec<Arc<dyn ToolExecutor>> {
187 self.tools
188 .values()
189 .filter(|t| user.can_access_tier(t.restricted_tiers()))
190 .cloned()
191 .collect()
192 }
193}
194
195// ── Tests ─────────────────────────────────────────────────────────────────────
196
197#[cfg(test)]
198mod tests {
199 use std::sync::Arc;
200
201 use async_trait::async_trait;
202 use serde_json::{Value, json};
203
204 use super::ToolRegistry;
205 use crate::rbac::{ServiceTier, UserIdentity};
206 use crate::tools::traits::{ToolExecutor, ToolResult};
207
208 /// Minimal mock tool for registry tests.
209 struct MockTool {
210 name: &'static str,
211 restricted: Vec<ServiceTier>,
212 }
213
214 impl MockTool {
215 fn new(name: &'static str) -> Self {
216 Self {
217 name,
218 restricted: vec![],
219 }
220 }
221
222 fn restricted(mut self, tier: ServiceTier) -> Self {
223 self.restricted.push(tier);
224 self
225 }
226 }
227
228 #[async_trait]
229 impl ToolExecutor for MockTool {
230 fn name(&self) -> &str {
231 self.name
232 }
233
234 fn schema(&self) -> Value {
235 json!({"type": "function", "function": {"name": self.name, "description": "mock"}})
236 }
237
238 async fn execute(&self, _args: Value) -> ToolResult {
239 ToolResult::ok(format!("mock-{} executed", self.name))
240 }
241
242 fn restricted_tiers(&self) -> &[ServiceTier] {
243 &self.restricted
244 }
245 }
246
247 /// A new registry has no tools.
248 ///
249 /// Why: Guard the baseline.
250 /// What: `new()` + `contains("any")` → false.
251 /// Test: This test.
252 #[test]
253 fn new_registry_is_empty() {
254 let reg = ToolRegistry::new();
255 assert!(!reg.contains("anything"));
256 assert!(reg.schemas().is_empty());
257 }
258
259 /// Registering a tool makes it findable.
260 ///
261 /// Why: Verify the basic register+contains contract.
262 /// What: Register "mock", then `contains("mock")` is true.
263 /// Test: This test.
264 #[test]
265 fn contains_after_register() {
266 let mut reg = ToolRegistry::new();
267 reg.register(Arc::new(MockTool::new("mock")));
268 assert!(reg.contains("mock"));
269 }
270
271 /// Dispatch to an unknown tool returns a structured error.
272 ///
273 /// Why: The LLM loop must not panic or abort on a missing tool.
274 /// What: `dispatch("unknown", {})` returns `ToolResult::Error`.
275 /// Test: This test.
276 #[tokio::test]
277 async fn dispatch_unknown_returns_error() {
278 let reg = ToolRegistry::new();
279 let result = reg.dispatch("unknown", json!({})).await;
280 assert!(result.is_error());
281 assert!(result.content().contains("no tool registered"));
282 }
283
284 /// Dispatch to a registered tool returns its output.
285 ///
286 /// Why: Verify the happy-path dispatch contract.
287 /// What: Register "mock", dispatch to it, assert success content.
288 /// Test: This test.
289 #[tokio::test]
290 async fn dispatch_registered_tool_succeeds() {
291 let mut reg = ToolRegistry::new();
292 reg.register(Arc::new(MockTool::new("mock")));
293 let result = reg.dispatch("mock", json!({})).await;
294 assert!(!result.is_error());
295 assert!(result.content().contains("mock-mock executed"));
296 }
297
298 /// `schemas()` returns one entry per registered tool.
299 ///
300 /// Why: Verify schema emission count.
301 /// What: Register two tools; `schemas()` returns 2 items.
302 /// Test: This test.
303 #[test]
304 fn schemas_returns_one_per_tool() {
305 let mut reg = ToolRegistry::new();
306 reg.register(Arc::new(MockTool::new("tool_a")));
307 reg.register(Arc::new(MockTool::new("tool_b")));
308 assert_eq!(reg.schemas().len(), 2);
309 }
310
311 /// `schema_for` returns the registered tool's schema.
312 ///
313 /// Why: Guard the direct single-tool lookup used by `ToolCallExtractor`.
314 /// What: Register "mock", fetch its schema by name, assert its shape.
315 /// Test: this test.
316 #[test]
317 fn schema_for_returns_registered_tool_schema() {
318 let mut reg = ToolRegistry::new();
319 reg.register(Arc::new(MockTool::new("mock")));
320 let schema = reg.schema_for("mock").expect("schema present");
321 assert_eq!(schema["function"]["name"], "mock");
322 }
323
324 /// `schema_for` returns `None` for an unregistered name.
325 ///
326 /// Why: Guard the miss path — no panic, no default schema fabricated.
327 /// What: Query a name that was never registered.
328 /// Test: this test.
329 #[test]
330 fn schema_for_none_when_missing() {
331 let reg = ToolRegistry::new();
332 assert!(reg.schema_for("does_not_exist").is_none());
333 }
334
335 /// `dispatch_gated` rejects a tool not in the allowlist.
336 ///
337 /// Why: Per-agent allowlists must be enforced at dispatch.
338 /// What: Register "mock", call `dispatch_gated("mock", {}, Some(&["other"]))`,
339 /// expect error.
340 /// Test: This test.
341 #[tokio::test]
342 async fn dispatch_gated_rejects_disallowed() {
343 let mut reg = ToolRegistry::new();
344 reg.register(Arc::new(MockTool::new("mock")));
345 let allowed = vec!["other".to_string()];
346 let result = reg.dispatch_gated("mock", json!({}), Some(&allowed)).await;
347 assert!(result.is_error());
348 assert!(result.content().contains("not permitted"));
349 }
350
351 /// `dispatch_gated` with `allowed = None` passes through.
352 ///
353 /// Why: `None` allowlist means no per-agent restriction.
354 /// What: `dispatch_gated("mock", {}, None)` calls through to dispatch.
355 /// Test: This test.
356 #[tokio::test]
357 async fn dispatch_gated_none_allowlist_permits() {
358 let mut reg = ToolRegistry::new();
359 reg.register(Arc::new(MockTool::new("mock")));
360 let result = reg.dispatch_gated("mock", json!({}), None).await;
361 assert!(!result.is_error());
362 }
363
364 /// `dispatch_for_user` blocks a restricted tier.
365 ///
366 /// Why: RBAC must be enforced at dispatch.
367 /// What: Register a tool restricted to `[ReadOnly]`, dispatch as a
368 /// `ReadOnly` user, expect error.
369 /// Test: This test.
370 #[tokio::test]
371 async fn dispatch_for_user_blocks_restricted_tier() {
372 let mut reg = ToolRegistry::new();
373 let tool = MockTool::new("secret_tool").restricted(ServiceTier::ReadOnly);
374 reg.register(Arc::new(tool));
375
376 let user = UserIdentity::new("u1", "alice", ServiceTier::ReadOnly);
377 let result = reg
378 .dispatch_for_user("secret_tool", json!({}), None, &user)
379 .await;
380 assert!(result.is_error());
381 assert!(result.content().contains("access tier"));
382 }
383
384 /// `dispatch_for_user` allows an unrestricted tier.
385 ///
386 /// Why: `All` tier must pass unrestricted tools.
387 /// What: Register an unrestricted tool, dispatch as `All`, expect success.
388 /// Test: This test.
389 #[tokio::test]
390 async fn dispatch_for_user_allows_unrestricted() {
391 let mut reg = ToolRegistry::new();
392 reg.register(Arc::new(MockTool::new("open_tool")));
393
394 let user = UserIdentity::default(); // tier = All
395 let result = reg
396 .dispatch_for_user("open_tool", json!({}), None, &user)
397 .await;
398 assert!(!result.is_error());
399 }
400
401 /// `gated` retains only the tools named in the allowlist.
402 ///
403 /// Why: This is the enforcement point for an agent's `tools.allowed`; the
404 /// resulting registry must contain exactly the permitted tools.
405 /// What: Register three tools, gate to two of them, assert membership.
406 /// Test: This test.
407 #[test]
408 fn gated_keeps_only_allowed() {
409 let mut reg = ToolRegistry::new();
410 reg.register(Arc::new(MockTool::new("read_file")));
411 reg.register(Arc::new(MockTool::new("write_file")));
412 reg.register(Arc::new(MockTool::new("bash")));
413
414 let allowed = vec!["read_file".to_string(), "bash".to_string()];
415 let gated = reg.gated(&allowed);
416
417 assert!(gated.contains("read_file"), "allowed tool must survive");
418 assert!(gated.contains("bash"), "allowed tool must survive");
419 assert!(
420 !gated.contains("write_file"),
421 "denied tool must be dropped from the gated registry"
422 );
423 assert_eq!(gated.schemas().len(), 2, "exactly the two allowed tools");
424 }
425
426 /// `gated` silently ignores allowlist entries that match no registered tool.
427 ///
428 /// Why: A typo in an agent's `tools.allowed` should not be a hard error; it
429 /// simply contributes no tool to the gated registry.
430 /// What: Gate with a mix of a real and a bogus name; only the real one survives.
431 /// Test: This test.
432 #[test]
433 fn gated_ignores_unknown_names() {
434 let mut reg = ToolRegistry::new();
435 reg.register(Arc::new(MockTool::new("read_file")));
436
437 let allowed = vec!["read_file".to_string(), "does_not_exist".to_string()];
438 let gated = reg.gated(&allowed);
439
440 assert!(gated.contains("read_file"));
441 assert_eq!(gated.schemas().len(), 1, "unknown name registers nothing");
442 }
443
444 /// `gated` with an empty allowlist produces an empty registry.
445 ///
446 /// Why: An agent that explicitly allows no tools must be handed a registry
447 /// with no tools (the model then has nothing to call).
448 /// What: Gate a populated registry with `&[]`; assert empty.
449 /// Test: This test.
450 #[test]
451 fn gated_empty_allowlist_is_empty() {
452 let mut reg = ToolRegistry::new();
453 reg.register(Arc::new(MockTool::new("read_file")));
454 let gated = reg.gated(&[]);
455 assert!(gated.schemas().is_empty());
456 assert!(!gated.contains("read_file"));
457 }
458
459 /// `filter_tools_for_user` drops tools that the user's tier is blocked for.
460 ///
461 /// Why: LLM should not see tools it cannot call.
462 /// What: Register one restricted and one open tool; filter for `ReadOnly`.
463 /// Expected: only the open tool survives.
464 /// Test: This test.
465 #[test]
466 fn filter_tools_for_user_drops_restricted() {
467 let mut reg = ToolRegistry::new();
468 reg.register(Arc::new(MockTool::new("open")));
469 reg.register(Arc::new(
470 MockTool::new("restricted").restricted(ServiceTier::ReadOnly),
471 ));
472
473 let user = UserIdentity::new("u", "u", ServiceTier::ReadOnly);
474 let filtered = reg.filter_tools_for_user(&user);
475 assert_eq!(filtered.len(), 1, "only the open tool should survive");
476 assert_eq!(filtered[0].name(), "open");
477 }
478}