Skip to main content

causa_runtime/composition/
bridge.rs

1//! Implementation of the composition component.
2
3use async_trait::async_trait;
4use causa_kernel::{
5    ArtifactStore, CallControl, DynamicToolSource, Tool, ToolCallContext, ToolDefinition,
6    ToolExecutionError, ToolOutput, ToolResultPayload, ToolResultStatus,
7};
8
9/// A single dynamic-source tool exposed through the plain [`Tool`]
10/// interface. The bridge routes `execute` to
11/// [`DynamicToolSource::invoke_with_store`] (the source de-namespaces the
12/// call; the host's artifact store is forwarded for media ingest) and
13/// maps invoke errors onto structured results: a timeout or cancellation
14/// is `UnknownOutcome` (the call may have run server-side), an
15/// out-of-catalog name is `Rejected`, unavailability and protocol
16/// failures are `Failed` with a model-readable message. The bridge returns
17/// the recorded result only — what an `UnknownOutcome` result does next is
18/// caller's responsibility (the runner commits the complete batch and
19/// stops; a standalone bridge consumer chooses how to use its result).
20///
21/// Snapshot semantics: the [`ToolDefinition`] is fixed at construction —
22/// listing changes after bridging are not picked up. For live catalogs
23/// prefer `ToolExecutor::register_dynamic`.
24pub struct ToolBridge {
25    source: std::sync::Arc<dyn DynamicToolSource>,
26    definition: ToolDefinition,
27}
28
29impl ToolBridge {
30    /// Bridge one tool definition of `source` into a static `Tool`.
31    pub fn new(source: std::sync::Arc<dyn DynamicToolSource>, definition: ToolDefinition) -> Self {
32        Self { source, definition }
33    }
34}
35
36#[async_trait]
37impl Tool for ToolBridge {
38    fn definition(&self) -> ToolDefinition {
39        self.definition.clone()
40    }
41
42    async fn execute(&self, ctx: &ToolCallContext, control: &CallControl) -> ToolResultPayload {
43        self.execute_with_store(ctx, control, None).await
44    }
45
46    async fn execute_with_store(
47        &self,
48        ctx: &ToolCallContext,
49        control: &CallControl,
50        store: Option<&dyn ArtifactStore>,
51    ) -> ToolResultPayload {
52        match self.source.invoke_with_store(ctx, control, store).await {
53            Ok(result) => result,
54            Err(e) => ToolResultPayload {
55                call_block_id: ctx.call_block_id,
56                status: match &e {
57                    ToolExecutionError::TimedOut | ToolExecutionError::Cancelled => {
58                        ToolResultStatus::UnknownOutcome
59                    }
60                    ToolExecutionError::UnknownTool(_) => ToolResultStatus::Rejected,
61                    ToolExecutionError::Unavailable(_) | ToolExecutionError::Protocol(_) => {
62                        ToolResultStatus::Failed
63                    }
64                },
65                output: ToolOutput::new(serde_json::json!({ "error": e.to_string() })),
66                media: Vec::new(),
67                notes: Vec::new(),
68            },
69        }
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use causa_kernel::{CancellationToken, ToolCallPayload};
77
78    /// Source stub: `None` succeeds with the call's arguments as output;
79    /// `Some` yields the (clonable) error.
80    struct StubSource(Option<ToolExecutionError>);
81
82    #[async_trait]
83    impl DynamicToolSource for StubSource {
84        fn id(&self) -> &str {
85            "stub"
86        }
87        async fn list(&self) -> Result<Vec<ToolDefinition>, causa_kernel::SourceError> {
88            Ok(vec![ToolDefinition {
89                name: "mcp_stub_echo".into(),
90                description: "stub".into(),
91                parameters: serde_json::json!({"type": "object"}),
92            }])
93        }
94        async fn invoke(
95            &self,
96            call: &ToolCallContext,
97            _control: &CallControl,
98        ) -> Result<ToolResultPayload, ToolExecutionError> {
99            match &self.0 {
100                Some(e) => Err(e.clone()),
101                None => Ok(ToolResultPayload {
102                    call_block_id: call.call_block_id,
103                    status: ToolResultStatus::Succeeded,
104                    output: ToolOutput::new(call.input.arguments.clone()),
105                    media: Vec::new(),
106                    notes: Vec::new(),
107                }),
108            }
109        }
110    }
111
112    fn bridge(error: Option<ToolExecutionError>) -> ToolBridge {
113        ToolBridge::new(
114            std::sync::Arc::new(StubSource(error)),
115            ToolDefinition {
116                name: "mcp_stub_echo".into(),
117                description: "stub".into(),
118                parameters: serde_json::json!({"type": "object"}),
119            },
120        )
121    }
122
123    fn call() -> ToolCallContext {
124        ToolCallContext {
125            call_block_id: crate::new_block_id(),
126            input: ToolCallPayload {
127                tool_name: "mcp_stub_echo".into(),
128                arguments: serde_json::json!({"k": "v"}),
129            },
130            result_notes: Vec::new(),
131        }
132    }
133
134    #[tokio::test]
135    async fn success_passes_through() {
136        let result = bridge(None).execute(&call(), &ctrl()).await;
137        assert_eq!(result.status, ToolResultStatus::Succeeded);
138        assert_eq!(result.output.content, serde_json::json!({"k": "v"}));
139    }
140
141    #[tokio::test]
142    async fn identical_dynamic_calls_keep_their_declaration_identity() {
143        let first = call();
144        let second = call();
145        assert_ne!(first.call_block_id, second.call_block_id);
146        let bridge = bridge(None);
147        let control = ctrl();
148        let (a, b) = tokio::join!(
149            bridge.execute(&first, &control),
150            bridge.execute(&second, &control),
151        );
152        assert_eq!(a.call_block_id, first.call_block_id);
153        assert_eq!(b.call_block_id, second.call_block_id);
154        assert_eq!(a.output, b.output);
155    }
156
157    #[tokio::test]
158    async fn error_mapping_is_canonical() {
159        let cases: Vec<(ToolExecutionError, ToolResultStatus)> = vec![
160            (
161                ToolExecutionError::TimedOut,
162                ToolResultStatus::UnknownOutcome,
163            ),
164            (
165                ToolExecutionError::Cancelled,
166                ToolResultStatus::UnknownOutcome,
167            ),
168            (
169                ToolExecutionError::UnknownTool("mcp_stub_nothere".into()),
170                ToolResultStatus::Rejected,
171            ),
172            (
173                ToolExecutionError::Unavailable("down".into()),
174                ToolResultStatus::Failed,
175            ),
176            (
177                ToolExecutionError::Protocol("bad frame".into()),
178                ToolResultStatus::Failed,
179            ),
180        ];
181        for (error, expected) in cases {
182            let result = bridge(Some(error.clone())).execute(&call(), &ctrl()).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}