1use std::sync::Arc;
4
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use tokio_util::sync::CancellationToken;
9
10use crate::ai::types::{ToolResultContent, ToolSchema};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum ExecutionMode {
15 Sequential,
17 #[default]
19 Parallel,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ToolResult {
25 pub content: Vec<ToolResultContent>,
26 #[serde(default)]
31 pub details: Value,
32 #[serde(default)]
33 pub terminate: bool,
34}
35
36impl ToolResult {
37 pub fn text(text: impl Into<String>) -> Self {
38 Self {
39 content: vec![ToolResultContent::text(text)],
40 details: Value::Null,
41 terminate: false,
42 }
43 }
44
45 pub fn error(message: impl Into<String>) -> Self {
46 Self::text(message)
47 }
48
49 pub fn with_details(mut self, details: Value) -> Self {
50 self.details = details;
51 self
52 }
53}
54
55#[async_trait]
59pub trait AgentTool: Send + Sync {
60 fn name(&self) -> &str;
61 fn label(&self) -> &str {
62 self.name()
63 }
64 fn description(&self) -> &str;
65 fn input_schema(&self) -> Value;
67 fn execution_mode(&self) -> ExecutionMode {
68 ExecutionMode::Parallel
69 }
70 fn prepare_arguments(&self, args: Value) -> Value {
71 args
72 }
73 async fn execute(
76 &self,
77 args: Value,
78 cancel: CancellationToken,
79 ) -> anyhow::Result<ToolResult>;
80
81 fn schema(&self) -> ToolSchema {
83 ToolSchema {
84 name: self.name().to_string(),
85 description: self.description().to_string(),
86 input_schema: self.input_schema(),
87 }
88 }
89}
90
91pub fn validate_required(schema: &Value, args: &Value) -> Result<(), String> {
94 let Some(required) = schema.get("required").and_then(|v| v.as_array()) else {
95 return Ok(());
96 };
97 let obj = args.as_object().ok_or_else(|| "tool arguments must be an object".to_string())?;
98 for r in required {
99 if let Some(key) = r.as_str() {
100 let present = obj
101 .get(key)
102 .map(|v| !v.is_null())
103 .unwrap_or(false);
104 if !present {
105 return Err(format!("missing required parameter: {key}"));
106 }
107 }
108 }
109 Ok(())
110}
111
112pub struct ToolCallContext<'a> {
118 pub tool_call_id: &'a str,
119 pub tool_name: &'a str,
120 pub args: &'a Value,
121}
122
123pub struct BeforeToolCallResult {
125 pub block: bool,
126 pub reason: Option<String>,
127}
128
129impl BeforeToolCallResult {
130 pub fn allow() -> Self {
131 Self {
132 block: false,
133 reason: None,
134 }
135 }
136 pub fn block(reason: impl Into<String>) -> Self {
137 Self {
138 block: true,
139 reason: Some(reason.into()),
140 }
141 }
142}
143
144#[async_trait]
146pub trait ToolGate: Send + Sync {
147 async fn before(&self, ctx: ToolCallContext<'_>) -> BeforeToolCallResult;
148}
149
150pub struct AllowAllGate;
152
153#[async_trait]
154impl ToolGate for AllowAllGate {
155 async fn before(&self, _ctx: ToolCallContext<'_>) -> BeforeToolCallResult {
156 BeforeToolCallResult::allow()
157 }
158}
159
160pub fn allow_all_gate() -> Arc<dyn ToolGate> {
161 Arc::new(AllowAllGate)
162}