Skip to main content

a3s_code_core/tools/builtin/
mod.rs

1//! Native Rust implementations of all built-in tools
2//!
3//! These replace the previous `a3s-tools` binary backend with direct Rust
4//! implementations that execute in-process. Each tool implements the `Tool` trait.
5
6pub(crate) mod bash;
7pub mod batch;
8mod code_intelligence;
9mod edit;
10mod generate_object;
11pub(crate) mod git;
12mod glob_tool;
13mod grep;
14mod ls;
15mod patch;
16mod read;
17mod web_fetch;
18mod web_search;
19mod write;
20
21use super::registry::ToolRegistry;
22use std::sync::Arc;
23
24/// Normalize a source URL before it can enter durable tool/task metadata.
25/// Credentials, query strings, and fragments are intentionally excluded.
26pub(crate) fn safe_http_source_url(value: &str) -> Option<String> {
27    let mut url = reqwest::Url::parse(value.trim()).ok()?;
28    if !matches!(url.scheme(), "http" | "https") || url.host_str()?.is_empty() {
29        return None;
30    }
31    url.set_username("").ok()?;
32    url.set_password(None).ok()?;
33    url.set_query(None);
34    url.set_fragment(None);
35    Some(url.to_string())
36}
37
38/// Register all baseline built-in tools with the registry, gated by
39/// workspace capabilities.
40///
41/// Tools whose required capability is missing are not registered, so the model
42/// never sees a tool the backend cannot service. `web_fetch` and `web_search`
43/// have no workspace capability and are always registered.
44///
45/// Note: `batch` is NOT registered here — it requires an `Arc<ToolRegistry>`
46/// and must be registered after the registry is wrapped in an Arc.
47pub fn register_builtins(
48    registry: &ToolRegistry,
49    workspace_services: &crate::workspace::WorkspaceServices,
50) {
51    let capabilities = workspace_services.capabilities();
52    if capabilities.read {
53        registry.register_builtin(Arc::new(read::ReadTool));
54        registry.register_builtin(Arc::new(ls::LsTool));
55    }
56    if capabilities.write {
57        registry.register_builtin(Arc::new(write::WriteTool));
58    }
59    if capabilities.read && capabilities.write {
60        registry.register_builtin(Arc::new(edit::EditTool));
61        registry.register_builtin(Arc::new(patch::PatchTool));
62    }
63    if capabilities.exec {
64        registry.register_builtin(Arc::new(bash::BashTool));
65    }
66    if capabilities.search {
67        registry.register_builtin(Arc::new(grep::GrepTool));
68        registry.register_builtin(Arc::new(glob_tool::GlobTool));
69    }
70    if workspace_services.code_intelligence().is_some() {
71        code_intelligence::register(registry);
72    }
73    if capabilities.git {
74        registry.register_builtin(Arc::new(git::GitTool));
75    }
76    registry.register_builtin(Arc::new(web_fetch::WebFetchTool));
77    registry.register_builtin(Arc::new(web_search::WebSearchTool::new()));
78}
79
80/// Register the batch tool. Must be called after the registry is wrapped in Arc.
81pub fn register_batch(registry: &Arc<ToolRegistry>) {
82    registry.register_builtin(Arc::new(batch::BatchTool::new(Arc::clone(registry))));
83}
84
85/// Register the programmatic tool calling wrapper.
86pub fn register_program(registry: &Arc<ToolRegistry>) {
87    register_program_with_catalog(
88        registry,
89        crate::program::ProgramCatalog::with_builtin_programs(),
90    );
91}
92
93/// Register the programmatic tool calling wrapper with a custom catalog.
94pub fn register_program_with_catalog(
95    registry: &Arc<ToolRegistry>,
96    catalog: crate::program::ProgramCatalog,
97) {
98    registry.register_builtin(Arc::new(crate::tools::ProgramTool::with_catalog(
99        Arc::clone(registry),
100        catalog,
101    )));
102}
103
104/// Register the task delegation tools (task, parallel_task).
105///
106/// Must be called after the registry is wrapped in Arc. Requires an LLM client
107/// and the workspace path so child agent loops can be spawned inline.
108/// Optionally accepts an MCP manager so child sessions inherit MCP tools.
109pub fn register_task(
110    registry: &Arc<ToolRegistry>,
111    llm_client: Arc<dyn crate::llm::LlmClient>,
112    agent_registry: Arc<crate::subagent::AgentRegistry>,
113    workspace: String,
114) {
115    register_task_with_mcp(
116        registry,
117        llm_client,
118        agent_registry,
119        workspace,
120        None,
121        None,
122        None,
123    );
124}
125
126/// Register the task delegation tools with optional MCP manager and parent context.
127///
128/// When `mcp_manager` is provided, delegated child sessions will have access
129/// to all MCP tools from connected servers.
130/// When `parent_context` is provided, child runs inherit parent capabilities.
131/// When `subagent_tracker` is provided, each task registers a
132/// `CancellationToken` against it so callers can cancel by `task_id`.
133pub fn register_task_with_mcp(
134    registry: &Arc<ToolRegistry>,
135    llm_client: Arc<dyn crate::llm::LlmClient>,
136    agent_registry: Arc<crate::subagent::AgentRegistry>,
137    workspace: String,
138    mcp_manager: Option<Arc<crate::mcp::manager::McpManager>>,
139    parent_context: Option<crate::child_run::ChildRunContext>,
140    subagent_tracker: Option<Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>>,
141) {
142    register_task_with_mcp_managers(
143        registry,
144        llm_client,
145        agent_registry,
146        workspace,
147        mcp_manager.into_iter().collect(),
148        parent_context,
149        subagent_tracker,
150    );
151}
152
153/// Register task delegation tools with ordered MCP capability sources.
154///
155/// Each manager keeps ownership of its own connections. Later sources shadow
156/// earlier sources on identical fully-qualified tool names inside child runs.
157pub fn register_task_with_mcp_managers(
158    registry: &Arc<ToolRegistry>,
159    llm_client: Arc<dyn crate::llm::LlmClient>,
160    agent_registry: Arc<crate::subagent::AgentRegistry>,
161    workspace: String,
162    mcp_managers: Vec<Arc<crate::mcp::manager::McpManager>>,
163    parent_context: Option<crate::child_run::ChildRunContext>,
164    subagent_tracker: Option<Arc<crate::subagent_task_tracker::InMemorySubagentTaskTracker>>,
165) {
166    use crate::tools::task::{ParallelTaskTool, TaskExecutor, TaskTool};
167    let mut executor =
168        TaskExecutor::with_mcp_managers(agent_registry, llm_client, workspace, mcp_managers);
169    if let Some(ctx) = parent_context {
170        executor = executor.with_parent_context(ctx);
171    }
172    if let Some(tracker) = subagent_tracker {
173        executor = executor.with_subagent_tracker(tracker);
174    }
175    let executor = Arc::new(executor);
176    registry.register_builtin(Arc::new(TaskTool::new(Arc::clone(&executor))));
177    registry.register_builtin(Arc::new(ParallelTaskTool::new(Arc::clone(&executor))));
178}
179
180/// Register the Skill tool for skill-based tool access control.
181pub(crate) fn register_skill(
182    registry: &Arc<ToolRegistry>,
183    llm_client: Arc<dyn crate::llm::LlmClient>,
184    skill_registry: Arc<crate::skills::SkillRegistry>,
185    tool_executor: Arc<crate::tools::ToolExecutor>,
186    base_config: crate::agent::AgentConfig,
187) {
188    use crate::tools::skill::{SearchSkillsTool, SkillTool};
189    registry.register_builtin(Arc::new(SearchSkillsTool::new(Arc::clone(&skill_registry))));
190    registry.register_builtin(Arc::new(SkillTool::new(
191        skill_registry,
192        llm_client,
193        tool_executor,
194        base_config,
195    )));
196}
197
198/// Register the `generate_object` tool for structured JSON output.
199///
200/// Must be called after the registry is wrapped in Arc. Requires an LLM client
201/// so the tool can make its own LLM calls for object generation.
202pub fn register_generate_object(
203    registry: &Arc<ToolRegistry>,
204    llm_client: Arc<dyn crate::llm::LlmClient>,
205) {
206    registry.register_builtin(Arc::new(generate_object::GenerateObjectTool::new(
207        llm_client,
208    )));
209}
210
211#[cfg(test)]
212mod tests {
213    use super::safe_http_source_url;
214
215    #[test]
216    fn safe_source_url_removes_credentials_query_and_fragment() {
217        assert_eq!(
218            safe_http_source_url(
219                "HTTPS://user:password@Example.COM/report?access_token=secret#section"
220            )
221            .as_deref(),
222            Some("https://example.com/report")
223        );
224        assert!(safe_http_source_url("file:///tmp/source").is_none());
225    }
226}