Skip to main content

merry_runtime/
tool_api.rs

1//! Application-facing typed tool construction.
2//!
3//! This module owns the small semantic tool API used by the facade and coding
4//! composition layers. The runtime converts a typed handler into its internal
5//! [`RegisteredTool`] representation; application code does not need to know
6//! about executors, action categories, or runner selection.
7
8use crate::{
9    FINAL_OUTPUT_TOOL_NAME, RegisteredTool, ToolActionKind, ToolExecutionContext,
10    ToolExecutionError, ToolExecutionOutcome, ToolExecutionResult, ToolExecutor,
11    ToolExecutorFuture,
12};
13use merry_core::{CoreError, ErrorInfo, PendingToolCall, ToolInputSchema, ToolName, ToolSpec};
14use schemars::JsonSchema;
15use serde::{Serialize, de::DeserializeOwned};
16use std::{fmt, future::Future, marker::PhantomData, sync::Arc};
17use thiserror::Error;
18
19/// A typed application tool executed by the Merry runtime.
20///
21/// The tool's input schema is derived from `I`. The handler runs as trusted
22/// in-process application code; runtime owns invocation ordering, lifecycle,
23/// artifact recording, and model continuation. Use the explicit host handoff
24/// protocol only when a different language runtime owns the callable.
25#[derive(Clone)]
26pub struct Tool {
27    spec: ToolSpec,
28    executor: Arc<dyn ToolExecutor>,
29}
30
31impl Tool {
32    /// Creates a provider-neutral tool specification from a typed input.
33    ///
34    /// This is useful for runtime-owned executors that need the same schema
35    /// derivation as [`Self::new`] but must retain custom execution, tracing,
36    /// cancellation, or action-policy behavior.
37    pub fn spec_for<I>(
38        name: impl AsRef<str>,
39        description: impl AsRef<str>,
40    ) -> Result<ToolSpec, ToolBuildError>
41    where
42        I: DeserializeOwned + JsonSchema,
43    {
44        let name = ToolName::new(name.as_ref())?;
45        if name.as_str() == FINAL_OUTPUT_TOOL_NAME {
46            return Err(ToolBuildError::ReservedName { name });
47        }
48        let input_schema = ToolInputSchema::new(schemars::schema_for!(I))?.require_object()?;
49        Ok(ToolSpec::new(name, description.as_ref(), input_schema)?)
50    }
51
52    /// Creates a typed asynchronous application tool.
53    ///
54    /// Handler errors become durable failed tool results, allowing the model
55    /// loop to observe the failure and recover. Serialization or argument
56    /// decoding failures are also represented as tool failures where the call
57    /// has already been admitted by runtime.
58    pub fn new<I, O, F, Fut, E>(
59        name: impl AsRef<str>,
60        description: impl AsRef<str>,
61        handler: F,
62    ) -> Result<Self, ToolBuildError>
63    where
64        I: DeserializeOwned + JsonSchema + Send + 'static,
65        O: Serialize + Send + 'static,
66        F: Fn(I) -> Fut + Send + Sync + 'static,
67        Fut: Future<Output = Result<O, E>> + Send + 'static,
68        E: fmt::Display + Send + Sync + 'static,
69    {
70        let spec = Self::spec_for::<I>(name, description)?;
71        let executor = TypedToolExecutor {
72            handler,
73            input_marker: PhantomData,
74            future_marker: PhantomData,
75            error_marker: PhantomData,
76        };
77
78        Ok(Self {
79            spec,
80            executor: Arc::new(executor),
81        })
82    }
83
84    /// Borrows the provider-neutral tool specification.
85    #[must_use]
86    pub fn spec(&self) -> &ToolSpec {
87        &self.spec
88    }
89
90    /// Returns the internal runtime registration used by coding composition.
91    ///
92    /// This is a framework integration hook. Application code should pass the
93    /// [`Tool`] to `CodingAgentProfileBuilder::tool` or `AgentBuilder::tool`.
94    #[doc(hidden)]
95    #[must_use]
96    pub fn into_registered_tool(self) -> RegisteredTool {
97        RegisteredTool::new(self.spec, self.executor, ToolActionKind::TrustedExternal)
98    }
99}
100
101impl fmt::Debug for Tool {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter
104            .debug_struct("Tool")
105            .field("spec", &self.spec)
106            .finish_non_exhaustive()
107    }
108}
109
110/// Errors raised while constructing a typed application tool.
111#[derive(Debug, Error)]
112pub enum ToolBuildError {
113    /// The public tool name, description, or schema was invalid.
114    #[error(transparent)]
115    Core(#[from] CoreError),
116    /// The tool name is reserved for runtime-owned protocol behavior.
117    #[error("tool name {name} is reserved by the runtime")]
118    ReservedName {
119        /// Rejected reserved tool name.
120        name: ToolName,
121    },
122}
123
124impl From<ToolBuildError> for CoreError {
125    fn from(error: ToolBuildError) -> Self {
126        match error {
127            ToolBuildError::Core(source) => source,
128            ToolBuildError::ReservedName { name } => CoreError::InvalidIdentifier {
129                kind: "ToolName",
130                value: name.to_string(),
131                reason: "tool name is reserved",
132            },
133        }
134    }
135}
136
137struct TypedToolExecutor<I, O, F, Fut, E> {
138    handler: F,
139    input_marker: PhantomData<fn(I) -> O>,
140    future_marker: PhantomData<fn() -> Fut>,
141    error_marker: PhantomData<fn() -> E>,
142}
143
144impl<I, O, F, Fut, E> ToolExecutor for TypedToolExecutor<I, O, F, Fut, E>
145where
146    I: DeserializeOwned + JsonSchema + Send + 'static,
147    O: Serialize + Send + 'static,
148    F: Fn(I) -> Fut + Send + Sync + 'static,
149    Fut: Future<Output = Result<O, E>> + Send + 'static,
150    E: fmt::Display + Send + Sync + 'static,
151{
152    fn execute<'a>(
153        &'a self,
154        call: PendingToolCall,
155        context: ToolExecutionContext,
156    ) -> ToolExecutorFuture<'a> {
157        let input = match call.arguments().deserialize_as::<I>() {
158            Ok(input) => input,
159            Err(source) => {
160                return Box::pin(async move {
161                    failed_tool_result(
162                        format!("tool arguments could not be decoded: {source}"),
163                        "tool_input_decode_failed",
164                        "tool arguments did not match the declared input type",
165                    )
166                });
167            }
168        };
169
170        let cancellation_token = context.cancellation_token().clone();
171        let handler_future = (self.handler)(input);
172        Box::pin(async move {
173            tokio::select! {
174                result = handler_future => match result {
175                    Ok(output) => match serde_json::to_string(&output) {
176                        Ok(content) => Ok(ToolExecutionOutcome::succeeded_json(content)),
177                        Err(source) => failed_tool_result(
178                            format!("tool output could not be serialized: {source}"),
179                            "tool_output_serialization_failed",
180                            "the tool returned a value that could not be serialized",
181                        ),
182                    },
183                    Err(error) => failed_tool_result(
184                        error.to_string(),
185                        "tool_handler_failed",
186                        "the tool handler returned a domain error",
187                    ),
188                },
189                _ = cancellation_token.cancelled() => Err(ToolExecutionError::Cancelled),
190            }
191        })
192    }
193}
194
195fn failed_tool_result(
196    content: String,
197    code: &'static str,
198    diagnostic_message: &'static str,
199) -> ToolExecutionResult {
200    let diagnostic = ErrorInfo::new(code, diagnostic_message).map_err(|source| {
201        ToolExecutionError::infrastructure(format!(
202            "failed to create tool failure diagnostic: {source}"
203        ))
204    })?;
205    Ok(ToolExecutionOutcome::failed_text(content, diagnostic))
206}