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::context::tools::ToolDefinition;
15use crate::ports::control::CallControl;
16use crate::ports::tool::{ToolCallContext, ToolDescription};
17
18/// One external tool catalog. Implementors own their connection, their
19/// naming (see the `mcp_{server_id}_{tool}` namespace convention in
20/// `causa-extension`), and their change notifications.
21#[async_trait]
22pub trait DynamicToolSource: Send + Sync {
23    /// Stable catalog identity — also the dispatch namespace key.
24    fn id(&self) -> &str;
25
26    /// Change signal for executor-side caching: bump whenever the tool
27    /// listing may have changed (e.g. MCP `tools/list_changed`), including a
28    /// change in the tools' declared hints alone. Consumers
29    /// may reuse a listing while the observed version remains unchanged.
30    /// This signal does not make version/list reads an atomic snapshot or
31    /// replace an invocation binding to concrete targets.
32    fn version(&self) -> u64 {
33        0
34    }
35
36    /// The current tool listing. Failure means acquisition failed, not an
37    /// empty catalog.
38    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError>;
39
40    /// The current tool listing with each tool's declared hints. The
41    /// reference executor binds from this method, so a tool's definition and
42    /// hints come from the same listing. The default calls
43    /// [`DynamicToolSource::list`] and declares no hints; a source whose
44    /// catalog carries hints, such as MCP tool annotations, overrides it.
45    ///
46    /// Failure means acquisition failed, not an empty catalog. The reference
47    /// executor propagates refresh errors and does not substitute an old
48    /// listing or skip the source. Existing successful bindings retain the
49    /// targets and hints they already acquired.
50    async fn describe(&self) -> Result<Vec<ToolDescription>, SourceError> {
51        Ok(self
52            .list()
53            .await?
54            .into_iter()
55            .map(ToolDescription::new)
56            .collect())
57    }
58
59    /// Execute one call against the catalog. `call.input.tool_name` arrives in
60    /// the source's namespace; implementors de-namespace it (and reject
61    /// names outside their namespace). Sources return the recorded result
62    /// only — handling `UnknownOutcome` belongs to the execution consumer,
63    /// not source vocabulary.
64    ///
65    /// `store` is the host's artifact store when one is configured. A source
66    /// whose tools produce images persists the bytes there and attaches
67    /// [`crate::context::block::MediaRef`]s to the result's media instead of
68    /// degrading them to text; a source that never produces media ignores it.
69    async fn invoke(
70        &self,
71        call: &ToolCallContext,
72        control: &CallControl,
73        store: Option<&dyn crate::ports::tool::ArtifactStore>,
74    ) -> Result<ToolResultPayload, ToolExecutionError>;
75}
76
77/// Listing failure — the catalog as a whole is unusable right now.
78#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
79#[non_exhaustive]
80pub enum SourceError {
81    /// Connection failure or server offline; retryable (transient).
82    #[error("tool source unavailable: {0}")]
83    Unavailable(String),
84    /// Protocol-level failure; not retryable (permanent).
85    #[error("tool source protocol error: {0}")]
86    Protocol(String),
87}
88
89/// Single-call failure inside a source. The executor's tool adapter
90/// (`ToolBridge` in `causa_runtime`) turns every variant into a structured
91/// tool result the model reads; the status mapping lives there, not here.
92///
93/// Exhaustive on purpose: the runtime maps every variant to a result status, so a new one is a breaking change.
94#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
95pub enum ToolExecutionError {
96    /// The call may or may not have run server-side — the outcome is
97    /// unknown, not failed (the executor marks it accordingly).
98    #[error("tool call timed out")]
99    TimedOut,
100    /// Cancelled before completion; the outcome is unknown.
101    #[error("tool call cancelled")]
102    Cancelled,
103    /// The name is not in this source's namespace.
104    #[error("unknown tool: {0}")]
105    UnknownTool(String),
106    /// Connection failure or server offline (transient).
107    #[error("tool source unavailable: {0}")]
108    Unavailable(String),
109    /// Protocol-level failure (permanent).
110    #[error("tool source protocol error: {0}")]
111    Protocol(String),
112}