Skip to main content

causa_runtime/
composition.rs

1//! Composition layer — adapters bridging kernel ports into each other.
2//!
3//! [`ToolBridge`] adapts a `(DynamicToolSource, ToolDefinition)`
4//! pair into a plain [`Tool`]. It is the executor's dynamic-dispatch
5//! adapter (an invocation binding wraps a dynamic definition in a
6//! bridge so it runs the same path as a local tool) and the
7//! canonical home of the `ToolExecutionError` → status mapping. Hosts that
8//! prefer snapshot semantics (describe once, register as static tools) reuse
9//! the same bridge directly, passing each tool's hints to
10//! [`ToolBridge::with_hints`]; for live catalogs prefer
11//! `ToolExecutor::register_dynamic`.
12
13use 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
20/// A single dynamic-source tool exposed through the plain [`Tool`]
21/// interface. The bridge routes `execute` to
22/// [`DynamicToolSource::invoke`] (the source de-namespaces the
23/// call; the host's artifact store is forwarded for media ingest) and
24/// maps invoke errors onto structured results: a timeout or cancellation
25/// is `UnknownOutcome` (the call may have run server-side), tagged with
26/// `meta.extra.reason` = `"source_timed_out"` or `"source_cancelled"`; an
27/// out-of-catalog name is `Rejected`, unavailability and protocol
28/// failures are `Failed` with a model-readable message, and those mappings
29/// carry no reason. The bridge returns
30/// the recorded result only — what an `UnknownOutcome` result does next is
31/// caller's responsibility (the runner commits the complete batch and
32/// stops; a standalone bridge consumer chooses how to use its result).
33///
34/// Snapshot semantics: the [`ToolDefinition`] and [`ToolHints`] are fixed
35/// at construction — listing changes after bridging are not picked up. For
36/// live catalogs prefer `ToolExecutor::register_dynamic`.
37pub struct ToolBridge {
38    source: std::sync::Arc<dyn DynamicToolSource>,
39    definition: ToolDefinition,
40    hints: ToolHints,
41}
42
43impl ToolBridge {
44    /// Bridge one tool definition of `source` into a static `Tool` that
45    /// declares no hints.
46    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    /// Sets the hints the bridged tool declares, usually the ones its
55    /// source listed with the definition.
56    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                // The source observed no result. A timeout or cancellation
82                // records why, aligning with the executor's reasons.
83                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    /// What the source stub reports: an echoed success, a (clonable) error,
111    /// or a terminal status and output of its own.
112    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}