causa-kernel 0.1.5

Causa kernel — primitive facts (ContextBlock) and behavior contracts (ports)
Documentation
//! `DynamicToolSource` port — the seam external tool catalogs (MCP
//! servers, plugin hosts) fill in so their tools can enter the model's
//! `ToolSurface` next to local Rust tools.
//!
//! It is a kernel contract: third parties implement it against the facts
//! crate alone (`causa-extension` depends only on this crate, exactly as
//! `causa-provider` implements `ModelGateway`). The aggregation and
//! dispatch logic that *consumes* the port lives in `causa_runtime`'s
//! executor.

use async_trait::async_trait;

use crate::context::tool_data::ToolResultPayload;
use crate::context::tools::ToolDefinition;
use crate::ports::control::CallControl;
use crate::ports::tool::{ToolCallContext, ToolDescription};

/// One external tool catalog. Implementors own their connection, their
/// naming (see the `mcp_{server_id}_{tool}` namespace convention in
/// `causa-extension`), and their change notifications.
#[async_trait]
pub trait DynamicToolSource: Send + Sync {
    /// Stable catalog identity — also the dispatch namespace key.
    fn id(&self) -> &str;

    /// Change signal for executor-side caching: bump whenever the tool
    /// listing may have changed (e.g. MCP `tools/list_changed`), including a
    /// change in the tools' declared hints alone. Consumers
    /// may reuse a listing while the observed version remains unchanged.
    /// This signal does not make version/list reads an atomic snapshot or
    /// replace an invocation binding to concrete targets.
    fn version(&self) -> u64 {
        0
    }

    /// The current tool listing. Failure means acquisition failed, not an
    /// empty catalog.
    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError>;

    /// The current tool listing with each tool's declared hints. The
    /// reference executor binds from this method, so a tool's definition and
    /// hints come from the same listing. The default calls
    /// [`DynamicToolSource::list`] and declares no hints; a source whose
    /// catalog carries hints, such as MCP tool annotations, overrides it.
    ///
    /// Failure means acquisition failed, not an empty catalog. The reference
    /// executor propagates refresh errors and does not substitute an old
    /// listing or skip the source. Existing successful bindings retain the
    /// targets and hints they already acquired.
    async fn describe(&self) -> Result<Vec<ToolDescription>, SourceError> {
        Ok(self
            .list()
            .await?
            .into_iter()
            .map(ToolDescription::new)
            .collect())
    }

    /// Execute one call against the catalog. `call.input.tool_name` arrives in
    /// the source's namespace; implementors de-namespace it (and reject
    /// names outside their namespace). A source that can report the terminal
    /// status returns `Ok` with it, including `TimedOut` or `Cancelled`
    /// carrying any partial output; the timeout and cancellation errors below
    /// mean no result was observed, and the bridge records `UnknownOutcome`
    /// for them. A source must not synthesize `UnknownOutcome` itself: the
    /// bridge passes an `Ok` result through unchanged, so a source without a
    /// result returns an error and lets the bridge map it.
    ///
    /// `store` is the host's artifact store when one is configured. A source
    /// whose tools produce images persists the bytes there and attaches
    /// [`crate::context::block::MediaRef`]s to the result's media instead of
    /// degrading them to text; a source that never produces media ignores it.
    async fn invoke(
        &self,
        call: &ToolCallContext,
        control: &CallControl,
        store: Option<&dyn crate::ports::tool::ArtifactStore>,
    ) -> Result<ToolResultPayload, ToolExecutionError>;
}

/// Listing failure — the catalog as a whole is unusable right now.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SourceError {
    /// Connection failure or server offline; retryable (transient).
    #[error("tool source unavailable: {0}")]
    Unavailable(String),
    /// Protocol-level failure; not retryable (permanent).
    #[error("tool source protocol error: {0}")]
    Protocol(String),
}

/// Single-call failure inside a source. The executor's tool adapter
/// (`ToolBridge` in `causa_runtime`) turns every variant into a structured
/// tool result the model reads; the status mapping lives there, not here.
///
/// A source that can report what happened returns `Ok` with the matching
/// [`ToolResultStatus`](crate::context::tool_data::ToolResultStatus),
/// including `TimedOut` or `Cancelled` with any partial output. The timeout
/// and cancellation variants below mean the source observed no result at
/// all: the bridge records
/// [`UnknownOutcome`](crate::context::tool_data::ToolResultStatus::UnknownOutcome).
///
/// Exhaustive on purpose: the runtime maps every variant to a result status, so a new one is a breaking change.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ToolExecutionError {
    /// No result was observed before the call's time budget ran out. A source
    /// that can report a timeout returns `Ok` with a
    /// [`TimedOut`](crate::context::tool_data::ToolResultStatus::TimedOut)
    /// result carrying any partial output instead; this error maps to
    /// `UnknownOutcome`.
    #[error("tool call timed out")]
    TimedOut,
    /// No result was observed because the call was cancelled. A source whose
    /// tool reports its own cancellation returns `Ok` with a
    /// [`Cancelled`](crate::context::tool_data::ToolResultStatus::Cancelled)
    /// result carrying any partial output instead; this error maps to
    /// `UnknownOutcome`.
    #[error("tool call cancelled")]
    Cancelled,
    /// The name is not in this source's namespace.
    #[error("unknown tool: {0}")]
    UnknownTool(String),
    /// Connection failure or server offline (transient).
    #[error("tool source unavailable: {0}")]
    Unavailable(String),
    /// Protocol-level failure (permanent).
    #[error("tool source protocol error: {0}")]
    Protocol(String),
}