1use async_trait::async_trait;
13use causa_kernel::{
14 ArtifactStore, CallControl, DynamicToolSource, Tool, ToolCallContext, ToolDefinition,
15 ToolExecutionError, ToolOutput, ToolResultPayload, ToolResultStatus,
16};
17
18pub struct ToolBridge {
34 source: std::sync::Arc<dyn DynamicToolSource>,
35 definition: ToolDefinition,
36}
37
38impl ToolBridge {
39 pub fn new(source: std::sync::Arc<dyn DynamicToolSource>, definition: ToolDefinition) -> Self {
41 Self { source, definition }
42 }
43}
44
45#[async_trait]
46impl Tool for ToolBridge {
47 fn definition(&self) -> ToolDefinition {
48 self.definition.clone()
49 }
50
51 async fn execute(
52 &self,
53 ctx: &ToolCallContext,
54 control: &CallControl,
55 store: Option<&dyn ArtifactStore>,
56 ) -> ToolResultPayload {
57 match self.source.invoke(ctx, control, store).await {
58 Ok(result) => result,
59 Err(e) => ToolResultPayload::new(
60 ctx.call_block_id,
61 match &e {
62 ToolExecutionError::TimedOut | ToolExecutionError::Cancelled => {
63 ToolResultStatus::UnknownOutcome
64 }
65 ToolExecutionError::UnknownTool(_) => ToolResultStatus::Rejected,
66 ToolExecutionError::Unavailable(_) | ToolExecutionError::Protocol(_) => {
67 ToolResultStatus::Failed
68 }
69 },
70 ToolOutput::new(serde_json::json!({ "error": e.to_string() })),
71 ),
72 }
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 use causa_kernel::{CancellationToken, ToolCallPayload};
80
81 struct StubSource(Option<ToolExecutionError>);
84
85 #[async_trait]
86 impl DynamicToolSource for StubSource {
87 fn id(&self) -> &str {
88 "stub"
89 }
90 async fn list(&self) -> Result<Vec<ToolDefinition>, causa_kernel::SourceError> {
91 Ok(vec![ToolDefinition::new(
92 "mcp_stub_echo",
93 "stub",
94 serde_json::json!({"type": "object"}),
95 )])
96 }
97 async fn invoke(
98 &self,
99 call: &ToolCallContext,
100 _control: &CallControl,
101 _store: Option<&dyn causa_kernel::ArtifactStore>,
102 ) -> Result<ToolResultPayload, ToolExecutionError> {
103 match &self.0 {
104 Some(e) => Err(e.clone()),
105 None => Ok(ToolResultPayload::new(
106 call.call_block_id,
107 ToolResultStatus::Succeeded,
108 ToolOutput::new(call.input.arguments.clone()),
109 )),
110 }
111 }
112 }
113
114 fn bridge(error: Option<ToolExecutionError>) -> ToolBridge {
115 ToolBridge::new(
116 std::sync::Arc::new(StubSource(error)),
117 ToolDefinition::new(
118 "mcp_stub_echo",
119 "stub",
120 serde_json::json!({"type": "object"}),
121 ),
122 )
123 }
124
125 fn call() -> ToolCallContext {
126 ToolCallContext::new(
127 crate::new_block_id(),
128 ToolCallPayload::new("mcp_stub_echo", serde_json::json!({"k": "v"})),
129 )
130 }
131
132 #[tokio::test]
133 async fn success_passes_through() {
134 let result = bridge(None).execute(&call(), &ctrl(), None).await;
135 assert_eq!(result.status, ToolResultStatus::Succeeded);
136 assert_eq!(result.output.content, serde_json::json!({"k": "v"}));
137 }
138
139 #[tokio::test]
140 async fn identical_dynamic_calls_keep_their_declaration_identity() {
141 let first = call();
142 let second = call();
143 assert_ne!(first.call_block_id, second.call_block_id);
144 let bridge = bridge(None);
145 let control = ctrl();
146 let (a, b) = tokio::join!(
147 bridge.execute(&first, &control, None),
148 bridge.execute(&second, &control, None),
149 );
150 assert_eq!(a.call_block_id, first.call_block_id);
151 assert_eq!(b.call_block_id, second.call_block_id);
152 assert_eq!(a.output, b.output);
153 }
154
155 #[tokio::test]
156 async fn error_mapping_is_canonical() {
157 let cases: Vec<(ToolExecutionError, ToolResultStatus)> = vec![
158 (
159 ToolExecutionError::TimedOut,
160 ToolResultStatus::UnknownOutcome,
161 ),
162 (
163 ToolExecutionError::Cancelled,
164 ToolResultStatus::UnknownOutcome,
165 ),
166 (
167 ToolExecutionError::UnknownTool("mcp_stub_nothere".into()),
168 ToolResultStatus::Rejected,
169 ),
170 (
171 ToolExecutionError::Unavailable("down".into()),
172 ToolResultStatus::Failed,
173 ),
174 (
175 ToolExecutionError::Protocol("bad frame".into()),
176 ToolResultStatus::Failed,
177 ),
178 ];
179 for (error, expected) in cases {
180 let result = bridge(Some(error.clone()))
181 .execute(&call(), &ctrl(), None)
182 .await;
183 assert_eq!(result.status, expected, "mapping for {error}");
184 assert!(
185 result
186 .output
187 .content
188 .to_string()
189 .contains(&error.to_string()),
190 "model-readable copy for {error}"
191 );
192 }
193 }
194
195 fn ctrl() -> CallControl {
196 CallControl::new(CancellationToken::new(), None)
197 }
198}