use std::collections::HashMap;
use std::sync::Arc;
use serde_json::Value;
use crate::rbac::UserIdentity;
use crate::tools::traits::{ToolExecutor, ToolResult};
#[derive(Default)]
pub struct ToolRegistry {
tools: HashMap<String, Arc<dyn ToolExecutor>>,
}
impl ToolRegistry {
pub fn new() -> Self {
Self {
tools: HashMap::new(),
}
}
pub fn register(&mut self, tool: Arc<dyn ToolExecutor>) {
let name = tool.name().to_string();
debug_assert!(
!self.tools.contains_key(&name),
"duplicate tool registration for '{name}' — collisions overwrite and cause dispatch bugs"
);
self.tools.insert(name, tool);
}
pub fn contains(&self, name: &str) -> bool {
self.tools.contains_key(name)
}
pub async fn dispatch(&self, name: &str, args: Value) -> ToolResult {
let Some(tool) = self.tools.get(name) else {
return ToolResult::err(format!("no tool registered with name '{name}'"));
};
tool.execute(args).await
}
pub async fn dispatch_gated(
&self,
name: &str,
args: Value,
allowed: Option<&[String]>,
) -> ToolResult {
if let Some(list) = allowed
&& !list.iter().any(|a| a == name)
{
return ToolResult::err(format!(
"Tool '{name}' is not permitted for this agent. Allowed: {}",
list.join(", ")
));
}
self.dispatch(name, args).await
}
pub async fn dispatch_for_user(
&self,
name: &str,
args: Value,
allowed: Option<&[String]>,
user: &UserIdentity,
) -> ToolResult {
if let Some(tool) = self.tools.get(name)
&& !user.can_access_tier(tool.restricted_tiers())
{
return ToolResult::err("This tool is not available for your access tier.");
}
self.dispatch_gated(name, args, allowed).await
}
pub fn gated(&self, allowed: &[String]) -> ToolRegistry {
let tools = self
.tools
.iter()
.filter(|(name, _)| allowed.iter().any(|a| a == *name))
.map(|(name, tool)| (name.clone(), Arc::clone(tool)))
.collect();
ToolRegistry { tools }
}
pub fn schemas(&self) -> Vec<Value> {
self.tools.values().map(|t| t.schema()).collect()
}
pub fn schema_for(&self, name: &str) -> Option<Value> {
self.tools.get(name).map(|t| t.schema())
}
pub fn filter_tools_for_user(&self, user: &UserIdentity) -> Vec<Arc<dyn ToolExecutor>> {
self.tools
.values()
.filter(|t| user.can_access_tier(t.restricted_tiers()))
.cloned()
.collect()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use super::ToolRegistry;
use crate::rbac::{ServiceTier, UserIdentity};
use crate::tools::traits::{ToolExecutor, ToolResult};
struct MockTool {
name: &'static str,
restricted: Vec<ServiceTier>,
}
impl MockTool {
fn new(name: &'static str) -> Self {
Self {
name,
restricted: vec![],
}
}
fn restricted(mut self, tier: ServiceTier) -> Self {
self.restricted.push(tier);
self
}
}
#[async_trait]
impl ToolExecutor for MockTool {
fn name(&self) -> &str {
self.name
}
fn schema(&self) -> Value {
json!({"type": "function", "function": {"name": self.name, "description": "mock"}})
}
async fn execute(&self, _args: Value) -> ToolResult {
ToolResult::ok(format!("mock-{} executed", self.name))
}
fn restricted_tiers(&self) -> &[ServiceTier] {
&self.restricted
}
}
#[test]
fn new_registry_is_empty() {
let reg = ToolRegistry::new();
assert!(!reg.contains("anything"));
assert!(reg.schemas().is_empty());
}
#[test]
fn contains_after_register() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("mock")));
assert!(reg.contains("mock"));
}
#[tokio::test]
async fn dispatch_unknown_returns_error() {
let reg = ToolRegistry::new();
let result = reg.dispatch("unknown", json!({})).await;
assert!(result.is_error());
assert!(result.content().contains("no tool registered"));
}
#[tokio::test]
async fn dispatch_registered_tool_succeeds() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("mock")));
let result = reg.dispatch("mock", json!({})).await;
assert!(!result.is_error());
assert!(result.content().contains("mock-mock executed"));
}
#[test]
fn schemas_returns_one_per_tool() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("tool_a")));
reg.register(Arc::new(MockTool::new("tool_b")));
assert_eq!(reg.schemas().len(), 2);
}
#[test]
fn schema_for_returns_registered_tool_schema() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("mock")));
let schema = reg.schema_for("mock").expect("schema present");
assert_eq!(schema["function"]["name"], "mock");
}
#[test]
fn schema_for_none_when_missing() {
let reg = ToolRegistry::new();
assert!(reg.schema_for("does_not_exist").is_none());
}
#[tokio::test]
async fn dispatch_gated_rejects_disallowed() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("mock")));
let allowed = vec!["other".to_string()];
let result = reg.dispatch_gated("mock", json!({}), Some(&allowed)).await;
assert!(result.is_error());
assert!(result.content().contains("not permitted"));
}
#[tokio::test]
async fn dispatch_gated_none_allowlist_permits() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("mock")));
let result = reg.dispatch_gated("mock", json!({}), None).await;
assert!(!result.is_error());
}
#[tokio::test]
async fn dispatch_for_user_blocks_restricted_tier() {
let mut reg = ToolRegistry::new();
let tool = MockTool::new("secret_tool").restricted(ServiceTier::ReadOnly);
reg.register(Arc::new(tool));
let user = UserIdentity::new("u1", "alice", ServiceTier::ReadOnly);
let result = reg
.dispatch_for_user("secret_tool", json!({}), None, &user)
.await;
assert!(result.is_error());
assert!(result.content().contains("access tier"));
}
#[tokio::test]
async fn dispatch_for_user_allows_unrestricted() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("open_tool")));
let user = UserIdentity::default(); let result = reg
.dispatch_for_user("open_tool", json!({}), None, &user)
.await;
assert!(!result.is_error());
}
#[test]
fn gated_keeps_only_allowed() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("read_file")));
reg.register(Arc::new(MockTool::new("write_file")));
reg.register(Arc::new(MockTool::new("bash")));
let allowed = vec!["read_file".to_string(), "bash".to_string()];
let gated = reg.gated(&allowed);
assert!(gated.contains("read_file"), "allowed tool must survive");
assert!(gated.contains("bash"), "allowed tool must survive");
assert!(
!gated.contains("write_file"),
"denied tool must be dropped from the gated registry"
);
assert_eq!(gated.schemas().len(), 2, "exactly the two allowed tools");
}
#[test]
fn gated_ignores_unknown_names() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("read_file")));
let allowed = vec!["read_file".to_string(), "does_not_exist".to_string()];
let gated = reg.gated(&allowed);
assert!(gated.contains("read_file"));
assert_eq!(gated.schemas().len(), 1, "unknown name registers nothing");
}
#[test]
fn gated_empty_allowlist_is_empty() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("read_file")));
let gated = reg.gated(&[]);
assert!(gated.schemas().is_empty());
assert!(!gated.contains("read_file"));
}
#[test]
fn filter_tools_for_user_drops_restricted() {
let mut reg = ToolRegistry::new();
reg.register(Arc::new(MockTool::new("open")));
reg.register(Arc::new(
MockTool::new("restricted").restricted(ServiceTier::ReadOnly),
));
let user = UserIdentity::new("u", "u", ServiceTier::ReadOnly);
let filtered = reg.filter_tools_for_user(&user);
assert_eq!(filtered.len(), 1, "only the open tool should survive");
assert_eq!(filtered[0].name(), "open");
}
}