causa-kernel 0.0.6

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;

/// 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`). 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. The reference executor propagates refresh errors and
    /// does not substitute an old listing or skip the source. Existing
    /// successful bindings retain the targets they already acquired.
    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError>;

    /// 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). Sources return the recorded result
    /// only — handling `UnknownOutcome` belongs to the execution consumer,
    /// not source vocabulary.
    ///
    /// `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.
///
/// 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 {
    /// The call may or may not have run server-side — the outcome is
    /// unknown, not failed (the executor marks it accordingly).
    #[error("tool call timed out")]
    TimedOut,
    /// Cancelled before completion; the outcome is unknown.
    #[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),
}