1use serde::de::Error as _;
4use serde::ser::SerializeMap;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7use super::json::{JsonObject, JsonSchema, JsonValue};
8
9#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11#[serde(rename_all = "camelCase")]
12#[non_exhaustive]
13pub struct ToolSpec {
14 pub name: String,
16 pub description: String,
18 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub input_schema: Option<JsonSchema>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub output_schema: Option<JsonSchema>,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub annotations: Option<JsonObject>,
28}
29
30impl ToolSpec {
31 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
33 Self {
34 name: name.into(),
35 description: description.into(),
36 input_schema: None,
37 output_schema: None,
38 annotations: None,
39 }
40 }
41
42 #[must_use]
44 pub fn with_input_schema(mut self, schema: JsonSchema) -> Self {
45 self.input_schema = Some(schema);
46 self
47 }
48
49 #[must_use]
51 pub fn with_output_schema(mut self, schema: JsonSchema) -> Self {
52 self.output_schema = Some(schema);
53 self
54 }
55
56 #[must_use]
58 pub fn with_annotations(mut self, annotations: JsonObject) -> Self {
59 self.annotations = Some(annotations);
60 self
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67#[non_exhaustive]
68pub struct ToolUse {
69 pub name: String,
71 pub tool_use_id: String,
73 pub input: JsonValue,
75}
76
77impl ToolUse {
78 pub fn new(name: impl Into<String>, tool_use_id: impl Into<String>, input: JsonValue) -> Self {
80 Self {
81 name: name.into(),
82 tool_use_id: tool_use_id.into(),
83 input,
84 }
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
90#[serde(rename_all = "lowercase")]
91#[non_exhaustive]
92pub enum ToolResultStatus {
93 Success,
95 Error,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum ToolChoice {
105 Auto,
107 Any,
109 Tool {
111 name: String,
113 },
114}
115
116impl ToolChoice {
117 pub fn tool(name: impl Into<String>) -> Self {
119 Self::Tool { name: name.into() }
120 }
121}
122
123#[derive(Serialize, Deserialize)]
124struct NamedTool {
125 name: String,
126}
127
128impl Serialize for ToolChoice {
129 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
130 let mut map = serializer.serialize_map(Some(1))?;
131 match self {
132 Self::Auto => map.serialize_entry("auto", &JsonObject::new())?,
133 Self::Any => map.serialize_entry("any", &JsonObject::new())?,
134 Self::Tool { name } => map.serialize_entry("tool", &NamedTool { name: name.clone() })?,
135 }
136 map.end()
137 }
138}
139
140impl<'de> Deserialize<'de> for ToolChoice {
141 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
142 let mut map = JsonObject::deserialize(deserializer)?;
143 if map.contains_key("auto") {
144 return Ok(Self::Auto);
145 }
146 if map.contains_key("any") {
147 return Ok(Self::Any);
148 }
149 let Some(tool) = map.remove("tool") else {
150 return Err(D::Error::custom("Unknown ToolChoice type"));
151 };
152 let named = NamedTool::deserialize(tool).map_err(D::Error::custom)?;
153 Ok(Self::Tool { name: named.name })
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use serde_json::json;
160
161 use super::*;
162
163 #[test]
164 fn tool_choice_wire_shapes() {
165 let cases = [
166 (ToolChoice::Auto, json!({"auto": {}})),
167 (ToolChoice::Any, json!({"any": {}})),
168 (ToolChoice::tool("calculator"), json!({"tool": {"name": "calculator"}})),
169 ];
170 for (choice, wire) in cases {
171 assert_eq!(serde_json::to_value(&choice).unwrap(), wire);
172 assert_eq!(serde_json::from_value::<ToolChoice>(wire).unwrap(), choice);
173 }
174 }
175
176 #[test]
177 fn tool_choice_rejects_unknown_shapes() {
178 let error = serde_json::from_value::<ToolChoice>(json!({"none": {}})).unwrap_err();
179 assert_eq!(error.to_string(), "Unknown ToolChoice type");
180 }
181
182 #[test]
183 fn tool_spec_omits_absent_optionals() {
184 assert_eq!(
185 serde_json::to_value(ToolSpec::new("a", "b")).unwrap(),
186 json!({"name": "a", "description": "b"})
187 );
188 }
189
190 #[test]
191 fn tool_spec_serializes_schemas_and_annotations_in_ts_order() {
192 let mut annotations = JsonObject::new();
193 annotations.insert("readOnlyHint".into(), json!(true));
194 let spec = ToolSpec::new("get_weather", "Get the weather")
195 .with_input_schema(json!({"type": "object"}))
196 .with_output_schema(json!({"type": "string"}))
197 .with_annotations(annotations);
198 assert_eq!(
199 serde_json::to_string(&spec).unwrap(),
200 r#"{"name":"get_weather","description":"Get the weather","inputSchema":{"type":"object"},"outputSchema":{"type":"string"},"annotations":{"readOnlyHint":true}}"#
201 );
202 }
203
204 #[test]
205 fn tool_use_uses_camel_case_keys() {
206 let tool_use = ToolUse::new("calc", "t-1", json!({"a": 1}));
207 assert_eq!(
208 serde_json::to_value(&tool_use).unwrap(),
209 json!({"name": "calc", "toolUseId": "t-1", "input": {"a": 1}})
210 );
211 }
212}