1use async_trait::async_trait;
14use causa_kernel::{
15 ArtifactStore, CallControl, DynamicToolSource, Tool, ToolCallContext, ToolDefinition,
16 ToolExecutionError, ToolMetadata, ToolOutput, ToolResultPayload, ToolResultStatus,
17};
18use serde_json::json;
19
20pub struct ToolBridge {
38 source: std::sync::Arc<dyn DynamicToolSource>,
39 definition: ToolDefinition,
40 metadata: ToolMetadata,
41}
42
43impl ToolBridge {
44 pub fn new(source: std::sync::Arc<dyn DynamicToolSource>, definition: ToolDefinition) -> Self {
47 Self {
48 source,
49 definition,
50 metadata: ToolMetadata::default(),
51 }
52 }
53
54 pub fn with_metadata(mut self, metadata: ToolMetadata) -> Self {
57 self.metadata = metadata;
58 self
59 }
60
61 pub fn with_meta<T: std::any::Any + Send + Sync>(mut self, value: T) -> Self {
64 self.metadata.insert(value);
65 self
66 }
67}
68
69#[async_trait]
70impl Tool for ToolBridge {
71 fn definition(&self) -> ToolDefinition {
72 self.definition.clone()
73 }
74
75 fn metadata(&self) -> ToolMetadata {
76 self.metadata.clone()
77 }
78
79 async fn execute(
80 &self,
81 ctx: &ToolCallContext,
82 control: &CallControl,
83 store: Option<&dyn ArtifactStore>,
84 ) -> ToolResultPayload {
85 match self.source.invoke(ctx, control, store).await {
86 Ok(result) => result,
87 Err(error) => {
88 let (status, reason) = match &error {
91 ToolExecutionError::TimedOut => {
92 (ToolResultStatus::UnknownOutcome, Some("source_timed_out"))
93 }
94 ToolExecutionError::Cancelled => {
95 (ToolResultStatus::UnknownOutcome, Some("source_cancelled"))
96 }
97 ToolExecutionError::UnknownTool(_) => (ToolResultStatus::Rejected, None),
98 ToolExecutionError::Unavailable(_) | ToolExecutionError::Protocol(_) => {
99 (ToolResultStatus::Failed, None)
100 }
101 };
102 let mut output = ToolOutput::new(json!({ "error": error.to_string() }));
103 if let Some(reason) = reason {
104 output.meta.get_or_insert_default().extra = Some(json!({ "reason": reason }));
105 }
106 ToolResultPayload::new(ctx.call_block_id, status, output)
107 }
108 }
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115 use causa_kernel::{CancellationToken, ToolCallPayload};
116
117 enum StubReply {
120 Echo,
121 Error(ToolExecutionError),
122 Reported(ToolResultStatus, ToolOutput),
123 }
124
125 struct StubSource(StubReply);
126
127 #[async_trait]
128 impl DynamicToolSource for StubSource {
129 fn id(&self) -> &str {
130 "stub"
131 }
132 async fn list(&self) -> Result<Vec<ToolDefinition>, causa_kernel::SourceError> {
133 Ok(vec![ToolDefinition::new(
134 "mcp_stub_echo",
135 "stub",
136 serde_json::json!({"type": "object"}),
137 )])
138 }
139 async fn invoke(
140 &self,
141 call: &ToolCallContext,
142 _control: &CallControl,
143 _store: Option<&dyn causa_kernel::ArtifactStore>,
144 ) -> Result<ToolResultPayload, ToolExecutionError> {
145 match &self.0 {
146 StubReply::Echo => Ok(ToolResultPayload::new(
147 call.call_block_id,
148 ToolResultStatus::Succeeded,
149 ToolOutput::new(call.input.arguments.clone()),
150 )),
151 StubReply::Error(e) => Err(e.clone()),
152 StubReply::Reported(status, output) => Ok(ToolResultPayload::new(
153 call.call_block_id,
154 status.clone(),
155 output.clone(),
156 )),
157 }
158 }
159 }
160
161 fn bridge(reply: StubReply) -> ToolBridge {
162 ToolBridge::new(
163 std::sync::Arc::new(StubSource(reply)),
164 ToolDefinition::new(
165 "mcp_stub_echo",
166 "stub",
167 serde_json::json!({"type": "object"}),
168 ),
169 )
170 }
171
172 fn call() -> ToolCallContext {
173 ToolCallContext::new(
174 crate::new_block_id(),
175 ToolCallPayload::new("mcp_stub_echo", serde_json::json!({"k": "v"})),
176 )
177 }
178
179 #[tokio::test]
180 async fn success_passes_through() {
181 let result = bridge(StubReply::Echo)
182 .execute(&call(), &ctrl(), None)
183 .await;
184 assert_eq!(result.status, ToolResultStatus::Succeeded);
185 assert_eq!(result.output.content, serde_json::json!({"k": "v"}));
186 }
187
188 #[test]
189 fn with_meta_attaches_typed_metadata() {
190 #[derive(Debug, PartialEq, Eq)]
191 struct Tag(&'static str);
192
193 let bridged = bridge(StubReply::Echo).with_meta(Tag("snapshot"));
194 assert_eq!(bridged.metadata().get::<Tag>(), Some(&Tag("snapshot")));
195 assert_eq!(bridged.metadata().len(), 1);
196 }
197
198 #[tokio::test]
199 async fn reported_status_and_output_pass_through() {
200 let output = ToolOutput::new(serde_json::json!({ "partial": "first half" }));
201 let call = call();
202 let result = bridge(StubReply::Reported(
203 ToolResultStatus::TimedOut,
204 output.clone(),
205 ))
206 .execute(&call, &ctrl(), None)
207 .await;
208 assert_eq!(result.call_block_id, call.call_block_id);
209 assert_eq!(result.status, ToolResultStatus::TimedOut);
210 assert_eq!(result.output, output);
211 assert!(
212 result.output.meta.is_none(),
213 "a source-reported result carries no bridge reason"
214 );
215 }
216
217 #[tokio::test]
218 async fn identical_dynamic_calls_keep_their_declaration_identity() {
219 let first = call();
220 let second = call();
221 assert_ne!(first.call_block_id, second.call_block_id);
222 let bridge = bridge(StubReply::Echo);
223 let control = ctrl();
224 let (a, b) = tokio::join!(
225 bridge.execute(&first, &control, None),
226 bridge.execute(&second, &control, None),
227 );
228 assert_eq!(a.call_block_id, first.call_block_id);
229 assert_eq!(b.call_block_id, second.call_block_id);
230 assert_eq!(a.output, b.output);
231 }
232
233 #[tokio::test]
234 async fn error_mapping_is_canonical() {
235 let cases: Vec<(ToolExecutionError, ToolResultStatus, Option<&str>)> = vec![
236 (
237 ToolExecutionError::TimedOut,
238 ToolResultStatus::UnknownOutcome,
239 Some("source_timed_out"),
240 ),
241 (
242 ToolExecutionError::Cancelled,
243 ToolResultStatus::UnknownOutcome,
244 Some("source_cancelled"),
245 ),
246 (
247 ToolExecutionError::UnknownTool("mcp_stub_nothere".into()),
248 ToolResultStatus::Rejected,
249 None,
250 ),
251 (
252 ToolExecutionError::Unavailable("down".into()),
253 ToolResultStatus::Failed,
254 None,
255 ),
256 (
257 ToolExecutionError::Protocol("bad frame".into()),
258 ToolResultStatus::Failed,
259 None,
260 ),
261 ];
262 for (error, expected, expected_reason) in cases {
263 let result = bridge(StubReply::Error(error.clone()))
264 .execute(&call(), &ctrl(), None)
265 .await;
266 assert_eq!(result.status, expected, "mapping for {error}");
267 let reason = result
268 .output
269 .meta
270 .as_ref()
271 .and_then(|meta| meta.extra.as_ref())
272 .and_then(|extra| extra.get("reason"))
273 .and_then(|reason| reason.as_str());
274 assert_eq!(reason, expected_reason, "reason for {error}");
275 assert!(
276 result
277 .output
278 .content
279 .to_string()
280 .contains(&error.to_string()),
281 "model-readable copy for {error}"
282 );
283 }
284 }
285
286 fn ctrl() -> CallControl {
287 CallControl::new(CancellationToken::new(), None)
288 }
289}