1mod 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 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#[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 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 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#[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#[derive(Debug, Clone, PartialEq, Default)]
142#[non_exhaustive]
143pub struct ToolSpec {
144 pub short_description: Option<String>,
146 pub origin: ToolOrigin,
147 pub traits: CallTraits,
148 pub callable_from_code: bool,
152 pub code_result: Option<&'static str>,
155 pub needs_dispatch: bool,
158 pub stance: ModeStance,
160 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#[async_trait]
223pub trait Tool: Send + Sync + 'static {
224 fn name(&self) -> &str;
225 fn description(&self) -> &str;
226 fn spec(&self) -> ToolSpec;
229 fn input_schema(&self, style: PathStyle) -> Value;
232
233 async fn guide(&self, _ctx: &PromptContext) -> Option<String> {
240 None
241 }
242
243 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 #[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}