Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: remove unused strict transformers in tool schema generation (#4289)

Eric Hayes06e3c13562de
diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rs
index f8af474707..14635e469c 100644
--- a/rust/cloud-storage/ai_tools/src/lib.rs
+++ b/rust/cloud-storage/ai_tools/src/lib.rs
@@ -2,6 +2,10 @@
use ai_toolset::AsyncToolCollection;
use ai_toolset::schema::{FrontendSchemas, ToolSchemaGenerator, frontend_schemas_builder};
+
+#[cfg(test)]
+mod test;
+
mod build_context;
mod display_results;
mod schemas;
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
index 4ba4619005..20d54902d0 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs
@@ -88,27 +88,3 @@ impl AsyncTool<SearchToolContext> for ContentSearch {
Ok(SearchToolResponse { results })
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ai_toolset::schema::generate_validated_input_schema;
-
- #[test]
- fn test_content_search_schema_validation() {
- let result = generate_validated_input_schema::<ContentSearch>();
- assert!(result.is_ok(), "{:?}", result);
-
- let validated = result.unwrap();
- assert_eq!(
- validated.name, "ContentSearch",
- "Tool name should match the schemars title"
- );
- assert!(
- validated
- .description
- .contains("Search items by their content"),
- "Description should contain expected text"
- );
- }
-}
diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
index 4028aeab9a..f3e8cc0049 100644
--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs
@@ -88,25 +88,3 @@ impl AsyncTool<SearchToolContext> for NameSearch {
Ok(SearchToolResponse { results })
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use ai_toolset::schema::generate_validated_input_schema;
-
- #[test]
- fn test_name_search_schema_validation() {
- let result = generate_validated_input_schema::<NameSearch>();
- assert!(result.is_ok(), "{:?}", result);
-
- let validated = result.unwrap();
- assert_eq!(
- validated.name, "NameSearch",
- "Tool name should match the schemars title"
- );
- assert!(
- validated.description.contains("Search items by their name"),
- "Description should contain expected text"
- );
- }
-}
diff --git a/rust/cloud-storage/ai_tools/src/test.rs b/rust/cloud-storage/ai_tools/src/test.rs
new file mode 100644
index 0000000000..f0849d217d
--- /dev/null
+++ b/rust/cloud-storage/ai_tools/src/test.rs
@@ -0,0 +1,45 @@
+//! Toolset construction tests.
+//!
+//! Adding a tool to a toolset runs its input schema through
+//! `generate_validated_input_schema` (via `AsyncToolObject::try_from_tool`),
+//! which enforces the strict-mode requirements shared by OpenAI and
+//! Anthropic. On a validation failure that path `.expect()`-panics, so a tool
+//! with an unsupported schema (e.g. a `HashMap` that emits
+//! `additionalProperties`) used to surface only at runtime when the service
+//! built its toolset.
+//!
+//! These tests build every toolset the crate exposes. If any tool fails
+//! schema validation, construction panics and the corresponding test fails —
+//! turning that runtime failure into a test-time failure.
+
+use super::*;
+
+#[test]
+fn subagent_toolset_passes_schema_validation() {
+ let _ = subagent_toolset();
+}
+
+#[test]
+fn all_tools_passes_schema_validation() {
+ let _ = all_tools();
+}
+
+#[test]
+fn mcp_tools_passes_schema_validation() {
+ let _ = mcp_tools();
+}
+
+#[test]
+fn no_tools_passes_schema_validation() {
+ let _ = no_tools();
+}
+
+#[test]
+fn search_toolset_passes_schema_validation() {
+ let _ = search_toolset();
+}
+
+#[test]
+fn frontend_schemas_build() {
+ let _ = all_tool_frontend_schemas();
+}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
index ad8cacfb92..f88fd51f1a 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/generate.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs
@@ -10,10 +10,7 @@ mod test;
use crate::schema::error::ValidationError;
use crate::schema::frontend_typegen::FrontendSchemasBuilder;
-use crate::schema::transform::{
- AddRequired, AdditionalPropertiesFalse, NormaliseRefSiblings, NullifyOptional, OneOfToAnyOf,
- StripUnsupported,
-};
+use crate::schema::transform::{NormaliseRefSiblings, OneOfToAnyOf, StripUnsupported};
use crate::schema::validate::validate_tool_schema;
use schemars::Schema;
use schemars::generate::SchemaSettings;
@@ -62,9 +59,6 @@ pub fn generate_validated_input_schema<T: schemars::JsonSchema>()
})
.with_transform(RecursiveTransform(OneOfToAnyOf))
.with_transform(RecursiveTransform(StripUnsupported))
- .with_transform(RecursiveTransform(NullifyOptional))
- .with_transform(RecursiveTransform(AddRequired))
- .with_transform(RecursiveTransform(AdditionalPropertiesFalse))
.into_generator()
.into_root_schema_for::<T>();
let (name, description) = validate_tool_schema(&schema)?;
diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate/test.rs b/rust/cloud-storage/ai_toolset/src/schema/generate/test.rs
index cba8fd81bc..afc35a049a 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/generate/test.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/generate/test.rs
@@ -2,7 +2,6 @@ use super::*;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
-use std::collections::HashMap;
// Test struct with valid schema (should pass)
#[derive(Debug, JsonSchema, Deserialize, Clone)]
@@ -64,47 +63,6 @@ struct Constrained {
pub id: String,
}
-#[derive(Debug, JsonSchema, Deserialize, Clone)]
-#[schemars(description = "Schema with a map field", title = "WithMap")]
-#[allow(dead_code)]
-struct WithMap {
- pub map_field: HashMap<String, String>,
-}
-
-#[derive(Debug, JsonSchema, Deserialize, Clone, Default)]
-#[allow(dead_code)]
-enum PlainEnum {
- #[default]
- Red,
- Blue,
-}
-
-// Fields that are optional without being Option (serde defaults): strict
-// mode requires them to become required + nullable.
-#[derive(Debug, JsonSchema, Deserialize, Clone)]
-#[schemars(
- description = "Schema with serde-default fields",
- title = "WithDefaults"
-)]
-#[allow(dead_code)]
-struct WithDefaults {
- pub always: String,
-
- #[serde(default)]
- #[schemars(description = "An optional counter")]
- pub count: u32,
-
- #[serde(default)]
- pub color: PlainEnum,
-}
-
-#[derive(Debug, JsonSchema, Deserialize, Clone)]
-#[schemars(description = "A recursive schema", title = "Recursive")]
-#[allow(dead_code)]
-struct Recursive {
- pub children: Vec<Recursive>,
-}
-
fn schema_json(schema: &Schema) -> Value {
serde_json::to_value(schema).expect("schema serializes")
}
@@ -130,41 +88,6 @@ fn test_validate_tool_schema_passes() {
);
}
-#[test]
-fn test_optional_fields_are_required_and_nullable() {
- let validated = generate_validated_input_schema::<ValidTestSchema>().unwrap();
- let json = schema_json(&validated.schema);
-
- // OpenAI strict mode: every property must be in `required`; optional
- // fields are expressed as nullable unions instead.
- let required: Vec<&str> = json["required"]
- .as_array()
- .unwrap()
- .iter()
- .map(|v| v.as_str().unwrap())
- .collect();
- for field in ["simple_field", "list_field", "flag_field", "number_field"] {
- assert!(required.contains(&field), "{field} must be required");
- }
- let types = property(&json, "simple_field")["type"].as_array().unwrap();
- assert!(types.contains(&Value::String("null".into())), "{types:?}");
-}
-
-#[test]
-fn test_additional_properties_only_on_objects() {
- let validated = generate_validated_input_schema::<ValidTestSchema>().unwrap();
- let json = schema_json(&validated.schema);
-
- assert_eq!(json["additionalProperties"], Value::Bool(false));
- // Scalars and arrays must not carry the keyword.
- for field in ["simple_field", "list_field", "flag_field", "number_field"] {
- assert!(
- property(&json, field).get("additionalProperties").is_none(),
- "{field} should not have additionalProperties"
- );
- }
-}
-
#[test]
fn test_enum_doc_comments_rewritten_to_any_of() {
let result = generate_validated_input_schema::<DocumentedEnumSchema>();
@@ -209,56 +132,3 @@ fn test_unsupported_constraints_stripped_into_description() {
// `uuid` is on both providers' format whitelist and survives.
assert_eq!(property(&json, "id")["format"], "uuid");
}
-
-#[test]
-fn test_serde_default_fields_become_required_and_nullable() {
- let validated = generate_validated_input_schema::<WithDefaults>().unwrap();
- let json = schema_json(&validated.schema);
-
- let required: Vec<&str> = json["required"]
- .as_array()
- .unwrap()
- .iter()
- .map(|v| v.as_str().unwrap())
- .collect();
- for field in ["always", "count", "color"] {
- assert!(required.contains(&field), "{field} must be required");
- }
-
- // An already-required field keeps its plain type.
- assert_eq!(property(&json, "always")["type"], "string");
-
- // A promoted scalar becomes a null union.
- let count_types = property(&json, "count")["type"].as_array().unwrap();
- assert!(count_types.contains(&Value::String("integer".into())));
- assert!(count_types.contains(&Value::String("null".into())));
-
- // A promoted enum admits null in both `type` and `enum`.
- let color = property(&json, "color");
- let color_types = color["type"].as_array().unwrap();
- assert!(
- color_types.contains(&Value::String("null".into())),
- "{color:?}"
- );
- let values = color["enum"].as_array().unwrap();
- assert!(values.contains(&Value::Null), "{values:?}");
- assert!(values.contains(&Value::String("Red".into())));
-}
-
-#[test]
-fn test_map_types_fail_validation() {
- let result = generate_validated_input_schema::<WithMap>();
- assert!(
- matches!(result, Err(ValidationError::AdditionalProperties)),
- "map types cannot be expressed in strict mode: {result:?}"
- );
-}
-
-#[test]
-fn test_recursive_types_fail_validation() {
- let result = generate_validated_input_schema::<Recursive>();
- assert!(
- matches!(result, Err(ValidationError::UnsupportedRef)),
- "recursive types cannot be inlined: {result:?}"
- );
-}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/transform/additional_properties.rs b/rust/cloud-storage/ai_toolset/src/schema/transform/additional_properties.rs
index a16083eb2e..8b13789179 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/transform/additional_properties.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/transform/additional_properties.rs
@@ -1,40 +1 @@
-use schemars::Schema;
-use schemars::transform::Transform;
-use serde_json::Value;
-/// Sets `additionalProperties: false` on every object schema, as required by
-/// both OpenAI and Anthropic strict mode.
-///
-/// Only applies to object-typed schemas — strict validators reject (or are
-/// confused by) the keyword on scalars and arrays. An existing
-/// `additionalProperties` value is left untouched: schemars emits a value
-/// *schema* there for map types (`HashMap<String, T>`), which strict mode
-/// cannot express — overwriting it would silently change the tool's
-/// contract, so it is left for [`ValidateAdditionalProperties`] to reject.
-///
-/// [`ValidateAdditionalProperties`]: crate::schema::validate::ValidateAdditionalProperties
-#[derive(Debug, Clone)]
-pub struct AdditionalPropertiesFalse;
-
-pub(crate) fn is_object_schema(obj: &serde_json::Map<String, Value>) -> bool {
- let type_is_object = match obj.get("type") {
- Some(Value::String(t)) => t == "object",
- Some(Value::Array(types)) => types.iter().any(|t| t == "object"),
- _ => false,
- };
- type_is_object || obj.contains_key("properties")
-}
-
-impl Transform for AdditionalPropertiesFalse {
- fn transform(&mut self, schema: &mut Schema) {
- let Some(obj) = schema.as_object_mut() else {
- return;
- };
- if !is_object_schema(obj) {
- return;
- }
- if !obj.contains_key("additionalProperties") {
- obj.insert("additionalProperties".to_string(), false.into());
- }
- }
-}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/transform/mod.rs b/rust/cloud-storage/ai_toolset/src/schema/transform/mod.rs
index 20720a7d30..ebd77ec9de 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/transform/mod.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/transform/mod.rs
@@ -7,17 +7,10 @@
//! [`RecursiveTransform`](schemars::transform::RecursiveTransform); read-only
//! checks belong in the `validate` module instead.
-mod additional_properties;
-mod nullify_optional;
mod ref_siblings;
-mod required;
mod rewrite_one_of;
mod strip_unsupported;
-pub use additional_properties::AdditionalPropertiesFalse;
-pub(crate) use additional_properties::is_object_schema;
-pub use nullify_optional::NullifyOptional;
pub use ref_siblings::NormaliseRefSiblings;
-pub use required::AddRequired;
pub use rewrite_one_of::OneOfToAnyOf;
pub use strip_unsupported::StripUnsupported;
diff --git a/rust/cloud-storage/ai_toolset/src/schema/transform/nullify_optional.rs b/rust/cloud-storage/ai_toolset/src/schema/transform/nullify_optional.rs
deleted file mode 100644
index 977eada860..0000000000
--- a/rust/cloud-storage/ai_toolset/src/schema/transform/nullify_optional.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-use schemars::Schema;
-use schemars::transform::Transform;
-use serde_json::{Map, Value, json};
-
-/// Rewrites optional properties (not listed in `required`) to accept `null`.
-///
-/// OpenAI strict mode forbids optional properties — optionality must be
-/// expressed as a union with `null`. This transform makes that rewrite;
-/// [`AddRequired`](super::AddRequired) then marks everything required, and
-/// must run **after** this transform since it overwrites the `required`
-/// array this one reads. `Option<T>` fields are already nullable and pass
-/// through unchanged; this catches properties that are optional any other
-/// way (e.g. `#[serde(default)]` fields).
-#[derive(Debug, Clone)]
-pub struct NullifyOptional;
-
-impl Transform for NullifyOptional {
- fn transform(&mut self, schema: &mut Schema) {
- let Some(obj) = schema.as_object_mut() else {
- return;
- };
-
- let required: Vec<String> = obj
- .get("required")
- .and_then(Value::as_array)
- .map(|names| {
- names
- .iter()
- .filter_map(Value::as_str)
- .map(str::to_owned)
- .collect()
- })
- .unwrap_or_default();
-
- let Some(properties) = obj.get_mut("properties").and_then(Value::as_object_mut) else {
- return;
- };
- for (name, property) in properties.iter_mut() {
- if !required.iter().any(|r| r == name) {
- make_nullable(property);
- }
- }
- }
-}
-
-fn has_null_type(obj: &Map<String, Value>) -> bool {
- match obj.get("type") {
- Some(Value::String(t)) => t == "null",
- Some(Value::Array(types)) => types.iter().any(|t| t == "null"),
- _ => false,
- }
-}
-
-fn make_nullable(property: &mut Value) {
- let Some(obj) = property.as_object_mut() else {
- return;
- };
-
- // Union node: add a null variant unless one exists.
- if let Some(Value::Array(variants)) = obj.get_mut("anyOf") {
- let has_null = variants
- .iter()
- .any(|v| v.as_object().is_some_and(has_null_type));
- if !has_null {
- variants.push(json!({"type": "null"}));
- }
- return;
- }
-
- match obj.get("type").cloned() {
- Some(Value::String(t)) => {
- if t != "null" {
- obj.insert("type".to_string(), json!([t, "null"]));
- }
- }
- Some(Value::Array(mut types)) => {
- if !types.iter().any(|t| t == "null") {
- types.push(json!("null"));
- obj.insert("type".to_string(), Value::Array(types));
- }
- }
- _ => {
- // const / allOf / other shapes that can't carry a type union:
- // wrap the whole node in a null union instead.
- let original = Value::Object(std::mem::take(obj));
- *property = json!({"anyOf": [original, {"type": "null"}]});
- return;
- }
- }
-
- // An enum must also admit null now that the type does.
- if let Some(Value::Array(values)) = obj.get_mut("enum")
- && !values.iter().any(Value::is_null)
- {
- values.push(Value::Null);
- }
-}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/transform/required.rs b/rust/cloud-storage/ai_toolset/src/schema/transform/required.rs
deleted file mode 100644
index 2dda24ccc9..0000000000
--- a/rust/cloud-storage/ai_toolset/src/schema/transform/required.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use schemars::Schema;
-use schemars::transform::Transform;
-use serde_json::Value;
-
-/// Adds all property names to the `required` array, as required by
-/// OpenAI's strict mode.
-///
-/// Must run **after** [`NullifyOptional`](super::NullifyOptional), which
-/// reads the original `required` array to decide which properties need a
-/// null union before this transform overwrites it.
-#[derive(Debug, Clone)]
-pub struct AddRequired;
-
-impl Transform for AddRequired {
- fn transform(&mut self, schema: &mut Schema) {
- let Some(obj) = schema.as_object_mut() else {
- return;
- };
- let Some(properties) = obj.get("properties").and_then(Value::as_object) else {
- return;
- };
- let property_names: Vec<Value> = properties.keys().cloned().map(Value::String).collect();
- obj.insert("required".to_string(), Value::Array(property_names));
- }
-}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/validate/mod.rs b/rust/cloud-storage/ai_toolset/src/schema/validate/mod.rs
index 0cacdfec43..7227e0dbf3 100644
--- a/rust/cloud-storage/ai_toolset/src/schema/validate/mod.rs
+++ b/rust/cloud-storage/ai_toolset/src/schema/validate/mod.rs
@@ -7,7 +7,6 @@
mod extract;
mod one_of;
mod recursive;
-mod strict;
use super::error::ValidationError;
use extract::Extract;
@@ -15,7 +14,6 @@ use schemars::Schema;
pub use one_of::ValidateNoOneOf;
pub use recursive::RecursiveValidate;
-pub use strict::{ValidateAdditionalProperties, ValidateEnumPrimitives, ValidateNoRefs};
/// A validating visitor similar to [`Transform`](schemars::transform::Transform)
///
@@ -50,9 +48,6 @@ pub fn validate_tool_schema(schema: &Schema) -> Result<(String, String), Validat
}
RecursiveValidate(ValidateNoOneOf).validate(schema)?;
- RecursiveValidate(ValidateNoRefs).validate(schema)?;
- RecursiveValidate(ValidateAdditionalProperties).validate(schema)?;
- RecursiveValidate(ValidateEnumPrimitives).validate(schema)?;
Ok((name, description))
}
diff --git a/rust/cloud-storage/ai_toolset/src/schema/validate/strict.rs b/rust/cloud-storage/ai_toolset/src/schema/validate/strict.rs
deleted file mode 100644
index 3f161a3626..0000000000
--- a/rust/cloud-storage/ai_toolset/src/schema/validate/strict.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-use super::Validate;
-use crate::schema::error::ValidationError;
-use crate::schema::transform::is_object_schema;
-use schemars::Schema;
-use serde_json::Value;
-
-/// Rejects schemas containing `$ref` / `$defs` / `definitions`.
-///
-/// The AI input pipeline inlines all subschemas, so any surviving `$ref`
-/// means the type is recursive (schemars falls back to `"$ref": "#"`) —
-/// Anthropic strict mode rejects recursive schemas, and there is no
-/// transform that can fix this.
-pub struct ValidateNoRefs;
-
-impl Validate for ValidateNoRefs {
- fn validate(&self, schema: &Schema) -> Result<(), ValidationError> {
- if let Some(obj) = schema.as_object()
- && (obj.contains_key("$ref")
- || obj.contains_key("$defs")
- || obj.contains_key("definitions"))
- {
- return Err(ValidationError::UnsupportedRef);
- }
- Ok(())
- }
-}
-
-/// Rejects object schemas whose `additionalProperties` is anything but
-/// `false`.
-///
-/// schemars emits a value schema there for map types
-/// (`HashMap<String, T>`); strict mode on both providers requires
-/// `additionalProperties: false`, so map-typed tool inputs cannot be
-/// expressed — use a `Vec` of key/value structs instead.
-pub struct ValidateAdditionalProperties;
-
-impl Validate for ValidateAdditionalProperties {
- fn validate(&self, schema: &Schema) -> Result<(), ValidationError> {
- let Some(obj) = schema.as_object() else {
- return Ok(());
- };
- if !is_object_schema(obj) {
- return Ok(());
- }
- match obj.get("additionalProperties") {
- Some(Value::Bool(false)) => Ok(()),
- _ => Err(ValidationError::AdditionalProperties),
- }
- }
-}
-
-/// Rejects `enum` arrays containing non-primitive values.
-///
-/// Both providers restrict enum members to strings, numbers, booleans, and
-/// nulls.
-pub struct ValidateEnumPrimitives;
-
-impl Validate for ValidateEnumPrimitives {
- fn validate(&self, schema: &Schema) -> Result<(), ValidationError> {
- if let Some(values) = schema.get("enum").and_then(Value::as_array)
- && values
- .iter()
- .any(|v| matches!(v, Value::Object(_) | Value::Array(_)))
- {
- return Err(ValidationError::ComplexEnum);
- }
- Ok(())
- }
-}