use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::types::{AgentError, AgentResult};
use super::{Content, Tool, ToolActivation, ToolContext, ToolExposure};
pub struct ActivateTool {
activation: ToolActivation,
candidates: HashMap<String, (ToolExposure, Value)>,
}
impl ActivateTool {
pub fn new(
activation: ToolActivation,
candidates: Vec<(String, ToolExposure, Value)>,
) -> Arc<Self> {
Arc::new(Self {
activation,
candidates: candidates
.into_iter()
.map(|(name, exposure, def)| (name, (exposure, def)))
.collect(),
})
}
fn candidate_names(&self) -> Vec<&str> {
let mut names: Vec<&str> = self.candidates.keys().map(|s| s.as_str()).collect();
names.sort_unstable();
names
}
}
#[async_trait]
impl Tool for ActivateTool {
fn name(&self) -> &'static str {
"activate_tool"
}
fn description(&self) -> &'static str {
"Mount a tool whose schema is not loaded yet.\n\n\
Some tools are named in the system message but their schemas are NOT loaded — until\n\
they are, only the name is known, and calling one fails: there is no parameter\n\
schema to call it with. This tool loads it.\n\
Pass the tool's name exactly as the roster spells it. The result is that tool's full\n\
description and argument schema, and from your next turn on it is callable exactly\n\
like any tool already in your list — and it stays mounted for the rest of the\n\
session, so open it once and use it as often as you need.\n\
A name that is not mountable comes back with the ones that are. A name that is\n\
already mounted comes back saying so. Do not open a capability on the chance it\n\
comes in handy: every mounted tool is sent on every later request."
}
fn schema(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The tool name exactly as the roster spells it."
}
},
"required": ["name"],
"additionalProperties": false,
})
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
let name = args
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| AgentError::ToolArgsInvalid {
name: self.name().to_string(),
raw: "missing field `name` — pass the tool name exactly as the roster spells it"
.to_string(),
})?;
let Some((exposure, definition)) = self.candidates.get(name) else {
return Ok(vec![Content::text(format!(
"No tool named `{name}` is mountable. Mountable names: {}.",
self.candidate_names().join(", ")
))]);
};
match exposure {
ToolExposure::Hidden => Ok(vec![Content::text(format!(
"`{name}` is internal and is not mountable. It is not in the roster."
))]),
ToolExposure::Direct => Ok(vec![Content::text(format!(
"`{name}` is already mounted — call it directly."
))]),
ToolExposure::Deferred => {
let first_open = self.activation.activate(name);
let status = if first_open {
"mounted"
} else {
"already mounted"
};
Ok(vec![Content::text(format!(
"`{name}` {status}. Call it from the next turn on, with these arguments:\n{}",
serde_json::to_string_pretty(definition).unwrap_or_default()
))])
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicBool;
use super::*;
use crate::engine::EventBus;
use crate::tool::ExecClock;
use crate::types::SessionId;
use serde_json::json;
fn test_context() -> ToolContext {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
ToolContext {
session_id: SessionId::new(0),
user_event_tx: tx,
llm_client: None,
session_store: None,
language: crate::types::Language::En,
cancel_token: tokio_util::sync::CancellationToken::new(),
max_output_chars: None,
exec_clock: ExecClock::default(),
waiting_for_human: Arc::new(AtomicBool::new(false)),
event_bus: EventBus::new(1),
}
}
fn registry_free_tool() -> (ActivateTool, ToolActivation) {
let activation = ToolActivation::new();
let tool = ActivateTool::new(
activation.clone(),
vec![
(
"browser_navigate".to_string(),
ToolExposure::Deferred,
json!({
"name": "browser_navigate",
"description": "Open a URL in the browser.",
"parameters": {"type": "object", "properties": {"url": {"type": "string"}}},
}),
),
(
"always_here".to_string(),
ToolExposure::Direct,
json!({"name": "always_here"}),
),
(
"internal".to_string(),
ToolExposure::Hidden,
json!({"name": "internal"}),
),
],
);
let tool = Arc::try_unwrap(tool).ok().expect("single owner in tests");
(tool, activation)
}
async fn call(tool: &ActivateTool, args: Value) -> String {
let ctx = test_context();
let out = tool.call(&args, &ctx).await.expect("call succeeds");
out.iter()
.map(|c| match c {
Content::Text { text } => text.clone(),
_ => String::new(),
})
.collect()
}
#[tokio::test]
async fn opening_a_tool_mounts_it_and_hands_back_its_shape() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "browser_navigate"})).await;
assert!(
activation.is_active("browser_navigate"),
"opening must stick for the session"
);
assert!(out.contains("mounted"), "say what happened: {out}");
assert!(
out.contains("\"url\""),
"and hand back the real arguments, not just the name: {out}"
);
}
#[tokio::test]
async fn an_unknown_name_is_refused_with_the_real_ones() {
let (tool, _activation) = registry_free_tool();
let out = call(&tool, json!({"name": "browser_nav"})).await;
assert!(out.contains("No tool named `browser_nav`"), "{out}");
assert!(
out.contains("browser_navigate"),
"the answer must name the tool it meant: {out}"
);
}
#[tokio::test]
async fn an_internal_tool_cannot_be_mounted() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "internal"})).await;
assert!(out.contains("not mountable"), "{out}");
assert!(!activation.is_active("internal"), "and nothing was opened");
}
#[tokio::test]
async fn opening_twice_is_reported_as_already_mounted() {
let (tool, _activation) = registry_free_tool();
call(&tool, json!({"name": "browser_navigate"})).await;
let out = call(&tool, json!({"name": "browser_navigate"})).await;
assert!(out.contains("already mounted"), "{out}");
}
#[tokio::test]
async fn an_already_mounted_tool_is_said_to_be() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "always_here"})).await;
assert!(out.contains("already mounted"), "{out}");
assert!(
!activation.is_active("always_here"),
"a Direct tool needs no activation entry"
);
}
#[tokio::test]
async fn a_missing_name_says_what_is_missing() {
let (tool, _activation) = registry_free_tool();
let err = tool.call(&json!({}), &test_context()).await;
let msg = format!("{:?}", err.expect_err("no name is an error"));
assert!(
msg.contains("`name`"),
"the error must name the field: {msg}"
);
}
}