use crate::test_utils::{MockObjectOutputTool, MockToolError, mock_math_toolset};
use portable_fixtures::{PortableEmbeddingFixture, portable_fixture_output};
use rig_core::embeddings::tool::ToolSchema;
use serde_json::json;
use super::*;
mod portable_fixtures {
use rig_core::{
message::{ImageMediaType, ToolResultContent},
tool::{Tool, ToolContext, ToolEmbedding, ToolExecutionError, ToolOutput},
};
use serde::{Deserialize, Serialize};
const PORTABLE_FIXTURE_IMAGE: &str = "cG9ydGFibGUtZml4dHVyZQ==";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PortableEmbeddingArgs {
pub value: String,
#[serde(default)]
pub fail: bool,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PortableEmbeddingContext {
pub prefix: String,
}
#[derive(Debug, thiserror::Error)]
#[error("portable fixture failure")]
pub struct PortableFixtureError;
pub fn portable_fixture_output(label: impl Into<String>) -> ToolOutput {
let mut content = vec![ToolResultContent::json(
serde_json::json!({"label": label.into()}),
)];
content.push(ToolResultContent::image_base64(
PORTABLE_FIXTURE_IMAGE,
Some(ImageMediaType::PNG),
None,
));
ToolOutput::content(content).expect("fixture content is non-empty")
}
#[derive(Clone)]
pub struct PortableEmbeddingFixture {
context: PortableEmbeddingContext,
}
impl PortableEmbeddingFixture {
pub fn new(prefix: impl Into<String>) -> Self {
Self {
context: PortableEmbeddingContext {
prefix: prefix.into(),
},
}
}
}
impl Tool for PortableEmbeddingFixture {
const NAME: &'static str = "portable_embedding_fixture";
type Args = PortableEmbeddingArgs;
type Output = ToolOutput;
type Error = PortableFixtureError;
fn description(&self) -> String {
format!("{} portable embedding fixture", self.context.prefix)
}
fn parameters(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"value": {"type": "string"},
"fail": {"type": "boolean"}
},
"required": ["value"]
})
}
fn map_error(&self, error: Self::Error) -> ToolExecutionError {
ToolExecutionError::provider(error.to_string())
.with_code("portable_fixture")
.with_model_output(portable_fixture_output("portable failure"))
.with_source(error)
}
async fn call(
&self,
_: &mut ToolContext,
arguments: Self::Args,
) -> Result<Self::Output, Self::Error> {
if arguments.fail {
Err(PortableFixtureError)
} else {
Ok(portable_fixture_output(format!(
"{}:{}",
self.context.prefix, arguments.value
)))
}
}
}
impl ToolEmbedding for PortableEmbeddingFixture {
type InitError = std::convert::Infallible;
type Context = PortableEmbeddingContext;
type State = ();
fn embedding_docs(&self) -> Vec<String> {
vec![format!(
"{} portable embedding document",
self.context.prefix
)]
}
fn context(&self) -> Self::Context {
self.context.clone()
}
fn init(_state: Self::State, context: Self::Context) -> Result<Self, Self::InitError> {
Ok(Self { context })
}
}
}
fn get_test_toolset() -> ToolSet {
mock_math_toolset()
}
#[test]
fn test_tool_deletion() {
let mut toolset = get_test_toolset();
assert_eq!(toolset.len(), 2);
toolset.remove_tool("add");
assert!(!toolset.contains("add"));
assert_eq!(toolset.len(), 1);
assert_eq!(
toolset.names().map(str::to_owned).collect::<Vec<_>>(),
vec!["subtract".to_string()]
);
}
#[test]
fn deleting_a_middle_tool_preserves_order_of_survivors() {
let mut toolset = ToolSet::default();
for name in ["alpha", "beta", "gamma", "delta"] {
toolset.add_dynamic_tool(named_tool(name, "test tool"));
}
toolset.remove_tool("beta");
assert_eq!(
toolset.names().map(str::to_owned).collect::<Vec<_>>(),
vec![
"alpha".to_string(),
"gamma".to_string(),
"delta".to_string()
],
"survivors must keep their registration order after a middle deletion"
);
}
fn named_tool(name: &str, description: &str) -> DynamicTool {
let output = format!("called {description}");
DynamicTool::new(
rig_core::message::ToolName::new(name).expect("tool name"),
description,
json!({ "type": "object", "properties": {} }),
move |_args| {
let output = output.clone();
Box::pin(async move { Ok(ToolOutput::text(output)) })
},
)
}
#[tokio::test]
async fn tool_definitions_follow_registration_order() {
let names: Vec<String> = (0..32).map(|i| format!("tool_{i:02}")).collect();
let mut toolset = ToolSet::default();
for name in &names {
toolset.add_dynamic_tool(named_tool(name, "test tool"));
}
let defs = toolset.tool_definitions();
let def_names: Vec<String> = defs.iter().map(|def| def.name.to_string()).collect();
assert_eq!(def_names, names);
}
#[test]
fn retrieved_tool_schemas_use_canonical_name() {
#[derive(Debug, thiserror::Error)]
#[error("init error")]
struct InitError;
struct RetrievedTool;
impl Tool for RetrievedTool {
const NAME: &'static str = "retrieved";
type Error = rig::tool::ToolExecutionError;
type Args = serde_json::Value;
type Output = String;
fn description(&self) -> String {
"dynamic tool".to_string()
}
fn parameters(&self) -> serde_json::Value {
json!({ "type": "object", "properties": {} })
}
async fn call(
&self,
_context: &mut ToolContext,
_args: Self::Args,
) -> Result<Self::Output, ToolExecutionError> {
Ok("ok".to_string())
}
}
impl ToolEmbedding for RetrievedTool {
type InitError = InitError;
type Context = ();
type State = ();
fn embedding_docs(&self) -> Vec<String> {
vec!["dynamic tool docs".to_string()]
}
fn context(&self) -> Self::Context {}
fn init(_state: Self::State, _context: Self::Context) -> Result<Self, Self::InitError> {
Ok(Self)
}
}
let mut toolset = ToolSet::default();
toolset
.add_retrieved_tool(RetrievedTool)
.expect("the tool context serializes");
let schemas = toolset.schemas().unwrap();
assert_eq!(schemas.len(), 1);
assert_eq!(schemas[0].name, RetrievedTool::NAME);
assert_eq!(schemas[0].embedding_docs, vec!["dynamic tool docs"]);
}
#[tokio::test]
async fn portable_embedding_tool_uses_classic_retrieval_without_schema_drift() {
let tool = PortableEmbeddingFixture::new("shared");
let portable_schema = ToolSchema {
name: PortableEmbeddingFixture::NAME.to_string(),
context: serde_json::to_value(tool.context()).unwrap(),
embedding_docs: tool.embedding_docs(),
};
let mut toolset = ToolSet::default();
toolset
.add_retrieved_tool(tool)
.expect("the tool context serializes");
let schemas = toolset.schemas().unwrap();
assert_eq!(schemas.len(), 1);
assert_eq!(schemas[0].name, portable_schema.name);
assert_eq!(schemas[0].context, portable_schema.context);
assert_eq!(schemas[0].embedding_docs, portable_schema.embedding_docs);
let handle = server::ToolServer::new()
.retrieved_tools(
1,
crate::test_utils::MockToolIndex::new([portable_schema.name.as_str()]),
toolset,
)
.run();
let definitions = handle
.tool_defs(Some("find the shared portable tool".to_string()))
.await
.unwrap();
assert_eq!(definitions.len(), 1);
assert_eq!(definitions[0].name, portable_schema.name);
assert_eq!(
definitions[0].description,
"shared portable embedding fixture"
);
assert_eq!(
definitions[0].parameters,
serde_json::json!({
"type": "object",
"properties": {
"value": {"type": "string"},
"fail": {"type": "boolean"}
},
"required": ["value"]
})
);
let success = handle
.toolset()
.execute(
&definitions[0].name,
r#"{"value":"ok"}"#,
&mut ToolContext::new(),
)
.await;
assert!(success.is_success());
assert_eq!(success.output(), &portable_fixture_output("shared:ok"));
let failure = handle
.toolset()
.execute(
&definitions[0].name,
r#"{"value":"ignored","fail":true}"#,
&mut ToolContext::new(),
)
.await;
let error = failure
.error()
.expect("portable failure should be retained");
assert_eq!(error.kind(), ToolErrorKind::Provider);
assert_eq!(error.code(), Some("portable_fixture"));
assert_eq!(
error.model_output(),
&portable_fixture_output("portable failure")
);
assert_eq!(failure.output(), error.model_output());
}
#[tokio::test]
async fn add_tools_merges_in_order_and_replaces_existing() {
let mut base = ToolSet::default();
base.add_dynamic_tool(named_tool("alpha", "base alpha"));
base.add_dynamic_tool(named_tool("beta", "base beta"));
let mut incoming = ToolSet::default();
incoming.add_dynamic_tool(named_tool("gamma", "incoming gamma"));
incoming.add_dynamic_tool(named_tool("alpha", "incoming alpha"));
base.add_tools(incoming);
let defs = base.tool_definitions();
assert_eq!(
defs.iter().map(|def| def.name.as_str()).collect::<Vec<_>>(),
vec!["alpha", "beta", "gamma"],
"merged tools should follow registration order with replaced names keeping position"
);
assert_eq!(defs[0].description, "incoming alpha");
}
#[tokio::test]
async fn json_shaped_string_output_stays_literal_text_through_dispatch() {
struct JsonShapedStringTool;
impl Tool for JsonShapedStringTool {
const NAME: &'static str = "json_shaped_string";
type Error = rig::tool::ToolExecutionError;
type Args = serde_json::Value;
type Output = String;
fn description(&self) -> String {
"Returns text that happens to look like a rich-content envelope".into()
}
fn parameters(&self) -> serde_json::Value {
json!({"type": "object"})
}
async fn call(
&self,
_context: &mut ToolContext,
_args: Self::Args,
) -> Result<Self::Output, ToolExecutionError> {
Ok(r#"{"type":"image","data":"literal"}"#.to_string())
}
}
let mut toolset = ToolSet::default();
toolset.add_tool(JsonShapedStringTool);
let result = toolset
.execute(JsonShapedStringTool::NAME, "{}", &mut ToolContext::new())
.await;
assert_eq!(
result.output(),
&ToolOutput::text(r#"{"type":"image","data":"literal"}"#)
);
}
#[tokio::test]
async fn object_tool_outputs_still_serialize_as_json() {
let mut toolset = ToolSet::default();
toolset.add_tool(MockObjectOutputTool);
let result = toolset
.execute("object_output", "{}", &mut ToolContext::new())
.await;
assert_eq!(
result.output(),
&ToolOutput::json(json!({
"status": "ok",
"count": 42
}))
);
}
#[tokio::test]
async fn null_args_are_normalized_to_empty_object() {
#[derive(serde::Deserialize, serde::Serialize)]
struct NoRequiredArgs {
label: Option<String>,
}
struct NoArgTool;
impl Tool for NoArgTool {
const NAME: &'static str = "no_arg_tool";
type Error = MockToolError;
type Args = NoRequiredArgs;
type Output = String;
fn description(&self) -> String {
"Tool with no required arguments".to_string()
}
fn parameters(&self) -> serde_json::Value {
json!({"type": "object", "properties": {}})
}
async fn call(
&self,
_context: &mut ToolContext,
args: Self::Args,
) -> Result<Self::Output, Self::Error> {
Ok(args.label.unwrap_or_else(|| "default".to_string()))
}
}
let mut toolset = ToolSet::default();
toolset.add_tool(NoArgTool);
let output = toolset
.execute("no_arg_tool", "null", &mut ToolContext::new())
.await;
assert_eq!(output.output(), &ToolOutput::text("default"));
}