infinity_agent_core/tools/
rap_tool.rs1use async_trait::async_trait;
10use rap_protocol::RapInvocation;
11use tracing;
12
13use super::{Tool, ToolContext, send_tool_error};
14use crate::traits::InputSender;
15use rap_client::http::HttpClient;
16
17type BoxError = Box<dyn std::error::Error + Send + Sync>;
18
19#[derive(Clone)]
24pub struct RapToolDescriptor {
25 pub name: String,
26 pub description: String,
27 pub parameters: serde_json::Value,
28 pub display_script: Option<String>,
29}
30
31impl From<rap_protocol::ToolDef> for RapToolDescriptor {
32 fn from(def: rap_protocol::ToolDef) -> Self {
33 Self {
34 name: def.name,
35 description: def.description,
36 parameters: def.input_schema,
37 display_script: def.display_script,
38 }
39 }
40}
41
42pub struct RapInvocationParams<'a> {
45 pub endpoint: &'a str,
47 pub operation: &'a str,
49 pub arguments: serde_json::Value,
51 pub id: String,
53 pub call_id: Option<String>,
55 pub callback_url: Option<&'a str>,
59}
60
61pub async fn invoke_rap_tool<H, M>(
73 http_client: &H,
74 params: RapInvocationParams<'_>,
75 context: &ToolContext<M>,
76) -> Result<(), BoxError>
77where
78 H: HttpClient,
79 M: InputSender + 'static,
80 M::Error: 'static,
81{
82 let RapInvocationParams {
83 endpoint,
84 operation,
85 arguments,
86 id,
87 call_id,
88 callback_url,
89 } = params;
90
91 let thread_ancestors = (context.thread_stack.len() > 1)
92 .then(|| context.thread_stack[..context.thread_stack.len() - 1].to_vec());
93
94 let invocation = RapInvocation {
95 operation: operation.to_owned(),
96 arguments,
97 id: id.clone(),
98 call_id: call_id.clone(),
99 callback_url: callback_url
100 .unwrap_or(context.callback_url.as_str())
101 .to_owned(),
102 group_id: context.group_id.clone(),
103 user_id: context.user_id.clone(),
104 thread_ancestors,
105 };
106
107 let body = serde_json::to_string(&invocation)?;
108 let status = http_client
109 .post(endpoint, &body)
110 .await
111 .map_err(|e| Box::new(e) as BoxError)?;
112
113 if !(200..300).contains(&status) {
114 tracing::warn!("RAP tool {operation} at {endpoint} returned status {status}");
115 send_tool_error(
116 context,
117 &id,
118 call_id,
119 format!(
120 "RAP tool '{operation}' failed: the server at {endpoint} \
121 responded with HTTP {status}. No result will arrive for \
122 this call."
123 ),
124 )
125 .await?;
126 return Ok(());
127 }
128 tracing::info!("Invoked RAP tool {operation} (status: {status})");
129 Ok(())
130}
131
132#[derive(Clone)]
136pub struct RapTool<H: HttpClient> {
137 pub descriptor: RapToolDescriptor,
138 pub endpoint: String,
139 pub http_client: H,
140 pub callback_url: Option<String>,
143}
144
145#[async_trait]
146impl<H: HttpClient + 'static, M: InputSender + 'static> Tool<M> for RapTool<H> {
147 fn name(&self) -> &str {
148 &self.descriptor.name
149 }
150
151 fn description(&self) -> &str {
152 &self.descriptor.description
153 }
154
155 fn parameters(&self) -> serde_json::Value {
156 self.descriptor.parameters.clone()
157 }
158
159 fn display_script(&self) -> Option<&str> {
160 self.descriptor.display_script.as_deref()
161 }
162
163 async fn execute(
164 &self,
165 args: serde_json::Value,
166 id: String,
167 call_id: Option<String>,
168 context: &ToolContext<M>,
169 ) -> Result<(), BoxError> {
170 invoke_rap_tool(
171 &self.http_client,
172 RapInvocationParams {
173 endpoint: &self.endpoint,
174 operation: &self.descriptor.name,
175 arguments: args,
176 id,
177 call_id,
178 callback_url: self.callback_url.as_deref(),
179 },
180 context,
181 )
182 .await
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use crate::message::{InputMessage, InputMessageContent};
190 use infinity_provider_protocol::message::UserContent;
191 use std::sync::{Arc, Mutex};
192
193 #[derive(Debug)]
194 struct TestError(String);
195 impl std::fmt::Display for TestError {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 write!(f, "{}", self.0)
198 }
199 }
200 impl std::error::Error for TestError {}
201
202 #[derive(Clone)]
205 struct MockHttp {
206 status: Option<u16>,
207 posts: Arc<Mutex<Vec<(String, String)>>>,
208 }
209
210 impl MockHttp {
211 fn returning(status: u16) -> Self {
212 Self {
213 status: Some(status),
214 posts: Arc::new(Mutex::new(Vec::new())),
215 }
216 }
217
218 fn failing() -> Self {
219 Self {
220 status: None,
221 posts: Arc::new(Mutex::new(Vec::new())),
222 }
223 }
224 }
225
226 #[async_trait]
227 impl HttpClient for MockHttp {
228 type Error = TestError;
229
230 async fn post(&self, url: &str, body: &str) -> Result<u16, TestError> {
231 self.posts
232 .lock()
233 .expect("bug: mock posts mutex poisoned")
234 .push((url.to_owned(), body.to_owned()));
235 self.status
236 .ok_or_else(|| TestError("connection refused".to_owned()))
237 }
238
239 async fn get(&self, _url: &str) -> Result<(u16, Vec<u8>), TestError> {
240 Err(TestError("unused".to_owned()))
241 }
242 }
243
244 #[derive(Clone)]
246 struct CapturingSender {
247 messages: Arc<Mutex<Vec<(InputMessage, String)>>>,
248 }
249
250 #[async_trait]
251 impl InputSender for CapturingSender {
252 type Error = TestError;
253
254 async fn send_to_input_queue(
255 &self,
256 message: InputMessage,
257 dedup_id: &str,
258 ) -> Result<(), TestError> {
259 self.messages
260 .lock()
261 .expect("bug: mock messages mutex poisoned")
262 .push((message, dedup_id.to_owned()));
263 Ok(())
264 }
265 }
266
267 fn test_context(thread_stack: Vec<&str>) -> ToolContext<CapturingSender> {
268 ToolContext {
269 message_sender: CapturingSender {
270 messages: Arc::new(Mutex::new(Vec::new())),
271 },
272 group_id: "thread-1".into(),
273 callback_url: "http://context-callback".to_owned(),
274 user_id: Some("user-1".to_owned()),
275 thread_stack: thread_stack
276 .into_iter()
277 .map(rap_protocol::ThreadId::from)
278 .collect(),
279 }
280 }
281
282 fn params<'a>(arguments: serde_json::Value) -> RapInvocationParams<'a> {
283 RapInvocationParams {
284 endpoint: "http://server/invoke",
285 operation: "lookup",
286 arguments,
287 id: "tc-1".to_owned(),
288 call_id: Some("call-1".to_owned()),
289 callback_url: None,
290 }
291 }
292
293 fn sent_messages(context: &ToolContext<CapturingSender>) -> Vec<(InputMessage, String)> {
294 context
295 .message_sender
296 .messages
297 .lock()
298 .expect("bug: mock messages mutex poisoned")
299 .clone()
300 }
301
302 #[tokio::test]
303 async fn non_2xx_delivers_descriptive_error_result() {
304 let http = MockHttp::returning(503);
305 let context = test_context(vec!["thread-1"]);
306
307 invoke_rap_tool(&http, params(serde_json::json!({})), &context)
308 .await
309 .expect("non-2xx is reported to the model, not returned as Err");
310
311 let sent = sent_messages(&context);
312 assert_eq!(sent.len(), 1, "exactly one error result is enqueued");
313 let (message, dedup_id) = &sent[0];
314 assert_eq!(dedup_id, "tc-1", "dedup ID is the tool-call ID");
315 assert_eq!(message.group_id.as_str(), "thread-1");
316 let InputMessageContent::User(UserContent::ToolResult(result)) = &message.content else {
317 panic!("expected a tool result, got {:?}", message.content);
318 };
319 assert_eq!(result.id, "tc-1");
320 assert_eq!(result.call_id.as_deref(), Some("call-1"));
321 let Some(infinity_provider_protocol::message::ToolResultContent::Text(text)) =
322 result.content.first()
323 else {
324 panic!("expected text content");
325 };
326 for expected in ["Error:", "lookup", "http://server/invoke", "503"] {
327 assert!(
328 text.text.contains(expected),
329 "error text must mention {expected:?}: {}",
330 text.text
331 );
332 }
333 }
334
335 #[tokio::test]
336 async fn transport_failure_returns_err_without_result() {
337 let http = MockHttp::failing();
338 let context = test_context(vec!["thread-1"]);
339
340 let result = invoke_rap_tool(&http, params(serde_json::json!({})), &context).await;
341
342 assert!(result.is_err(), "transport failures surface as Err");
343 assert!(
344 sent_messages(&context).is_empty(),
345 "the runtime's generic fallback owns transport failures"
346 );
347 }
348
349 #[tokio::test]
350 async fn subthread_invocation_carries_ancestors_and_callback_override() {
351 let http = MockHttp::returning(204);
352 let context = test_context(vec!["root", "middle", "leaf"]);
353 let mut request = params(serde_json::json!({}));
354 request.callback_url = Some("http://bridge-listener");
355
356 invoke_rap_tool(&http, request, &context)
357 .await
358 .expect("2xx must succeed");
359
360 let posts = http.posts.lock().expect("bug: mock posts mutex poisoned");
361 let invocation: RapInvocation =
362 serde_json::from_str(&posts[0].1).expect("posted body is a RapInvocation");
363 assert_eq!(
364 invocation.thread_ancestors,
365 Some(vec!["root".into(), "middle".into()]),
366 "ancestors exclude the current thread"
367 );
368 assert_eq!(invocation.callback_url, "http://bridge-listener");
369 assert!(
370 sent_messages(&context).is_empty(),
371 "a successful invocation enqueues nothing; the result arrives by callback"
372 );
373 }
374
375 #[tokio::test]
378 async fn root_invocation_defaults_to_context_callback() {
379 let http = MockHttp::returning(200);
380 let context = test_context(vec!["thread-1"]);
381
382 invoke_rap_tool(&http, params(serde_json::json!({})), &context)
383 .await
384 .expect("2xx must succeed");
385
386 let posts = http.posts.lock().expect("bug: mock posts mutex poisoned");
387 let invocation: RapInvocation =
388 serde_json::from_str(&posts[0].1).expect("posted body is a RapInvocation");
389 assert_eq!(invocation.thread_ancestors, None);
390 assert_eq!(invocation.callback_url, "http://context-callback");
391 }
392}