Skip to main content

causa_kernel/ports/
source.rs

1//! `DynamicToolSource` port — the seam external tool catalogs (MCP
2//! servers, plugin hosts) fill in so their tools can enter the model's
3//! `ToolSurface` next to local Rust tools.
4//!
5//! It is a kernel contract: third parties implement it against the facts
6//! crate alone (`causa-extension` depends only on this crate, exactly as
7//! `causa-provider` implements `ModelGateway`). The aggregation and
8//! dispatch logic that *consumes* the port lives in `causa_runtime`'s
9//! executor.
10
11use async_trait::async_trait;
12
13use crate::context::tool_data::ToolResultPayload;
14use crate::ports::control::CallControl;
15use crate::ports::tool::{ToolCallContext, ToolDefinition};
16
17/// One external tool catalog. Implementors own their connection, their
18/// naming (see the `mcp_{server_id}_{tool}` namespace convention in
19/// `causa-extension`), and their change notifications.
20#[async_trait]
21pub trait DynamicToolSource: Send + Sync {
22    /// Stable catalog identity — also the dispatch namespace key.
23    fn id(&self) -> &str;
24
25    /// Change signal for executor-side caching: bump whenever the tool
26    /// listing may have changed (e.g. MCP `tools/list_changed`). Consumers
27    /// may reuse a listing while the observed version remains unchanged.
28    /// This signal does not make version/list reads an atomic snapshot or
29    /// replace an invocation binding to concrete targets.
30    fn version(&self) -> u64 {
31        0
32    }
33
34    /// The current tool listing. Failure means acquisition failed, not an
35    /// empty catalog. The reference executor propagates refresh errors and
36    /// does not substitute an old listing or skip the source. Existing
37    /// successful bindings retain the targets they already acquired.
38    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError>;
39
40    /// Execute one call against the catalog. `call.input.tool_name` arrives in
41    /// the source's namespace; implementors de-namespace it (and reject
42    /// names outside their namespace). Sources return the recorded result
43    /// only — handling `UnknownOutcome` belongs to the execution consumer,
44    /// not source vocabulary.
45    async fn invoke(
46        &self,
47        call: &ToolCallContext,
48        control: &CallControl,
49    ) -> Result<ToolResultPayload, ToolExecutionError>;
50
51    /// Execute one call with the host's artifact store available for
52    /// media ingest: a source whose tools produce images can persist the
53    /// bytes via `store` and attach [`crate::context::block::MediaRef`]s
54    /// to the result's `ToolResultPayload.media` instead of degrading
55    /// them to text. Additive with a delegating default, so sources that
56    /// never produce media keep their existing `invoke` only.
57    async fn invoke_with_store(
58        &self,
59        call: &ToolCallContext,
60        control: &CallControl,
61        store: Option<&dyn crate::ports::tool::ArtifactStore>,
62    ) -> Result<ToolResultPayload, ToolExecutionError> {
63        let _ = store;
64        Self::invoke(self, call, control).await
65    }
66}
67
68/// Listing failure — the catalog as a whole is unusable right now.
69#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
70pub enum SourceError {
71    /// Connection failure or server offline; retryable (transient).
72    #[error("tool source unavailable: {0}")]
73    Unavailable(String),
74    /// Protocol-level failure; not retryable (permanent).
75    #[error("tool source protocol error: {0}")]
76    Protocol(String),
77}
78
79/// Single-call failure inside a source. The executor's tool adapter
80/// (`ToolBridge` in `causa_runtime`) turns every variant into a structured
81/// tool result the model reads; the status mapping lives there, not here.
82#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
83pub enum ToolExecutionError {
84    /// The call may or may not have run server-side — the outcome is
85    /// unknown, not failed (the executor marks it accordingly).
86    #[error("tool call timed out")]
87    TimedOut,
88    /// Cancelled before completion; the outcome is unknown.
89    #[error("tool call cancelled")]
90    Cancelled,
91    /// The name is not in this source's namespace.
92    #[error("unknown tool: {0}")]
93    UnknownTool(String),
94    /// Connection failure or server offline (transient).
95    #[error("tool source unavailable: {0}")]
96    Unavailable(String),
97    /// Protocol-level failure (permanent).
98    #[error("tool source protocol error: {0}")]
99    Protocol(String),
100}