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 (`ToolExecutor::execute_with_limits` wraps a dynamic call in a
6//! bridge so it runs the same static path as a local tool) and the
7//! canonical home of the `ToolExecutionError` → status mapping. Hosts that
8//! prefer snapshot semantics (list once, register as static tools) reuse
9//! the same bridge directly; for live catalogs prefer
10//! `ToolExecutor::register_dynamic`.
11
12use async_trait::async_trait;
13use causa_kernel::ToolCallPayload;
14use causa_kernel::{
15    ArtifactStore, CallControl, DynamicToolSource, Tool, ToolCallContext, ToolDefinition,
16    ToolExecutionError, ToolOutput, ToolResultPayload, ToolResultStatus,
17};
18
19/// A single dynamic-source tool exposed through the plain [`Tool`]
20/// interface. The bridge routes `execute` to
21/// [`DynamicToolSource::invoke_with_store`] (the source de-namespaces the
22/// call; the host's artifact store is forwarded for media ingest) and
23/// maps invoke errors onto structured results: a timeout or cancellation
24/// is `UnknownOutcome` (the call may have run server-side), an
25/// out-of-catalog name is `Rejected`, unavailability and protocol
26/// failures are `Failed` with a model-readable message. The bridge returns
27/// the recorded result only — what an `UnknownOutcome` result does next is
28/// the caller's configuration (the executor resolves it; a standalone
29/// bridge consumer chooses).
30///
31/// Snapshot semantics: the [`ToolDefinition`] is fixed at construction —
32/// listing changes after bridging are not picked up. For live catalogs
33/// prefer `ToolExecutor::register_dynamic`.
34pub struct ToolBridge {
35    source: std::sync::Arc<dyn DynamicToolSource>,
36    definition: ToolDefinition,
37}
38
39impl ToolBridge {
40    /// Bridge one tool definition of `source` into a static `Tool`.
41    pub fn new(source: std::sync::Arc<dyn DynamicToolSource>, definition: ToolDefinition) -> Self {
42        Self { source, definition }
43    }
44}
45
46#[async_trait]
47impl Tool for ToolBridge {
48    fn definition(&self) -> ToolDefinition {
49        self.definition.clone()
50    }
51
52    async fn execute(&self, ctx: &ToolCallContext, control: &CallControl) -> ToolResultPayload {
53        self.execute_with_store(ctx, control, None).await
54    }
55
56    async fn execute_with_store(
57        &self,
58        ctx: &ToolCallContext,
59        control: &CallControl,
60        store: Option<&dyn ArtifactStore>,
61    ) -> ToolResultPayload {
62        let payload = ToolCallPayload {
63            call_id: ctx.call_id.clone(),
64            tool_name: ctx.tool_name.clone(),
65            arguments: ctx.arguments.clone(),
66        };
67        match self
68            .source
69            .invoke_with_store(&payload, control, store)
70            .await
71        {
72            Ok(result) => result,
73            Err(e) => ToolResultPayload {
74                call_id: ctx.call_id.clone(),
75                status: match &e {
76                    ToolExecutionError::TimedOut | ToolExecutionError::Cancelled => {
77                        ToolResultStatus::UnknownOutcome
78                    }
79                    ToolExecutionError::UnknownTool(_) => ToolResultStatus::Rejected,
80                    ToolExecutionError::Unavailable(_) | ToolExecutionError::Protocol(_) => {
81                        ToolResultStatus::Failed
82                    }
83                },
84                output: ToolOutput::new(serde_json::json!({ "error": e.to_string() })),
85                media: Vec::new(),
86            },
87        }
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use causa_kernel::{CancellationToken, ToolCallId};
95
96    /// Source stub: `None` succeeds with the call's arguments as output;
97    /// `Some` yields the (clonable) error.
98    struct StubSource(Option<ToolExecutionError>);
99
100    #[async_trait]
101    impl DynamicToolSource for StubSource {
102        fn id(&self) -> &str {
103            "stub"
104        }
105        async fn list(&self) -> Result<Vec<ToolDefinition>, causa_kernel::SourceError> {
106            Ok(vec![ToolDefinition {
107                name: "mcp_stub_echo".into(),
108                description: "stub".into(),
109                parameters: serde_json::json!({"type": "object"}),
110            }])
111        }
112        async fn invoke(
113            &self,
114            call: &ToolCallPayload,
115            _control: &CallControl,
116        ) -> Result<ToolResultPayload, ToolExecutionError> {
117            match &self.0 {
118                Some(e) => Err(e.clone()),
119                None => Ok(ToolResultPayload {
120                    call_id: call.call_id.clone(),
121                    status: ToolResultStatus::Succeeded,
122                    output: ToolOutput::new(call.arguments.clone()),
123                    media: Vec::new(),
124                }),
125            }
126        }
127    }
128
129    fn bridge(error: Option<ToolExecutionError>) -> ToolBridge {
130        ToolBridge::new(
131            std::sync::Arc::new(StubSource(error)),
132            ToolDefinition {
133                name: "mcp_stub_echo".into(),
134                description: "stub".into(),
135                parameters: serde_json::json!({"type": "object"}),
136            },
137        )
138    }
139
140    fn call() -> ToolCallContext {
141        ToolCallContext {
142            call_id: ToolCallId("call-1".into()),
143            tool_name: "mcp_stub_echo".into(),
144            arguments: serde_json::json!({"k": "v"}),
145        }
146    }
147
148    #[tokio::test]
149    async fn success_passes_through() {
150        let result = bridge(None).execute(&call(), &ctrl()).await;
151        assert_eq!(result.status, ToolResultStatus::Succeeded);
152        assert_eq!(result.output.content, serde_json::json!({"k": "v"}));
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())).execute(&call(), &ctrl()).await;
181            assert_eq!(result.status, expected, "mapping for {error}");
182            assert!(
183                result
184                    .output
185                    .content
186                    .to_string()
187                    .contains(&error.to_string()),
188                "model-readable copy for {error}"
189            );
190        }
191    }
192
193    fn ctrl() -> CallControl {
194        CallControl::new(CancellationToken::new(), None)
195    }
196}