Skip to main content

base/interface/tool/
mod.rs

1//! Tool trait. All tools implement this single trait.
2
3mod context;
4mod registry;
5mod result;
6mod schema;
7
8pub use context::*;
9pub use registry::*;
10pub use result::*;
11pub use schema::*;
12
13use crate::error::ToolError;
14use async_trait::async_trait;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::path::PathBuf;
18use std::sync::Arc;
19use tokio_util::sync::CancellationToken;
20
21pub use crate::context::config::PathStyle;
22use crate::interface::permission::{ModeStance, PermissionFacts};
23pub use crate::permission::PermissionMode;
24#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct PromptContext {
27    pub cwd: PathBuf,
28    pub model: String,
29    pub session_id: String,
30    pub is_interactive: bool,
31    pub all_tool_names: Vec<String>,
32    pub allowed_agent_types: Vec<String>,
33    pub path_style: PathStyle,
34    /// The instance's names, for a guide that tells the model where
35    /// something lives or what the product is called.
36    pub layout: crate::paths::Layout,
37}
38impl Default for PromptContext {
39    fn default() -> Self {
40        Self {
41            cwd: PathBuf::new(),
42            model: String::new(),
43            session_id: String::new(),
44            is_interactive: false,
45            all_tool_names: vec![],
46            allowed_agent_types: vec![],
47            path_style: PathStyle::default(),
48            layout: crate::paths::Layout::default(),
49        }
50    }
51}
52
53/// Where a tool came from, for [`crate::interface::model::ToolDef::source`].
54///
55/// A name prefix (`mcp__`) already implies the answer, but a naming
56/// convention is not a declaration: it holds only for as long as nobody
57/// registers a builtin whose name happens to start that way. An adapter that
58/// knows which server or plugin it is fronting says so here.
59#[derive(Debug, Clone, PartialEq, Eq, Default)]
60#[non_exhaustive]
61pub enum ToolOrigin {
62    #[default]
63    Builtin,
64    Mcp {
65        server: String,
66    },
67    Plugin {
68        name: String,
69    },
70    /// Declared by the host for one session; calling it goes to the host.
71    Host,
72}
73
74impl ToolOrigin {
75    pub fn mcp(server: impl Into<String>) -> Self {
76        Self::Mcp {
77            server: server.into(),
78        }
79    }
80
81    pub fn plugin(name: impl Into<String>) -> Self {
82        Self::Plugin { name: name.into() }
83    }
84
85    pub fn mcp_server(&self) -> Option<&str> {
86        match self {
87            Self::Mcp { server } => Some(server),
88            Self::Builtin | Self::Plugin { .. } | Self::Host => None,
89        }
90    }
91
92    pub fn is_mcp(&self) -> bool {
93        self.mcp_server().is_some()
94    }
95
96    /// `builtin`, `mcp:<server>`, `plugin:<name>` or `host`.
97    pub fn wire(&self) -> String {
98        match self {
99            Self::Builtin => "builtin".to_string(),
100            Self::Mcp { server } => format!("mcp:{server}"),
101            Self::Plugin { name } => format!("plugin:{name}"),
102            Self::Host => "host".to_string(),
103        }
104    }
105}
106
107/// What a tool says about one call: answered by [`Tool::call_traits`], which
108/// is handed the call's input.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
110#[non_exhaustive]
111pub struct CallTraits {
112    pub read_only: bool,
113    pub concurrency_safe: bool,
114    pub destructive: bool,
115}
116
117impl CallTraits {
118    pub fn read_only(mut self, yes: bool) -> Self {
119        self.read_only = yes;
120        self
121    }
122    pub fn concurrency_safe(mut self, yes: bool) -> Self {
123        self.concurrency_safe = yes;
124        self
125    }
126    pub fn destructive(mut self, yes: bool) -> Self {
127        self.destructive = yes;
128        self
129    }
130}
131
132/// What a tool says about itself that holds for every call. Built with
133/// [`ToolSpec::new`] and the setters: `ToolSpec::new().read_only(true)`.
134///
135/// `traits` is the answer when the input is not looked at. A tool whose answer
136/// depends on the input overrides [`Tool::call_traits`] too, and puts its
137/// conservative answer here.
138///
139/// The input schema is not here: it is built on every call and the spec is
140/// asked for far more often than the schema.
141#[derive(Debug, Clone, PartialEq, Default)]
142#[non_exhaustive]
143pub struct ToolSpec {
144    /// What `ToolSearch` lists next to the name; the description when unset.
145    pub short_description: Option<String>,
146    pub origin: ToolOrigin,
147    pub traits: CallTraits,
148    /// Whether a program the model writes (`RunCode`) may call this tool.
149    /// Tools that do work and return data say yes; tools that talk to the
150    /// conversation or a person do not.
151    pub callable_from_code: bool,
152    /// What a program gets back from this tool, when that is more than the
153    /// text the model sees — the shape of its structured content.
154    pub code_result: Option<&'static str>,
155    /// Whether this tool calls other tools, and so needs
156    /// [`ToolContext::dispatch`].
157    pub needs_dispatch: bool,
158    /// How the permission modes treat this tool's calls.
159    pub stance: ModeStance,
160    /// The tool lets the model read a long result in parts (an offset), so
161    /// the engine does not save a long result to a file for it.
162    pub pages_itself: bool,
163}
164
165impl ToolSpec {
166    pub fn new() -> Self {
167        Self::default()
168    }
169    pub fn short_description(mut self, text: impl Into<String>) -> Self {
170        self.short_description = Some(text.into());
171        self
172    }
173    pub fn origin(mut self, origin: ToolOrigin) -> Self {
174        self.origin = origin;
175        self
176    }
177    pub fn traits(mut self, traits: CallTraits) -> Self {
178        self.traits = traits;
179        self
180    }
181    pub fn read_only(mut self, yes: bool) -> Self {
182        self.traits.read_only = yes;
183        self
184    }
185    pub fn concurrency_safe(mut self, yes: bool) -> Self {
186        self.traits.concurrency_safe = yes;
187        self
188    }
189    pub fn destructive(mut self, yes: bool) -> Self {
190        self.traits.destructive = yes;
191        self
192    }
193    pub fn callable_from_code(mut self, yes: bool) -> Self {
194        self.callable_from_code = yes;
195        self
196    }
197    pub fn code_result(mut self, shape: &'static str) -> Self {
198        self.code_result = Some(shape);
199        self
200    }
201    pub fn pages_itself(mut self) -> Self {
202        self.pages_itself = true;
203        self
204    }
205    pub fn needs_dispatch(mut self, yes: bool) -> Self {
206        self.needs_dispatch = yes;
207        self
208    }
209    pub fn stance(mut self, stance: ModeStance) -> Self {
210        self.stance = stance;
211        self
212    }
213}
214
215/// A tool the model can call.
216///
217/// What holds for every call is one [`spec`](Self::spec); what depends on the
218/// call's input is [`call_traits`](Self::call_traits), which defaults to the
219/// spec's answer. [`permission_facts`](Self::permission_facts) is what the
220/// permission engine weighs about the call; a tool that states none is asked
221/// about.
222#[async_trait]
223pub trait Tool: Send + Sync + 'static {
224    fn name(&self) -> &str;
225    fn description(&self) -> &str;
226    /// Everything about this tool that holds for every call — see
227    /// [`ToolSpec`].
228    fn spec(&self) -> ToolSpec;
229    /// The input schema as worded for a session's [`PathStyle`]; only tools
230    /// whose argument docs mention paths read `style`.
231    fn input_schema(&self, style: PathStyle) -> Value;
232
233    /// This tool's detailed usage guide, when it has one that says more than
234    /// `description()` already does.
235    ///
236    /// `ToolDef`s carry only `description()`; the full guides total ~85 KB
237    /// across the built-in set, too much to pay on every API call, so the model
238    /// fetches them on demand via `ToolSearch{query: "select:<name>"}`.
239    async fn guide(&self, _ctx: &PromptContext) -> Option<String> {
240        None
241    }
242
243    /// What this call reads, writes and may run beside; `spec().traits` unless
244    /// the answer depends on the input.
245    fn call_traits(&self, _input: &Value) -> CallTraits {
246        self.spec().traits
247    }
248
249    async fn permission_facts(&self, _: &Value, _: &ToolContext) -> PermissionFacts {
250        PermissionFacts::unknown()
251    }
252    async fn validate_input(&self, _: &Value, _: &ToolContext) -> ValidationResult {
253        ValidationResult::Ok
254    }
255    async fn call(
256        &self,
257        i: Value,
258        c: ToolContext,
259        p: ProgressSender,
260    ) -> Result<ToolResult, ToolError>;
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    struct F;
267    #[async_trait]
268    impl Tool for F {
269        fn name(&self) -> &str {
270            "f"
271        }
272        fn description(&self) -> &str {
273            "f"
274        }
275        fn spec(&self) -> ToolSpec {
276            ToolSpec::new().read_only(true).concurrency_safe(true)
277        }
278        fn input_schema(&self, _: PathStyle) -> Value {
279            serde_json::json!({})
280        }
281        async fn call(
282            &self,
283            _: Value,
284            _: ToolContext,
285            _: ProgressSender,
286        ) -> Result<ToolResult, ToolError> {
287            Ok(ToolResult::text("ok"))
288        }
289    }
290    #[test]
291    fn empty() {
292        assert!(InMemoryToolRegistry::new().list().is_empty());
293    }
294    #[test]
295    fn find() {
296        let r = InMemoryToolRegistry::new();
297        r.register(Arc::new(F));
298        assert!(r.get("f").is_some());
299    }
300
301    /// A tool that says nothing about where it came from is a builtin, so the
302    /// ones that say otherwise (MCP) are the exceptions — a newly written
303    /// builtin cannot forget to declare itself.
304    #[test]
305    fn a_tool_that_says_nothing_is_a_builtin() {
306        assert_eq!(F.spec().origin, ToolOrigin::Builtin);
307        assert_eq!(ToolOrigin::Builtin.wire(), "builtin");
308        assert_eq!(ToolOrigin::mcp("github").wire(), "mcp:github");
309    }
310}
311
312#[cfg(test)]
313mod spec_tests {
314    use super::*;
315
316    async fn unreachable_call() -> Result<ToolResult, ToolError> {
317        Ok(ToolResult::text("ok"))
318    }
319
320    struct Plain;
321    #[async_trait]
322    impl Tool for Plain {
323        fn name(&self) -> &str {
324            "Plain"
325        }
326        fn description(&self) -> &str {
327            "says nothing about itself"
328        }
329        fn spec(&self) -> ToolSpec {
330            ToolSpec::new()
331        }
332        fn input_schema(&self, _: PathStyle) -> Value {
333            serde_json::json!({"type": "object"})
334        }
335        async fn call(
336            &self,
337            _: Value,
338            _: ToolContext,
339            _: ProgressSender,
340        ) -> Result<ToolResult, ToolError> {
341            unreachable_call().await
342        }
343    }
344
345    struct Declared;
346    #[async_trait]
347    impl Tool for Declared {
348        fn name(&self) -> &str {
349            "Declared"
350        }
351        fn description(&self) -> &str {
352            "declares a spec"
353        }
354        fn input_schema(&self, _: PathStyle) -> Value {
355            serde_json::json!({"type": "object"})
356        }
357        fn spec(&self) -> ToolSpec {
358            ToolSpec::new()
359                .origin(ToolOrigin::mcp("x"))
360                .concurrency_safe(true)
361                .destructive(true)
362                .needs_dispatch(true)
363                .stance(ModeStance::LeavesPlan)
364                .short_description("short")
365        }
366        fn call_traits(&self, input: &Value) -> CallTraits {
367            self.spec().traits.read_only(input.get("peek").is_some())
368        }
369        async fn call(
370            &self,
371            _: Value,
372            _: ToolContext,
373            _: ProgressSender,
374        ) -> Result<ToolResult, ToolError> {
375            unreachable_call().await
376        }
377    }
378
379    #[tokio::test]
380    async fn a_tool_that_declares_nothing_gets_the_defaults() {
381        assert_eq!(Plain.spec(), ToolSpec::new());
382        assert_eq!(Plain.call_traits(&Value::Null), CallTraits::default());
383        assert_eq!(Plain.spec().origin, ToolOrigin::Builtin);
384        assert_eq!(Plain.spec().stance, ModeStance::Normal);
385        assert!(Plain.guide(&PromptContext::default()).await.is_none());
386    }
387
388    #[test]
389    fn a_declared_spec_is_what_the_engine_reads() {
390        let spec = Declared.spec();
391        assert_eq!(spec.origin.mcp_server(), Some("x"));
392        assert!(spec.traits.concurrency_safe && spec.traits.destructive);
393        assert!(spec.needs_dispatch);
394        assert_eq!(spec.stance, ModeStance::LeavesPlan);
395        assert!(!spec.callable_from_code);
396        assert_eq!(spec.short_description.as_deref(), Some("short"));
397    }
398
399    #[test]
400    fn call_traits_that_read_the_input_win_over_the_spec() {
401        assert!(!Declared.spec().traits.read_only);
402        assert!(
403            Declared
404                .call_traits(&serde_json::json!({"peek": 1}))
405                .read_only
406        );
407        assert!(!Declared.call_traits(&serde_json::json!({})).read_only);
408    }
409}