fix: sanitize provider tool names

This commit is contained in:
zyl
2026-03-30 03:11:43 +08:00
parent 5db25b513e
commit dbb18a094c
5 changed files with 182 additions and 15 deletions

View File

@@ -204,7 +204,7 @@ pub use text_browser::TextBrowserTool;
pub use tool_search::ToolSearchTool;
pub use traits::Tool;
#[allow(unused_imports)]
pub use traits::{ToolResult, ToolSpec};
pub use traits::{provider_safe_tool_name, ToolResult, ToolSpec};
pub use verifiable_intent::VerifiableIntentTool;
pub use weather_tool::WeatherTool;
pub use web_fetch::WebFetchTool;

View File

@@ -17,6 +17,18 @@ pub struct ToolSpec {
pub parameters: serde_json::Value,
}
pub fn provider_safe_tool_name(name: &str) -> String {
name.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
ch
} else {
'_'
}
})
.collect()
}
/// Core tool trait — implement for any capability
#[async_trait]
pub trait Tool: Send + Sync {
@@ -118,4 +130,13 @@ mod tests {
assert!(!parsed.success);
assert_eq!(parsed.error.as_deref(), Some("boom"));
}
#[test]
fn provider_safe_tool_name_replaces_invalid_function_characters() {
assert_eq!(
provider_safe_tool_name("zhihu-hotlist.extract_hotlist"),
"zhihu-hotlist_extract_hotlist"
);
assert_eq!(provider_safe_tool_name("shell"), "shell");
}
}