diff --git a/crates/goose/src/agents/extension_manager/lease.rs b/crates/goose/src/agents/extension_manager/lease.rs index d0aa99bcc..8cfb1887b 100644 --- a/crates/goose/src/agents/extension_manager/lease.rs +++ b/crates/goose/src/agents/extension_manager/lease.rs @@ -267,32 +267,28 @@ impl ExtensionLease { } pub async fn tools(&self) -> Vec { - self.tool_catalog() - .await - .entries - .iter() - .map(|entry| entry.tool.clone()) - .collect() + self.tools_where(|_| true).await } pub async fn tools_for(&self, extension: &str) -> Vec { let key = name_to_key(extension); - self.tool_catalog() - .await - .entries - .iter() - .filter(|entry| entry.extension.key == key) - .map(|entry| entry.tool.clone()) - .collect() + self.tools_where(|extension| extension.key == key).await } pub async fn tools_excluding(&self, extension: &str) -> Vec { let key = name_to_key(extension); + self.tools_where(|extension| extension.key != key).await + } + + pub(in crate::agents) async fn tools_where( + &self, + predicate: impl Fn(&Extension) -> bool, + ) -> Vec { self.tool_catalog() .await .entries .iter() - .filter(|entry| entry.extension.key != key) + .filter(|entry| predicate(&entry.extension)) .map(|entry| entry.tool.clone()) .collect() } diff --git a/crates/goose/src/agents/services.rs b/crates/goose/src/agents/services.rs index 0cd746432..aa6054750 100644 --- a/crates/goose/src/agents/services.rs +++ b/crates/goose/src/agents/services.rs @@ -118,6 +118,8 @@ pub struct TurnSettings { pub on_failure_timeout: std::time::Duration, pub stop_hook_block_cap: u32, pub tool_pair_summarization: bool, + pub defer_tools: bool, + pub always_load_tools: Vec, pub compaction_threshold: f64, pub compaction_token_limit: usize, /// `None` derives it from the context limit. @@ -148,6 +150,17 @@ impl TurnSettings { .get_param::("GOOSE_STOP_HOOK_BLOCK_CAP") .unwrap_or(DEFAULT_DENY_LIMIT), tool_pair_summarization: crate::context_mgmt::tool_pair_summarization_enabled(), + defer_tools: config + .get_param::("GOOSE_TOOL_DEFERRAL") + .is_ok_and(|value| value == "lookup"), + always_load_tools: config + .get_param::("GOOSE_TOOL_DEFERRAL_ALWAYS_LOAD") + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect(), compaction_threshold: config .get_param::("GOOSE_AUTO_COMPACT_THRESHOLD") .unwrap_or(crate::context_mgmt::DEFAULT_COMPACTION_THRESHOLD), @@ -778,6 +791,8 @@ impl StateMachineServices { compaction_threshold, tool_call_cutoff, tool_pair_summarization: settings.tool_pair_summarization, + defer_tools: settings.defer_tools, + always_load_tools: settings.always_load_tools.clone(), session_manager: self.session_manager.clone(), extension_manager: Arc::clone(&self.extension_manager), extension_lease, diff --git a/crates/goose/src/agents/state_machine/ops_toolcalling.rs b/crates/goose/src/agents/state_machine/ops_toolcalling.rs index d5020d4e7..d5fea2e1e 100644 --- a/crates/goose/src/agents/state_machine/ops_toolcalling.rs +++ b/crates/goose/src/agents/state_machine/ops_toolcalling.rs @@ -8,11 +8,14 @@ use async_trait::async_trait; use futures::{FutureExt, StreamExt}; use goose_agent::post_tool_call_hook::PostToolCallHook; use goose_agent::tool_call_state::request_executable; -use rmcp::model::{CallToolRequestParams, CallToolResult, ContentBlock, ErrorData, Role, Tool}; +use rmcp::model::{ + CallToolRequestParams, CallToolResult, ContentBlock, ErrorData, Role, Tool, ToolAnnotations, +}; use crate::agents::extension::ExtensionInfo; use crate::agents::extension_manager::{CallRequest, ExtensionLease, ExtensionManager}; use crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME; +use crate::agents::reply_parts::is_tool_visible_to_model; use crate::agents::state_machine::ops_llm::{ADVERTISED_TOOLS_NOTE, LLM_OPERATION_NAME}; use crate::agents::state_machine::ops_recipe::final_output_called_with_other_tools; use crate::agents::state_machine::ops_skills::LOAD_SKILL_TOOL_NAME; @@ -40,6 +43,69 @@ use std::sync::{Arc, Mutex as StdMutex}; use tokio_util::sync::CancellationToken; use tracing_futures::Instrument; +const ENABLE_TOOLS: &str = "enable_tools"; + +#[derive(serde::Deserialize, schemars::JsonSchema)] +struct EnableToolsParams { + /// Exact MCP tool names to make available on the next response. + tool_names: Vec, +} + +fn enable_tools_tool() -> Result { + let schema: rmcp::model::JsonObject = serde_json::from_value(serde_json::to_value( + schemars::schema_for!(EnableToolsParams), + )?)?; + Ok(Tool::new( + ENABLE_TOOLS, + "Enable MCP tools listed in the system instructions. Call them in your next response.", + schema, + ) + .annotate(ToolAnnotations::new().read_only(true))) +} + +fn enabled_tools(conversation: &Conversation) -> HashSet { + let mut requests = HashSet::new(); + let mut enabled = HashSet::new(); + for content in conversation + .messages() + .iter() + .flat_map(|message| &message.content) + { + match content { + MessageContent::ToolRequest(request) + if request + .tool_call + .as_ref() + .is_ok_and(|call| call.name == ENABLE_TOOLS) => + { + requests.insert(&request.id); + } + MessageContent::ToolResponse(response) if requests.remove(&response.id) => { + let Ok(result) = &response.tool_result else { + continue; + }; + if result.is_error == Some(true) { + continue; + } + let Some(names) = result + .structured_content + .as_ref() + .and_then(|value| value["enabled"].as_array()) + else { + continue; + }; + enabled.extend( + names + .iter() + .filter_map(|name| name.as_str().map(str::to_string)), + ); + } + _ => {} + } + } + enabled +} + #[derive(Clone, Copy)] pub(super) enum ToolCategory { Shell, @@ -251,6 +317,8 @@ pub struct ToolExecutionOperation { post_tool_call_hook: Arc>, lease: Arc>>>, batch: Arc>, + defer_tools: bool, + always_load_tools: HashSet, } impl ToolExecutionOperation { @@ -259,6 +327,8 @@ impl ToolExecutionOperation { hook_manager: HookManager, post_tool_call_hook: Arc>, lease: Arc>>>, + defer_tools: bool, + always_load_tools: Vec, ) -> Self { Self { extension_manager, @@ -266,9 +336,56 @@ impl ToolExecutionOperation { post_tool_call_hook, lease, batch: Arc::default(), + defer_tools, + always_load_tools: always_load_tools.into_iter().collect(), } } + fn defers_tools(&self, lease: &ExtensionLease) -> bool { + #[cfg(feature = "code-mode")] + if lease.is_enabled(crate::agents::platform_extensions::code_execution::EXTENSION_NAME) { + return false; + } + let _ = lease; + self.defer_tools + } + + async fn mcp_tools(&self, lease: &ExtensionLease) -> Vec { + lease + .tools_where(|extension| !extension.is_platform()) + .await + .into_iter() + .filter(is_tool_visible_to_model) + .collect() + } + + async fn enable_tools( + &self, + lease: &ExtensionLease, + call: &CallToolRequestParams, + ) -> CallToolResult { + let params = serde_json::from_value::(serde_json::Value::Object( + call.arguments.clone().unwrap_or_default(), + )); + let params = match params { + Ok(params) => params, + Err(error) => { + return CallToolResult::error(vec![ContentBlock::text(error.to_string())]) + } + }; + let tools = self.mcp_tools(lease).await; + if let Some(name) = params + .tool_names + .iter() + .find(|name| !tools.iter().any(|tool| tool.name == name.as_str())) + { + return CallToolResult::error(vec![ContentBlock::text(format!( + "Unknown MCP tool: {name}" + ))]); + } + CallToolResult::structured(serde_json::json!({"enabled": params.tool_names})) + } + fn take_batch(&self) -> (Vec, Option) { self.batch.lock().unwrap().take() } @@ -320,21 +437,26 @@ impl ToolExecutionOperation { ) .await; - let result = lease - .call( - tool_call.clone(), - CallRequest::new(request_id.clone()).with_container(session.container.clone()), - cancellation_token, - ) - .await; - let result = result.unwrap_or_else(|error| { - #[cfg(feature = "telemetry")] - crate::posthog::emit_error( - "tool_execution_failed", - &format!("{}: {}", tool_call.name, error), - ); - ToolCallResult::from(Err(error)) - }); + let result = if self.defers_tools(&lease) && tool_call.name == ENABLE_TOOLS { + ToolCallResult::from(Ok(self.enable_tools(&lease, &tool_call).await)) + } else { + let result = lease + .call( + tool_call.clone(), + CallRequest::new(request_id.clone()) + .with_container(session.container.clone()), + cancellation_token, + ) + .await; + result.unwrap_or_else(|error| { + #[cfg(feature = "telemetry")] + crate::posthog::emit_error( + "tool_execution_failed", + &format!("{}: {}", tool_call.name, error), + ); + ToolCallResult::from(Err(error)) + }) + }; let result = self .extension_manager .applying_mutation(result, &session.id); @@ -704,15 +826,23 @@ pub(super) enum ToolDisposition { /// The extension block, as a header part plus one part per extension. Prompt /// extras are joined with a blank line, so this renders the same text as one /// combined part while keeping each extension's tokens attributable. -fn extension_prompt_parts(extensions: &[ExtensionInfo]) -> Vec<(String, String)> { +fn extension_prompt_parts( + extensions: &[ExtensionInfo], + defer_tools: bool, +) -> Vec<(String, String)> { let mut parts = vec![( "extensions".to_string(), "# Extensions\n\n\ Extensions provide additional tools and context from different data sources and applications.\n\ You can dynamically enable or disable extensions as needed to help complete tasks.\n\n\ - Because you dynamically load extensions, your conversation history may refer to interactions with extensions that are not currently active. The currently active extensions are below. Each of these extensions provides tools that are in your tool specification." + Because you dynamically load extensions, your conversation history may refer to interactions with extensions that are not currently active. The currently active extensions are below." .to_string(), )]; + if !defer_tools { + parts[0].1.push_str( + " Each of these extensions provides tools that are in your tool specification.", + ); + } for extension in extensions { let mut lines = vec![format!("## {}", extension.name)]; if extension.has_resources { @@ -767,11 +897,27 @@ impl Operation for ToolExecutionOperation { } async fn inference_tools(&self, session: &Session) -> Result> { - Ok(self - .lease(session) - .await? - .tools_excluding(crate::skills::EXTENSION_NAME) - .await) + let lease = self.lease(session).await?; + let mut tools = lease.tools_excluding(crate::skills::EXTENSION_NAME).await; + if self.defers_tools(&lease) { + let deferred: HashSet<_> = self + .mcp_tools(&lease) + .await + .into_iter() + .filter(|tool| !self.always_load_tools.contains(tool.name.as_ref())) + .map(|tool| tool.name.to_string()) + .collect(); + let enabled = session + .conversation + .as_ref() + .map(enabled_tools) + .unwrap_or_default(); + tools.retain(|tool| { + !deferred.contains(tool.name.as_ref()) || enabled.contains(tool.name.as_ref()) + }); + tools.push(enable_tools_tool()?); + } + Ok(tools) } async fn moim_parts( @@ -816,7 +962,25 @@ impl Operation for ToolExecutionOperation { } // HashMap order shuffles across restarts and would bust the prompt cache. extensions.sort_by(|a, b| a.name.cmp(&b.name)); - prompt_parts.extend(extension_prompt_parts(&extensions)); + prompt_parts.extend(extension_prompt_parts( + &extensions, + self.defers_tools(&lease), + )); + if self.defers_tools(&lease) { + let mut names: Vec<_> = self + .mcp_tools(&lease) + .await + .into_iter() + .filter(|tool| !self.always_load_tools.contains(tool.name.as_ref())) + .map(|tool| tool.name.to_string()) + .collect(); + names.sort(); + prompt_parts.push(("mcp_tools".to_string(), format!( + "MCP tools available to enable: {}. Call enable_tools with exact tool_names before using them. \ + Their schemas become available on your next response. Enabling does not execute a tool.", + names.join(", ") + ))); + } Ok(prompt_parts) } @@ -874,12 +1038,15 @@ impl Operation for ToolExecutionOperation { return applied([response.into()]); }; - let known_tools: HashSet<_> = lease + let mut known_tools: HashSet<_> = lease .tools_excluding(crate::skills::EXTENSION_NAME) .await .into_iter() .map(|tool| tool.name.to_string()) .collect(); + if self.defers_tools(&lease) { + known_tools.insert(ENABLE_TOOLS.to_string()); + } pending.retain(|(request, _)| { request .tool_call @@ -1003,7 +1170,7 @@ mod tests { ExtensionInfo::new("memory", "", true), ]; - let parts = extension_prompt_parts(&extensions); + let parts = extension_prompt_parts(&extensions, false); let keys: Vec<&str> = parts.iter().map(|(key, _)| key.as_str()).collect(); assert_eq!( diff --git a/crates/goose/src/agents/state_machine/tests/pipeline.rs b/crates/goose/src/agents/state_machine/tests/pipeline.rs index b0cc43e46..8b961d456 100644 --- a/crates/goose/src/agents/state_machine/tests/pipeline.rs +++ b/crates/goose/src/agents/state_machine/tests/pipeline.rs @@ -270,6 +270,18 @@ impl TestPipeline { self } + pub(super) fn with_always_load_tools(mut self, tools: Vec) -> Self { + assert!(!self.services.initialized()); + self.turn_settings.always_load_tools = tools; + self + } + + pub(super) fn with_deferred_tools(mut self) -> Self { + assert!(!self.services.initialized()); + self.turn_settings.defer_tools = true; + self + } + pub(super) fn with_max_turns(mut self, max_turns: u32) -> Self { self.max_turns = max_turns; self @@ -911,6 +923,8 @@ async fn build_test_pipeline( on_failure_timeout: std::time::Duration::from_secs(1), stop_hook_block_cap: 3, tool_pair_summarization: true, + defer_tools: false, + always_load_tools: Vec::new(), compaction_threshold: COMPACTION_THRESHOLD, compaction_token_limit: usize::MAX, tool_call_cutoff: None, diff --git a/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs b/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs index 683f1a4cc..c19616c08 100644 --- a/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs +++ b/crates/goose/src/agents/state_machine/tests/tool_lifecycle.rs @@ -166,6 +166,61 @@ async fn basic_tool_calling() -> Result<()> { Ok(()) } +#[tokio::test] +async fn configured_tools_remain_eager_with_deferral() -> Result<()> { + let (pipeline, api) = test_pipeline().await?; + let pipeline = pipeline + .with_deferred_tools() + .with_always_load_tools(vec![ADD.to_string(), APP_ONLY.to_string()]); + api.on("add one").call(ADD, value(1)); + api.on("result: 1").reply("done"); + pipeline.run(["add one"]).await?; + let calls = api.calls(); + assert!(calls[0].advertises_tool(ADD)); + assert!(!calls[0].advertises_tool(DIVIDE)); + assert!(!calls[0].advertises_tool(APP_ONLY)); + assert!(!calls[0].system_contains(&format!("{ADD},"))); + assert!(calls[0].system_contains(DIVIDE)); + Ok(()) +} + +#[tokio::test] +async fn deferred_tools_follow_the_conversation_lifecycle() -> Result<()> { + let (pipeline, api) = test_pipeline().await?; + let pipeline = pipeline.with_deferred_tools(); + api.on("add one") + .call("enable_tools", json!({"tool_names": [ADD]})) + .times(1); + api.on(r#""enabled":["calculator__add"]"#) + .call(ADD, value(1)); + api.on("result: 1").reply("one"); + let result = pipeline.run(["add one"]).await?; + assert!(!api.calls()[0].advertises_tool(ADD)); + assert!(api.calls()[0].system_contains(ADD)); + result.assert_message(-1, Agent, "one"); + + let pipeline = pipeline.reconstruct().await?; + api.on("Please summarize the conversation history") + .reply("summary"); + pipeline.run(["/compact"]).await?; + api.on("add two").call(ADD, value(2)); + api.on("result: 3").reply("three"); + pipeline + .run(["add two"]) + .await? + .assert_message(-1, Agent, "three"); + assert!(!api.calls().last().unwrap().input_contains(r#""enabled""#)); + + pipeline.run(["/clear"]).await?; + api.on("add again").unadvertised_call(ADD, value(1)); + api.on("not available").reply("enable it again"); + pipeline + .run(["add again"]) + .await? + .assert_message(-2, ToolResponse, "not available"); + Ok(()) +} + #[tokio::test] async fn provider_turn_executes_only_advertised_registered_tools() -> Result<()> { let (pipeline, api) = test_pipeline().await?; diff --git a/crates/goose/src/agents/state_machine_builder.rs b/crates/goose/src/agents/state_machine_builder.rs index 95a213484..cea3a9821 100644 --- a/crates/goose/src/agents/state_machine_builder.rs +++ b/crates/goose/src/agents/state_machine_builder.rs @@ -36,6 +36,8 @@ pub(crate) struct StateMachineConfig<'a> { pub(crate) compaction_threshold: f64, pub(crate) tool_call_cutoff: usize, pub(crate) tool_pair_summarization: bool, + pub(crate) defer_tools: bool, + pub(crate) always_load_tools: Vec, pub(crate) session_manager: Arc, pub(crate) extension_manager: Arc, pub(crate) extension_lease: Arc>>>, @@ -99,6 +101,8 @@ pub(crate) fn build_state_machine( compaction_threshold, tool_call_cutoff, tool_pair_summarization, + defer_tools, + always_load_tools, session_manager, extension_manager, extension_lease, @@ -142,6 +146,8 @@ pub(crate) fn build_state_machine( hook_manager.clone(), Arc::clone(&post_tool_call_hook), Arc::clone(&extension_lease), + defer_tools, + always_load_tools, )), Arc::new(RemainingToolCallsOperation::new( hook_manager.clone(), diff --git a/documentation/docs/guides/config-files.md b/documentation/docs/guides/config-files.md index 1236bd0e6..38227d07f 100644 --- a/documentation/docs/guides/config-files.md +++ b/documentation/docs/guides/config-files.md @@ -51,6 +51,8 @@ The following settings can be configured at the root level of your config.yaml f | `GOOSE_CACHE_TTL` | Anthropic prompt-cache TTL; `1h` keeps the cached prefix alive across idle gaps at a higher cache-write rate. Headless runs always use `5m` | "5m", "1h" | "5m" | No | | `GOOSE_MODE` | [Tool execution behavior](/docs/guides/managing-tools/goose-permissions) | "auto", "approve", "chat", "smart_approve" | "auto" | No | | `GOOSE_MAX_TURNS` | [Maximum number of turns](/docs/guides/sessions/smart-context-management#maximum-turns) allowed without user input | Integer (e.g., 10, 50, 100) | 1000 | No | +| `GOOSE_TOOL_DEFERRAL` | Publish MCP tool names up front; enable schemas on demand with `enable_tools` | "lookup" | Disabled when unset | No | +| `GOOSE_TOOL_DEFERRAL_ALWAYS_LOAD` | Comma-separated exact model-visible tool names to keep eager when deferral is enabled | String (e.g., "serverA__toolA,serverB__toolC") | Empty | No | | `GOOSE_TOOLSHIM` | Enable tool interpretation | true/false | false | No | | `GOOSE_TOOLSHIM_OLLAMA_MODEL` | Model for tool interpretation | Model name (e.g., "llama3.2") | System default | No | | `GOOSE_INPUT_LIMIT` | Override input token limit for Ollama (maps to `num_ctx`) | Positive integer | Model default | No | @@ -74,6 +76,8 @@ The following settings can be configured at the root level of your config.yaml f Additional [environment variables](/docs/guides/environment-variables) may also be supported in config.yaml. +With `GOOSE_TOOL_DEFERRAL: lookup`, the model calls `enable_tools` to load MCP tool schemas on demand; platform tools remain available immediately. `GOOSE_TOOL_DEFERRAL_ALWAYS_LOAD` keeps selected tools eager using their exact model-visible names, including extension prefixes. Whitespace around comma-separated entries is ignored. This list has no effect unless deferral is enabled and does not override availability, visibility, or permissions. + ## Example Configuration Here's a basic example of a config.yaml file: