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). A source that can report the terminal
62 /// status returns `Ok` with it, including `TimedOut` or `Cancelled`
63 /// carrying any partial output; the timeout and cancellation errors below
64 /// mean no result was observed, and the bridge records `UnknownOutcome`
65 /// for them. A source must not synthesize `UnknownOutcome` itself: the
66 /// bridge passes an `Ok` result through unchanged, so a source without a
67 /// result returns an error and lets the bridge map it.
68 ///
69 /// `store` is the host's artifact store when one is configured. A source
70 /// whose tools produce images persists the bytes there and attaches
71 /// [`crate::context::block::MediaRef`]s to the result's media instead of
72 /// degrading them to text; a source that never produces media ignores it.
73 async fn invoke(
74 &self,
75 call: &ToolCallContext,
76 control: &CallControl,
77 store: Option<&dyn crate::ports::tool::ArtifactStore>,
78 ) -> Result<ToolResultPayload, ToolExecutionError>;
79}
80
81/// Listing failure — the catalog as a whole is unusable right now.
82#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
83#[non_exhaustive]
84pub enum SourceError {
85 /// Connection failure or server offline; retryable (transient).
86 #[error("tool source unavailable: {0}")]
87 Unavailable(String),
88 /// Protocol-level failure; not retryable (permanent).
89 #[error("tool source protocol error: {0}")]
90 Protocol(String),
91}
92
93/// Single-call failure inside a source. The executor's tool adapter
94/// (`ToolBridge` in `causa_runtime`) turns every variant into a structured
95/// tool result the model reads; the status mapping lives there, not here.
96///
97/// A source that can report what happened returns `Ok` with the matching
98/// [`ToolResultStatus`](crate::context::tool_data::ToolResultStatus),
99/// including `TimedOut` or `Cancelled` with any partial output. The timeout
100/// and cancellation variants below mean the source observed no result at
101/// all: the bridge records
102/// [`UnknownOutcome`](crate::context::tool_data::ToolResultStatus::UnknownOutcome).
103///
104/// Exhaustive on purpose: the runtime maps every variant to a result status, so a new one is a breaking change.
105#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
106pub enum ToolExecutionError {
107 /// No result was observed before the call's time budget ran out. A source
108 /// that can report a timeout returns `Ok` with a
109 /// [`TimedOut`](crate::context::tool_data::ToolResultStatus::TimedOut)
110 /// result carrying any partial output instead; this error maps to
111 /// `UnknownOutcome`.
112 #[error("tool call timed out")]
113 TimedOut,
114 /// No result was observed because the call was cancelled. A source whose
115 /// tool reports its own cancellation returns `Ok` with a
116 /// [`Cancelled`](crate::context::tool_data::ToolResultStatus::Cancelled)
117 /// result carrying any partial output instead; this error maps to
118 /// `UnknownOutcome`.
119 #[error("tool call cancelled")]
120 Cancelled,
121 /// The name is not in this source's namespace.
122 #[error("unknown tool: {0}")]
123 UnknownTool(String),
124 /// Connection failure or server offline (transient).
125 #[error("tool source unavailable: {0}")]
126 Unavailable(String),
127 /// Protocol-level failure (permanent).
128 #[error("tool source protocol error: {0}")]
129 Protocol(String),
130}