Skip to main content

merry_runtime/tool/
registry.rs

1use crate::{
2    final_output::FINAL_OUTPUT_TOOL_NAME,
3    tool::{
4        executor::{ToolExecutionContext, ToolExecutionError, ToolExecutor, ToolExecutorFuture},
5        proposal::ToolActionKind,
6    },
7    tool_input_validation::{CompiledToolInputValidator, ToolInputValidationError},
8};
9use merry_core::{PendingToolCall, ToolName, ToolSpec};
10use std::{collections::BTreeMap, sync::Arc};
11
12/// Where a registered tool is executed.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ToolRunner {
15    /// Merry/Rust runtime owns execution through a [`ToolExecutor`].
16    Runtime,
17    /// An external SDK runner executes after Merry emits a bridge event.
18    Bridge,
19}
20
21/// Runtime execution policy for calls that appear in the same model batch.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ToolConcurrency {
24    /// Calls may execute concurrently with adjacent parallel-safe calls.
25    ParallelSafe,
26    /// The call executes alone and acts as a barrier between concurrent waves.
27    Exclusive,
28}
29
30/// Runtime-owned registered tool definition.
31///
32/// A registered tool binds a provider-visible spec to an executor. It does not
33/// start or automate a tool loop. [`crate::Runtime::submit_tool_result`] is the
34/// external/manual result path; [`crate::Runtime::execute_tool_call`] is the
35/// runtime-registered executor path.
36#[derive(Clone)]
37pub struct RegisteredTool {
38    pub(super) spec: ToolSpec,
39    pub(super) external_binding: Option<merry_core::ExternalToolBinding>,
40    pub(super) executor: Arc<dyn ToolExecutor>,
41    pub(super) action_kind: ToolActionKind,
42    pub(super) proposals_enabled: bool,
43    pub(super) runner: ToolRunner,
44    pub(super) concurrency: ToolConcurrency,
45}
46
47impl RegisteredTool {
48    /// Creates a registered tool with an explicit runtime-owned action category.
49    ///
50    /// The spec is provider-visible after adapter rendering, but the executor
51    /// remains a runtime-owned boundary. The action category stays inside
52    /// runtime and is not rendered into the provider-visible tool spec.
53    #[must_use]
54    pub fn new(
55        spec: ToolSpec,
56        executor: Arc<dyn ToolExecutor>,
57        action_kind: ToolActionKind,
58    ) -> Self {
59        Self {
60            spec,
61            external_binding: None,
62            executor,
63            action_kind,
64            proposals_enabled: false,
65            runner: ToolRunner::Runtime,
66            concurrency: ToolConcurrency::Exclusive,
67        }
68    }
69
70    /// Attaches a stable adapter binding for session catalog persistence.
71    ///
72    /// Binding metadata is never rendered into the model's tool definition.
73    #[must_use]
74    pub fn with_external_binding(mut self, binding: merry_core::ExternalToolBinding) -> Self {
75        self.external_binding = Some(binding);
76        self
77    }
78
79    /// Returns the adapter identity, if this tool belongs to an external catalog.
80    #[must_use]
81    pub fn external_binding(&self) -> Option<&merry_core::ExternalToolBinding> {
82        self.external_binding.as_ref()
83    }
84
85    /// Enables read-only proposal evidence for a mutating tool.
86    ///
87    /// Runtime calls [`ToolExecutor::propose`] only for registered tools that
88    /// explicitly opt in here. The hook is still skipped for read-only tools.
89    #[must_use]
90    pub fn with_action_proposal(mut self) -> Self {
91        self.proposals_enabled = true;
92        self
93    }
94
95    /// Opts this tool into bounded concurrent execution within one model batch.
96    ///
97    /// Use this only when concurrent calls cannot race through writes,
98    /// processes, network access, permissions, or runtime-control state.
99    #[must_use]
100    pub fn with_parallel_safe_execution(mut self) -> Self {
101        self.concurrency = ToolConcurrency::ParallelSafe;
102        self
103    }
104
105    /// Creates a registered read-only tool.
106    ///
107    /// Use this only for tools that do not write workspace state or execute
108    /// commands. Network access is controlled by runtime profile, not by this
109    /// constructor.
110    #[must_use]
111    pub fn read_only(spec: ToolSpec, executor: Arc<dyn ToolExecutor>) -> Self {
112        Self::new(spec, executor, ToolActionKind::ReadOnly)
113    }
114
115    /// Creates a tool whose execution is delegated to an external SDK bridge.
116    #[must_use]
117    pub fn bridge(spec: ToolSpec) -> Self {
118        Self {
119            spec,
120            external_binding: None,
121            executor: Arc::new(BridgeExecutor),
122            action_kind: ToolActionKind::ReadOnly,
123            proposals_enabled: false,
124            runner: ToolRunner::Bridge,
125            concurrency: ToolConcurrency::Exclusive,
126        }
127    }
128
129    /// Borrows the provider-visible tool specification.
130    #[must_use]
131    pub fn spec(&self) -> &ToolSpec {
132        &self.spec
133    }
134
135    /// Returns the runtime-owned action category for this tool.
136    #[must_use]
137    pub fn action_kind(&self) -> ToolActionKind {
138        self.action_kind
139    }
140
141    /// Returns where this tool is executed.
142    #[must_use]
143    pub fn runner(&self) -> ToolRunner {
144        self.runner
145    }
146
147    /// Returns the runtime execution policy for batched calls.
148    #[must_use]
149    pub fn concurrency(&self) -> ToolConcurrency {
150        self.concurrency
151    }
152
153    /// Returns whether this tool opted into action proposal evidence.
154    #[must_use]
155    pub fn proposals_enabled(&self) -> bool {
156        self.proposals_enabled
157    }
158
159    pub(crate) fn executor(&self) -> Arc<dyn ToolExecutor> {
160        Arc::clone(&self.executor)
161    }
162}
163
164pub(super) struct BridgeExecutor;
165
166impl ToolExecutor for BridgeExecutor {
167    fn execute<'a>(
168        &'a self,
169        call: PendingToolCall,
170        _context: ToolExecutionContext,
171    ) -> ToolExecutorFuture<'a> {
172        Box::pin(async move {
173            Err(ToolExecutionError::infrastructure(format!(
174                "bridge tool {} must be executed by a bridge runner",
175                call.name().as_str()
176            )))
177        })
178    }
179}
180
181impl std::fmt::Debug for RegisteredTool {
182    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        formatter
184            .debug_struct("RegisteredTool")
185            .field("spec", &self.spec)
186            .field("action_kind", &self.action_kind)
187            .field("proposals_enabled", &self.proposals_enabled)
188            .field("runner", &self.runner)
189            .field("concurrency", &self.concurrency)
190            .finish_non_exhaustive()
191    }
192}
193
194#[derive(Debug, Clone, Default)]
195pub(crate) struct ToolRegistry {
196    pub(super) tools: BTreeMap<ToolName, RegisteredToolEntry>,
197    pub(super) order: Vec<ToolName>,
198}
199
200#[derive(Debug, Clone)]
201pub(super) struct RegisteredToolEntry {
202    pub(super) tool: RegisteredTool,
203    pub(super) input_validator: CompiledToolInputValidator,
204}
205
206impl ToolRegistry {
207    pub(crate) fn from_registered(tools: Vec<RegisteredTool>) -> Result<Self, ToolRegistryError> {
208        let mut registry = BTreeMap::new();
209        let mut order = Vec::with_capacity(tools.len());
210
211        for tool in tools {
212            let name = tool.spec().name().clone();
213            if name.as_str() == FINAL_OUTPUT_TOOL_NAME {
214                return Err(ToolRegistryError::ReservedName { name });
215            }
216            let input_validator = CompiledToolInputValidator::compile(tool.spec().input_schema())
217                .map_err(|source| ToolRegistryError::InvalidToolInputSchema {
218                name: name.clone(),
219                message: source.to_string(),
220            })?;
221            let entry = RegisteredToolEntry {
222                tool,
223                input_validator,
224            };
225            if registry.insert(name.clone(), entry).is_some() {
226                return Err(ToolRegistryError::DuplicateName { name });
227            }
228            order.push(name);
229        }
230
231        Ok(Self {
232            tools: registry,
233            order,
234        })
235    }
236
237    pub(crate) fn tool_specs(&self) -> Vec<ToolSpec> {
238        self.order
239            .iter()
240            .filter_map(|name| self.tools.get(name))
241            .map(|entry| entry.tool.spec().clone())
242            .collect()
243    }
244
245    pub(crate) fn external_tool_catalog(
246        &self,
247    ) -> Result<merry_core::SessionToolCatalog, merry_core::CoreError> {
248        merry_core::SessionToolCatalog::new(
249            self.order
250                .iter()
251                .filter_map(|name| {
252                    let tool = &self.tools.get(name)?.tool;
253                    Some(merry_core::SessionToolCatalogEntry::new(
254                        tool.spec().clone(),
255                        tool.external_binding()?.clone(),
256                    ))
257                })
258                .collect(),
259        )
260    }
261
262    pub(crate) fn registered_tool(&self, name: &ToolName) -> Option<&RegisteredTool> {
263        self.tools.get(name).map(|entry| &entry.tool)
264    }
265
266    pub(crate) fn validate_tool_input(
267        &self,
268        call: &PendingToolCall,
269    ) -> Option<Result<(), ToolInputValidationError>> {
270        self.tools
271            .get(call.name())
272            .map(|entry| entry.input_validator.validate_call(call))
273    }
274
275    pub(crate) fn first_bridge_tool_name(&self) -> Option<&ToolName> {
276        self.tools
277            .iter()
278            .find_map(|(name, entry)| (entry.tool.runner() == ToolRunner::Bridge).then_some(name))
279    }
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub(crate) enum ToolRegistryError {
284    DuplicateName { name: ToolName },
285    ReservedName { name: ToolName },
286    InvalidToolInputSchema { name: ToolName, message: String },
287}