1use std::borrow::Cow;
46
47use adk_core::{SchemaAdapter, schema_utils};
48use serde_json::{Map, Value};
49
50#[derive(Debug)]
76pub struct AnthropicSchemaAdapter;
77
78impl SchemaAdapter for AnthropicSchemaAdapter {
79 fn normalize_schema(&self, mut schema: Value) -> Value {
80 schema_utils::strip_schema_keyword(&mut schema);
81 schema_utils::strip_conditional_keywords(&mut schema);
82 schema_utils::add_implicit_object_type(&mut schema);
83 schema
84 }
85
86 fn normalize_tool_name<'a>(&self, name: &'a str) -> Cow<'a, str> {
87 if name.len() <= 64 {
88 Cow::Borrowed(name)
89 } else {
90 let mut end = 64;
92 while end > 0 && !name.is_char_boundary(end) {
93 end -= 1;
94 }
95 Cow::Owned(name[..end].to_string())
96 }
97 }
98}
99
100pub(super) fn nest_composition(schema: &mut Value) {
110 if !can_nest(schema) {
111 return;
112 }
113 let Some(fields) = schema.as_object_mut() else {
114 return;
115 };
116 let mut composition = Map::new();
117 for keyword in ["oneOf", "anyOf", "allOf"] {
118 if let Some(value) = fields.remove(keyword) {
119 composition.insert(keyword.into(), value);
120 }
121 }
122 if !composition.is_empty() {
123 if let Some(value) = fields.remove("not") {
124 composition.insert("not".into(), value);
125 }
126 fields.insert("not".into(), serde_json::json!({"not": composition}));
127 }
128}
129
130fn can_nest(value: &Value) -> bool {
131 match value {
132 Value::Object(fields) => {
133 !fields.contains_key("unevaluatedProperties")
136 && !fields.contains_key("unevaluatedItems")
137 && ["$ref", "$dynamicRef", "$recursiveRef"].into_iter().all(|keyword| {
138 fields.get(keyword).and_then(Value::as_str).is_none_or(|reference| {
139 reference.starts_with("#/$defs/") || reference.starts_with("#/definitions/")
140 })
141 })
142 && fields.values().all(can_nest)
143 }
144 Value::Array(items) => items.iter().all(can_nest),
145 _ => true,
146 }
147}
148
149const UNSUPPORTED_OUTPUT_KEYWORDS: [&str; 10] = [
151 "minimum",
152 "maximum",
153 "exclusiveMinimum",
154 "exclusiveMaximum",
155 "multipleOf",
156 "minLength",
157 "maxLength",
158 "maxItems",
159 "minProperties",
160 "maxProperties",
161];
162
163pub(super) fn structured_output_schema(schema: &Value) -> Option<Value> {
172 fn close(node: &mut Value) -> bool {
173 match node {
174 Value::Array(items) => items.iter_mut().all(close),
175 Value::Object(fields) => {
176 for keyword in UNSUPPORTED_OUTPUT_KEYWORDS {
177 fields.remove(keyword);
178 }
179 if fields.get("minItems").and_then(Value::as_u64).is_some_and(|min| min > 1) {
180 fields.remove("minItems");
181 }
182 let is_object = fields.contains_key("properties")
183 || fields.get("type").and_then(Value::as_str) == Some("object");
184 if is_object {
185 match fields.get("additionalProperties") {
186 None => {
187 fields.insert("additionalProperties".to_string(), Value::Bool(false));
188 }
189 Some(Value::Bool(false)) => {}
190 Some(_) => return false,
191 }
192 }
193 for (key, value) in fields.iter_mut() {
194 let ok = match key.as_str() {
195 "properties" | "$defs" | "definitions" | "patternProperties" => {
196 value.as_object_mut().is_none_or(|map| map.values_mut().all(close))
197 }
198 "items" | "prefixItems" | "anyOf" | "allOf" | "oneOf" | "not" => {
199 close(value)
200 }
201 _ => true,
202 };
203 if !ok {
204 return false;
205 }
206 }
207 true
208 }
209 _ => true,
210 }
211 }
212 let mut schema = schema.clone();
213 schema_utils::strip_schema_keyword(&mut schema);
214 schema_utils::strip_conditional_keywords(&mut schema);
215 schema_utils::add_implicit_object_type(&mut schema);
216 close(&mut schema).then_some(schema)
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use serde_json::json;
223
224 #[test]
225 fn nests_root_composition() {
226 let adapter = AnthropicSchemaAdapter;
227 for keyword in ["oneOf", "anyOf", "allOf"] {
228 let mut schema = json!({
229 "type":"object",
230 "properties":{"action":{"enum":["read","write"]},"value":{"type":"string"}},
231 "required":["action"],
232 "additionalProperties":false,
233 "not":{"required":["blocked"]}
234 });
235 schema[keyword] = json!([
236 {"type":"object","properties":{"action":{"const":"read"}},"required":["action"]},
237 {"type":"object","properties":{"action":{"const":"write"}},"required":["action","value"]}
238 ]);
239 let mut normalized = adapter.normalize_schema(schema.clone());
240 nest_composition(&mut normalized);
241 assert!(normalized.get(keyword).is_none());
242 assert_eq!(normalized["properties"], schema["properties"]);
243 assert_eq!(normalized["required"], schema["required"]);
244 assert_eq!(normalized["additionalProperties"], false);
245 assert_eq!(normalized["not"]["not"][keyword], schema[keyword]);
246 assert_eq!(normalized["not"]["not"]["not"], schema["not"]);
247 let mut again = normalized.clone();
248 nest_composition(&mut again);
249 assert_eq!(again, normalized);
250 }
251 }
252
253 #[test]
254 fn retains_location_sensitive_composition() {
255 let adapter = AnthropicSchemaAdapter;
256 for constraint in [
257 json!({"unevaluatedProperties":false}),
258 json!({"unevaluatedItems":false}),
259 json!({"$ref":"#/oneOf/0"}),
260 json!({"$dynamicRef":"#node"}),
261 ] {
262 let schema = json!({"type":"object","oneOf":[constraint]});
263 let mut nested = adapter.normalize_schema(schema.clone());
264 nest_composition(&mut nested);
265 assert_eq!(nested, schema);
266 }
267 }
268
269 #[test]
270 fn test_strips_schema_keyword() {
271 let adapter = AnthropicSchemaAdapter;
272 let schema = json!({
273 "$schema": "http://json-schema.org/draft-07/schema#",
274 "type": "object",
275 "properties": { "name": { "type": "string" } }
276 });
277 let result = adapter.normalize_schema(schema);
278 assert!(result.get("$schema").is_none());
279 assert_eq!(result["type"], "object");
280 }
281
282 #[test]
283 fn test_strips_conditional_keywords() {
284 let adapter = AnthropicSchemaAdapter;
285 let schema = json!({
286 "type": "object",
287 "if": { "properties": { "kind": { "const": "a" } } },
288 "then": { "required": ["extra"] },
289 "else": { "required": [] }
290 });
291 let result = adapter.normalize_schema(schema);
292 assert!(result.get("if").is_none());
293 assert!(result.get("then").is_none());
294 assert!(result.get("else").is_none());
295 }
296
297 #[test]
298 fn test_adds_implicit_object_type() {
299 let adapter = AnthropicSchemaAdapter;
300 let schema = json!({
301 "properties": {
302 "name": { "type": "string" }
303 }
304 });
305 let result = adapter.normalize_schema(schema);
306 assert_eq!(result["type"], "object");
307 }
308
309 #[test]
310 fn test_preserves_ref() {
311 let adapter = AnthropicSchemaAdapter;
312 let schema = json!({
313 "type": "object",
314 "$ref": "#/$defs/Address"
315 });
316 let result = adapter.normalize_schema(schema);
317 assert_eq!(result["$ref"], "#/$defs/Address");
318 }
319
320 #[test]
321 fn test_preserves_defs() {
322 let adapter = AnthropicSchemaAdapter;
323 let schema = json!({
324 "type": "object",
325 "$defs": {
326 "Address": {
327 "type": "object",
328 "properties": {
329 "street": { "type": "string" }
330 }
331 }
332 }
333 });
334 let result = adapter.normalize_schema(schema);
335 assert!(result.get("$defs").is_some());
336 assert_eq!(result["$defs"]["Address"]["type"], "object");
337 }
338
339 #[test]
340 fn test_preserves_any_of() {
341 let adapter = AnthropicSchemaAdapter;
342 let schema = json!({
343 "anyOf": [
344 { "type": "string" },
345 { "type": "number" }
346 ]
347 });
348 let result = adapter.normalize_schema(schema);
349 assert!(result.get("anyOf").is_some());
350 assert_eq!(result["anyOf"].as_array().unwrap().len(), 2);
351 }
352
353 #[test]
354 fn test_preserves_one_of() {
355 let adapter = AnthropicSchemaAdapter;
356 let schema = json!({
357 "oneOf": [
358 { "type": "boolean" },
359 { "type": "null" }
360 ]
361 });
362 let result = adapter.normalize_schema(schema);
363 assert!(result.get("oneOf").is_some());
364 assert_eq!(result["oneOf"].as_array().unwrap().len(), 2);
365 }
366
367 #[test]
368 fn test_preserves_all_of() {
369 let adapter = AnthropicSchemaAdapter;
370 let schema = json!({
371 "allOf": [
372 { "type": "object", "properties": { "a": { "type": "string" } } },
373 { "required": ["a"] }
374 ]
375 });
376 let result = adapter.normalize_schema(schema);
377 assert!(result.get("allOf").is_some());
378 assert_eq!(result["allOf"].as_array().unwrap().len(), 2);
379 }
380
381 #[test]
382 fn test_preserves_additional_properties() {
383 let adapter = AnthropicSchemaAdapter;
384 let schema = json!({
385 "type": "object",
386 "properties": { "name": { "type": "string" } },
387 "additionalProperties": false
388 });
389 let result = adapter.normalize_schema(schema);
390 assert_eq!(result["additionalProperties"], false);
391 }
392
393 #[test]
394 fn test_preserves_type_arrays() {
395 let adapter = AnthropicSchemaAdapter;
396 let schema = json!({
397 "type": ["string", "null"]
398 });
399 let result = adapter.normalize_schema(schema);
400 assert_eq!(result["type"], json!(["string", "null"]));
401 }
402
403 #[test]
404 fn test_preserves_const() {
405 let adapter = AnthropicSchemaAdapter;
406 let schema = json!({
407 "type": "string",
408 "const": "fixed_value"
409 });
410 let result = adapter.normalize_schema(schema);
411 assert_eq!(result["const"], "fixed_value");
412 }
413
414 #[test]
415 fn test_preserves_all_format_values() {
416 let adapter = AnthropicSchemaAdapter;
417 let formats = [
418 "date-time",
419 "date",
420 "time",
421 "email",
422 "uri",
423 "uuid",
424 "hostname",
425 "ipv4",
426 "ipv6",
427 "uri-reference",
428 "json-pointer",
429 "regex",
430 "iri",
431 "iri-reference",
432 "uri-template",
433 "int32",
434 "int64",
435 "float",
436 "double",
437 ];
438 for format in formats {
439 let schema = json!({ "type": "string", "format": format });
440 let result = adapter.normalize_schema(schema);
441 assert_eq!(
442 result["format"], format,
443 "format '{format}' should be preserved by Anthropic adapter"
444 );
445 }
446 }
447
448 #[test]
449 fn test_normalize_tool_name_short() {
450 let adapter = AnthropicSchemaAdapter;
451 let name = "get_weather";
452 assert_eq!(adapter.normalize_tool_name(name), Cow::Borrowed("get_weather"));
453 }
454
455 #[test]
456 fn test_normalize_tool_name_exactly_64() {
457 let adapter = AnthropicSchemaAdapter;
458 let name = "a".repeat(64);
459 assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));
460 }
461
462 #[test]
463 fn test_normalize_tool_name_truncates_at_64() {
464 let adapter = AnthropicSchemaAdapter;
465 let name = "a".repeat(100);
466 let result = adapter.normalize_tool_name(&name);
467 assert_eq!(result.len(), 64);
468 assert_eq!(result.as_ref(), "a".repeat(64).as_str());
469 }
470
471 #[test]
472 fn test_normalize_tool_name_multibyte_boundary() {
473 let adapter = AnthropicSchemaAdapter;
474 let name = "🦀".repeat(16);
476 assert_eq!(name.len(), 64);
477 assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));
478
479 let long_name = "🦀".repeat(17);
481 let result = adapter.normalize_tool_name(&long_name);
482 assert_eq!(result.len(), 64);
483 assert_eq!(result.as_ref(), "🦀".repeat(16).as_str());
484 }
485
486 #[test]
487 fn test_normalize_tool_name_truncates_at_char_boundary() {
488 let adapter = AnthropicSchemaAdapter;
489 let name = "é".repeat(32);
491 assert_eq!(name.len(), 64);
492 assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));
493
494 let long_name = "é".repeat(33);
496 let result = adapter.normalize_tool_name(&long_name);
497 assert_eq!(result.len(), 64);
498 assert_eq!(result.as_ref(), "é".repeat(32).as_str());
499 }
500
501 #[test]
502 fn test_empty_schema() {
503 let adapter = AnthropicSchemaAdapter;
504 assert_eq!(adapter.empty_schema(), json!({"type": "object", "properties": {}}));
505 }
506
507 #[test]
508 fn test_idempotent() {
509 let adapter = AnthropicSchemaAdapter;
510 let schema = json!({
511 "$schema": "http://json-schema.org/draft-07/schema#",
512 "properties": {
513 "name": { "type": "string" }
514 },
515 "if": { "const": true },
516 "then": { "required": ["name"] },
517 "anyOf": [{ "type": "string" }],
518 "const": "test",
519 "additionalProperties": false
520 });
521 let first = adapter.normalize_schema(schema);
522 let second = adapter.normalize_schema(first.clone());
523 assert_eq!(first, second);
524 }
525
526 #[test]
527 fn test_nested_conditional_keywords_stripped() {
528 let adapter = AnthropicSchemaAdapter;
529 let schema = json!({
530 "type": "object",
531 "properties": {
532 "nested": {
533 "type": "object",
534 "properties": {
535 "deep": { "type": "string" }
536 },
537 "if": { "properties": { "deep": { "const": "x" } } },
538 "then": { "required": ["deep"] }
539 }
540 }
541 });
542 let result = adapter.normalize_schema(schema);
543 let nested = &result["properties"]["nested"];
544 assert!(nested.get("if").is_none());
545 assert!(nested.get("then").is_none());
546 }
547
548 #[test]
549 fn test_combined_transforms() {
550 let adapter = AnthropicSchemaAdapter;
551 let schema = json!({
552 "$schema": "http://json-schema.org/draft-07/schema#",
553 "properties": {
554 "status": { "type": "string", "const": "active" },
555 "host": { "type": "string", "format": "hostname" }
556 },
557 "$ref": "#/$defs/Base",
558 "$defs": { "Base": { "type": "object" } },
559 "anyOf": [{ "type": "string" }],
560 "oneOf": [{ "type": "number" }],
561 "allOf": [{ "required": ["status"] }],
562 "additionalProperties": { "type": "string" },
563 "if": { "properties": { "status": { "const": "active" } } },
564 "then": { "required": ["host"] }
565 });
566 let result = adapter.normalize_schema(schema);
567
568 assert!(result.get("$schema").is_none());
570 assert!(result.get("if").is_none());
572 assert!(result.get("then").is_none());
573 assert_eq!(result["type"], "object");
575 assert_eq!(result["properties"]["status"]["const"], "active");
577 assert_eq!(result["properties"]["host"]["format"], "hostname");
579 assert_eq!(result["$ref"], "#/$defs/Base");
581 assert!(result.get("$defs").is_some());
582 assert!(result.get("anyOf").is_some());
583 assert!(result.get("oneOf").is_some());
584 assert!(result.get("allOf").is_some());
585 assert!(result.get("additionalProperties").is_some());
586 }
587
588 #[test]
595 fn test_passthrough_preserves_all_schema_features() {
596 let adapter = AnthropicSchemaAdapter;
597
598 let schema = json!({
599 "$schema": "http://json-schema.org/draft-07/schema#",
600 "type": "object",
601 "$defs": { "Foo": { "type": "string" } },
602 "properties": {
603 "ref_field": { "$ref": "#/$defs/Foo" },
604 "nullable": { "type": ["string", "null"] },
605 "status": { "const": "active" },
606 "format_field": { "type": "string", "format": "hostname" }
607 },
608 "anyOf": [{"type": "object"}, {"type": "null"}],
609 "additionalProperties": true,
610 "if": { "properties": { "x": { "type": "number" } } },
611 "then": { "required": ["x"] }
612 });
613
614 let result = adapter.normalize_schema(schema);
615
616 assert_eq!(
618 result["properties"]["ref_field"]["$ref"], "#/$defs/Foo",
619 "$ref must be preserved"
620 );
621 assert_eq!(result["$defs"]["Foo"]["type"], "string", "$defs must be preserved");
622
623 assert_eq!(result["additionalProperties"], true, "additionalProperties must be preserved");
625
626 assert_eq!(
628 result["properties"]["nullable"]["type"],
629 json!(["string", "null"]),
630 "type arrays must be preserved"
631 );
632
633 assert_eq!(
635 result["properties"]["status"]["const"], "active",
636 "const keyword must be preserved"
637 );
638
639 assert_eq!(
641 result["properties"]["format_field"]["format"], "hostname",
642 "all format values must be preserved"
643 );
644
645 let any_of = result["anyOf"].as_array().expect("anyOf must be preserved");
647 assert_eq!(any_of.len(), 2);
648 assert_eq!(any_of[0]["type"], "object");
649 assert_eq!(any_of[1]["type"], "null");
650
651 assert!(result.get("$schema").is_none(), "$schema must be stripped");
653 assert!(result.get("if").is_none(), "if must be stripped");
654 assert!(result.get("then").is_none(), "then must be stripped");
655 assert!(
656 result.get("else").is_none(),
657 "else must be stripped (not present in input but verify absence)"
658 );
659
660 assert_eq!(result["type"], "object");
662 }
663
664 #[test]
668 fn test_passthrough_strips_else_keyword() {
669 let adapter = AnthropicSchemaAdapter;
670
671 let schema = json!({
672 "type": "object",
673 "properties": {
674 "x": { "type": "number" }
675 },
676 "if": { "properties": { "x": { "minimum": 0 } } },
677 "then": { "required": ["x"] },
678 "else": { "properties": { "fallback": { "type": "string" } } }
679 });
680
681 let result = adapter.normalize_schema(schema);
682
683 assert!(result.get("if").is_none(), "if must be stripped");
684 assert!(result.get("then").is_none(), "then must be stripped");
685 assert!(result.get("else").is_none(), "else must be stripped");
686 assert_eq!(result["type"], "object");
688 assert!(result.get("properties").is_some());
689 }
690
691 #[test]
695 fn test_passthrough_preserves_one_of_and_all_of() {
696 let adapter = AnthropicSchemaAdapter;
697
698 let schema = json!({
699 "type": "object",
700 "oneOf": [
701 { "properties": { "a": { "type": "string" } } },
702 { "properties": { "b": { "type": "number" } } }
703 ],
704 "allOf": [
705 { "required": ["id"] },
706 { "properties": { "id": { "type": "string" } } }
707 ]
708 });
709
710 let result = adapter.normalize_schema(schema);
711
712 let one_of = result["oneOf"].as_array().expect("oneOf must be preserved");
713 assert_eq!(one_of.len(), 2);
714
715 let all_of = result["allOf"].as_array().expect("allOf must be preserved");
716 assert_eq!(all_of.len(), 2);
717 }
718
719 #[test]
720 fn a_response_schema_is_closed_and_unbounded_for_structured_outputs() {
721 let schema = json!({
722 "$schema": "http://json-schema.org/draft-07/schema#",
723 "type": "object",
724 "properties": {
725 "score": {"type": "number", "minimum": 0.0, "maximum": 1.0},
726 "tags": {"type": "array", "items": {"type": "string", "maxLength": 9}, "minItems": 2},
727 "owner": {"properties": {"name": {"type": "string"}}}
728 },
729 "required": ["score"]
730 });
731 assert_eq!(
732 structured_output_schema(&schema).unwrap(),
733 json!({
734 "type": "object",
735 "properties": {
736 "score": {"type": "number"},
737 "tags": {"type": "array", "items": {"type": "string"}},
738 "owner": {
739 "type": "object",
740 "properties": {"name": {"type": "string"}},
741 "additionalProperties": false
742 }
743 },
744 "required": ["score"],
745 "additionalProperties": false
746 })
747 );
748 }
749
750 #[test]
751 fn an_open_map_is_not_sent_as_structured_output() {
752 let map = json!({"type": "object", "additionalProperties": {"type": "string"}});
753 assert_eq!(structured_output_schema(&map), None);
754 let nested = json!({"type": "object", "properties": {"labels": map}});
755 assert_eq!(structured_output_schema(&nested), None);
756 }
757}