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