Skip to main content

open_agent/tools/
tool.rs

1/// A named asynchronous function with a JSON input schema.
2///
3/// Use [`tool()`] to build a tool incrementally or [`Tool::new`] to supply a schema
4/// directly. Clones share the handler through [`Arc`]. The handler is responsible
5/// for validating arguments; the schema is sent to the model as its description.
6#[derive(Clone)]
7pub struct Tool {
8    /// Name used to match model tool calls to this handler.
9    name: String,
10
11    /// Description sent to the model.
12    description: String,
13
14    /// Normalized JSON input schema sent to the model.
15    input_schema: Value,
16
17    /// Shared asynchronous handler; clones of a tool share the same closure.
18    handler: ToolHandler,
19}
20
21impl Tool {
22    /// Creates a tool and normalizes its input schema.
23    ///
24    /// Accepted schema forms:
25    ///
26    /// - A full object containing `type` and `properties` is passed through unchanged.
27    /// - So is `{"type": "object"}` with only object-schema keywords beside it (`required`,
28    ///   `additionalProperties`, `description`, and the like), which declares a tool without
29    ///   parameters; an empty `properties` is added to it.
30    /// - A property map such as `{"query": "string"}` makes each property required.
31    /// - Extended properties may include `optional`, `required`, and `default`.
32    ///   Explicit `required: true` wins; otherwise `optional: true`, `required: false`,
33    ///   or a default makes the property optional. The two flags are removed afterward.
34    ///
35    /// Type aliases include `str`, `int`, `i32`/`i64`/`u32`/`u64`, `float`/`f32`/`f64`,
36    /// `bool`, `list`/`vec`, and `dict`/`map`. Unknown names become `string`. Non-object schema
37    /// inputs produce an empty object schema. The handler still validates arguments.
38    ///
39    /// # Example
40    ///
41    /// ```rust
42    /// use open_agent::Tool;
43    /// use serde_json::json;
44    ///
45    /// let search = Tool::new(
46    ///     "search",
47    ///     "Search documents",
48    ///     json!({
49    ///         "query": "string",
50    ///         "limit": {"type": "integer", "default": 10}
51    ///     }),
52    ///     |args| async move {
53    ///         let limit = args["limit"].as_u64().unwrap_or(10);
54    ///         Ok(json!({"query": args["query"], "limit": limit}))
55    ///     },
56    /// );
57    /// ```
58    pub fn new<F, Fut>(
59        name: impl Into<String>,
60        description: impl Into<String>,
61        input_schema: Value,
62        handler: F,
63    ) -> Self
64    where
65        F: Fn(Value) -> Fut + Send + Sync + 'static,
66        Fut: Future<Output = Result<Value>> + Send + 'static,
67    {
68        let name = name.into();
69        let description = description.into();
70
71        let input_schema = convert_schema_to_openai(input_schema);
72
73        Self {
74            name,
75            description,
76            input_schema,
77            handler: Arc::new(move |args| Box::pin(handler(args))),
78        }
79    }
80
81    /// Runs the handler with the supplied JSON arguments.
82    ///
83    /// The handler validates arguments; this method does not enforce the input schema.
84    ///
85    /// # Errors
86    ///
87    /// Propagates the handler's error unchanged. Automatic execution converts that
88    /// error to a tool-result JSON object so the model can respond to it.
89    pub async fn execute(&self, arguments: Value) -> Result<Value> {
90        (self.handler)(arguments).await
91    }
92
93    /// Returns the tool name, description, and schema in OpenAI function-calling format.
94    ///
95    /// The returned JSON contains no handler. Anthropic translation extracts the same
96    /// metadata when building its request.
97    pub fn to_openai_format(&self) -> Value {
98        serde_json::json!({
99            "type": "function",
100            "function": {
101                "name": self.name,
102                "description": self.description,
103                "parameters": self.input_schema
104            }
105        })
106    }
107
108    /// Returns the tool's name.
109    pub fn name(&self) -> &str {
110        &self.name
111    }
112
113    /// Returns the tool's description.
114    pub fn description(&self) -> &str {
115        &self.description
116    }
117
118    /// Returns a reference to the tool's input schema.
119    pub fn input_schema(&self) -> &Value {
120        &self.input_schema
121    }
122}
123
124/// Shows tool metadata and omits the handler.
125impl std::fmt::Debug for Tool {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.debug_struct("Tool")
128            .field("name", &self.name)
129            .field("description", &self.description)
130            .field("input_schema", &self.input_schema)
131            // Handler is intentionally omitted - it's not debuggable
132            .finish()
133    }
134}