Skip to main content

strands_macros/
lib.rs

1//! Procedural macros for the Strands Agents Rust SDK: [`macro@tool`] and [`macro@tools`].
2//!
3//! Use them through the `strands` crate (`strands::tool`, `strands::tools`); the generated code
4//! names only `strands` paths, so a crate needs no `serde` or `schemars` dependency of its own.
5
6mod attrs;
7mod docs;
8mod expand;
9mod signature;
10mod tool_fn;
11mod tools_impl;
12
13use proc_macro::TokenStream;
14
15/// Turns an `async fn` into a Strands tool.
16///
17/// The function stays callable as written. Next to it the macro generates a unit struct named
18/// after the function in PascalCase (`get_weather` becomes `GetWeather`) that implements
19/// `strands::Tool` and is `Clone`, `Copy`, `Default` and `Debug`.
20///
21/// - **Name.** The model-facing name is the function name; `#[tool(name = "..")]` overrides it.
22///   Names are 1 to 64 ASCII letters, digits, `_` or `-`.
23/// - **Description.** The function's doc comment up to its first section heading (`# Errors`,
24///   `# Examples`, ...), trimmed, with paragraphs kept; `#[tool(description = "..")]` overrides it.
25///   A tool without either does not compile, since models need the description to pick tools.
26/// - **Input.** The parameters form the input schema, in order: each parameter's doc comment is
27///   its `description`, `Option<T>` parameters are optional, and `#[serde(..)]` and
28///   `#[schemars(..)]` attributes on a parameter apply to its property. Parameter types implement
29///   `serde::Deserialize` and `schemars::JsonSchema`. The schema is normalized as
30///   `strands::tools::schema_for` does, computed once, and declares `additionalProperties: false`.
31///   The input is validated against it before the call; invalid input becomes an error result
32///   listing the violations, and unknown keys are ignored. A tool without parameters has the
33///   empty object schema and takes its input as given.
34/// - **Context.** One parameter of type `&ToolContext` marked `#[tool(context)]` receives the
35///   call's context; it is not part of the schema.
36/// - **Return value.** `Result<T, E>` with `E: Into<ToolError>` (any `std::error::Error`) or
37///   `E: Into<BoxError>` (`BoxError`, `String`, `&str`, `anyhow::Error`), or a plain `T`. A
38///   `ToolResultBlock` is the result (answering this call's tool use), a `Vec<ToolResultContent>`
39///   is the content of a successful result, and any other `T: Serialize` is shaped as
40///   `FunctionTool` shapes a callback's value: a string becomes text, an object JSON content, and
41///   so on. An `Err` becomes an error result with the text `Error: <message>`, except an
42///   interrupt from `ctx.interrupt(..)?`, which pauses the agent.
43/// - **Dependencies.** The generated input struct uses the `serde` and `schemars` that strands
44///   re-exports. A parameter of a type of your own derives `serde::Deserialize` and
45///   `schemars::JsonSchema` itself, so add `serde` and `schemars = "1"` (the major version
46///   strands uses) to your `Cargo.toml`.
47/// - **Paths.** Generated code names `::strands`; a crate that re-exports strands sets
48///   `#[tool(crate = "path::to::strands")]`.
49///
50/// ```
51/// use serde_json::json;
52/// use strands::{Tool, ToolContext, ToolError, tool};
53///
54/// /// Get the current weather for a city.
55/// #[tool]
56/// async fn get_weather(
57///     /// City name, for example "Seattle".
58///     city: String,
59///     /// Days to forecast.
60///     days: Option<u32>,
61///     #[tool(context)] ctx: &ToolContext,
62/// ) -> Result<String, ToolError> {
63///     let _ = ctx.tool_use();
64///     Ok(format!("Sunny in {city} for {} days", days.unwrap_or(1)))
65/// }
66///
67/// let spec = GetWeather.tool_spec();
68/// assert_eq!(spec.name, "get_weather");
69/// assert_eq!(spec.description, "Get the current weather for a city.");
70/// assert_eq!(
71///     spec.input_schema,
72///     Some(json!({
73///         "type": "object",
74///         "properties": {
75///             "city": {"type": "string", "description": "City name, for example \"Seattle\"."},
76///             "days": {"type": ["integer", "null"], "description": "Days to forecast.", "minimum": 0}
77///         },
78///         "required": ["city"],
79///         "additionalProperties": false
80///     }))
81/// );
82/// ```
83#[proc_macro_attribute]
84pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
85    tool_fn::expand(attr.into(), item.into()).into()
86}
87
88/// Generates tools from the `#[tool]` methods of an `impl` block, for tools with state.
89///
90/// Each `#[tool]` method takes `&self` and follows the [`macro@tool`] rules for its name,
91/// description, parameters, context and return value. For a method `check_stock` the macro
92/// generates `check_stock_tool(self: &Arc<Self>) -> impl Tool`, a tool holding the `Arc` that
93/// calls the method, with the method's visibility, and `tools(self: &Arc<Self>) ->
94/// Vec<ToolSource>` with every tool of the block, in order. `#[tools(crate = "..")]` sets the
95/// strands path.
96///
97/// ```
98/// use std::sync::Arc;
99/// use strands::{Tool, ToolError, tools};
100///
101/// struct Inventory {
102///     stock: u32,
103/// }
104///
105/// #[tools]
106/// impl Inventory {
107///     /// Look up stock for a product.
108///     #[tool]
109///     async fn check_stock(&self, sku: String) -> Result<u32, ToolError> {
110///         let _ = sku;
111///         Ok(self.stock)
112///     }
113/// }
114///
115/// let inventory = Arc::new(Inventory { stock: 3 });
116/// assert_eq!(inventory.check_stock_tool().name(), "check_stock");
117/// assert_eq!(inventory.tools().len(), 1);
118/// ```
119#[proc_macro_attribute]
120pub fn tools(attr: TokenStream, item: TokenStream) -> TokenStream {
121    tools_impl::expand(attr.into(), item.into()).into()
122}