Skip to main content

strands/vended_tools/
handoff_to_user.rs

1//! The `handoff_to_user` tool: pauses the agent loop with an interrupt that surfaces a message to
2//! the user; on resume the user's reply is the tool result.
3
4use serde_json::json;
5
6use super::input::InputReader;
7use crate::tools::{FunctionTool, ToolError};
8use crate::types::{InterruptParams, JsonSchema, JsonValue};
9
10/// The name of the interrupt the tool raises (`HANDOFF_INTERRUPT_NAME`), the same whatever the
11/// tool is called, so callers can match handoffs in
12/// [`AgentResult::interrupts`](crate::AgentResult::interrupts).
13pub const HANDOFF_INTERRUPT_NAME: &str = "strands:handoff-to-user";
14
15/// The description of the `handoff_to_user` tool shown to the model
16/// (`DEFAULT_HANDOFF_TO_USER_DESCRIPTION`).
17pub(crate) const DEFAULT_HANDOFF_TO_USER_DESCRIPTION: &str = concat!(
18    "Ask the user a question and wait for their answer. Use it only when you cannot proceed ",
19    "without confirmation, approval, or information that only the user has. Do not call it to ",
20    "deliver a final answer or to report progress. The user's reply is returned as the tool result."
21);
22
23/// Options for [`make_handoff_to_user`] (`MakeHandoffToUserOptions`).
24#[derive(Debug, Clone, Default, bon::Builder)]
25#[builder(on(String, into))]
26pub struct MakeHandoffToUserOptions {
27    /// The tool name; `handoff_to_user` when absent. The interrupt name stays
28    /// [`HANDOFF_INTERRUPT_NAME`].
29    pub name: Option<String>,
30    /// The tool description; the default handoff description when absent.
31    pub description: Option<String>,
32}
33
34fn input_schema() -> JsonSchema {
35    json!({
36        "type": "object",
37        "properties": {
38            "message": {"type": "string", "description": "The message to surface to the user."}
39        },
40        "required": ["message"],
41        "additionalProperties": false
42    })
43}
44
45/// The default `handoff_to_user` tool.
46#[must_use]
47pub fn handoff_to_user() -> FunctionTool {
48    make_handoff_to_user(MakeHandoffToUserOptions::default())
49}
50
51/// Creates a handoff tool. The first call raises an interrupt named
52/// [`HANDOFF_INTERRUPT_NAME`] whose reason is `message`; once answered, the reply is the result.
53///
54/// ```
55/// use strands::vended_tools::handoff_to_user::{MakeHandoffToUserOptions, make_handoff_to_user};
56///
57/// let ask_user = make_handoff_to_user(MakeHandoffToUserOptions::builder().name("ask_user").build());
58/// let agent = strands::Agent::builder().tools([ask_user]).printer(false).build()?;
59/// assert!(agent.tool_registry().get("ask_user").is_some());
60/// # Ok::<(), strands::Error>(())
61/// ```
62#[must_use]
63pub fn make_handoff_to_user(options: MakeHandoffToUserOptions) -> FunctionTool {
64    let name = options.name.unwrap_or_else(|| "handoff_to_user".to_owned());
65    let description = options
66        .description
67        .unwrap_or_else(|| DEFAULT_HANDOFF_TO_USER_DESCRIPTION.to_owned());
68    FunctionTool::builder(name, description)
69        .input_schema(input_schema())
70        .callback(|input, context| {
71            let result = parse(&input).and_then(|message| {
72                let params = InterruptParams::new(HANDOFF_INTERRUPT_NAME).with_reason(message);
73                Ok(context.interrupt(params)?)
74            });
75            async move { result }
76        })
77}
78
79fn parse(input: &JsonValue) -> Result<String, ToolError> {
80    let mut reader = InputReader::new(input);
81    let message = reader.string("message");
82    if message.is_some_and(|message| message.trim().is_empty()) {
83        reader.issue("message", "message must not be empty");
84    }
85    reader.finish()?;
86    Ok(message.unwrap_or_default().to_owned())
87}
88
89#[cfg(test)]
90mod tests;