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