Skip to main content

Crate sagashield

Crate sagashield 

Source
Expand description

SagaShield — ACID transactional Saga runtime, Step-0 security guardrail, and MCP server for autonomous AI agents.

Every tool call runs inside a saga: it is authorized by a deterministic StateMachine, logged to a SQLite write-ahead log (Wal), executed through a TransactionalTool, and — on failure — compensated in reverse order (Saga rollback). A SecurityGuard screens requests before the FSM check, the WAL write, or any side effect.

§Architecture

  • AgentKernel — single entry point: FSM + WAL + ToolRegistry + optional security guard, with automatic LIFO rollback.
  • Walsessions/actions tables, idempotency lookups, dangling session recovery, OTel-ready tracing spans.
  • SessionReplay — deterministic dry-run replay of a past saga with formal FSM re-validation (no side effects).
  • AuditExporter — session export as OpenTelemetry resourceSpans JSON.
  • McpServer — JSON-RPC 2.0 stdio server (sagashield-mcp binary).

§Quickstart

use std::sync::Arc;
use sagashield::{
    AgentKernel, KernelError, ToolContext, ToolOutput, ToolRegistry,
    TransactionalTool, Wal,
};
use serde_json::{Value, json};

struct GreetTool;

#[async_trait::async_trait]
impl TransactionalTool for GreetTool {
    fn id(&self) -> &'static str { "greet" }

    async fn execute(
        &self,
        _ctx: &ToolContext,
        args: Value,
    ) -> Result<ToolOutput, KernelError> {
        let name = args.get("name").and_then(Value::as_str).unwrap_or("world");
        Ok(ToolOutput::new(json!({ "greeting": format!("hello {name}") })))
    }

    async fn compensate(
        &self,
        _ctx: &ToolContext,
        _args: Value,
        _output: ToolOutput,
    ) -> Result<(), KernelError> {
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let wal = Arc::new(Wal::open_in_memory()?);
    let registry = ToolRegistry::new();
    registry.register(Arc::new(GreetTool))?;

    let mut kernel = AgentKernel::new(wal, registry);
    let session = uuid::Uuid::new_v4();
    kernel.begin_planning()?;
    kernel.begin_tool("greet")?;
    let out = kernel.execute_tool(&session, "greet", json!({ "name": "ada" }), None).await?;
    assert!(out.data["greeting"] == "hello ada");
    Ok(())
}

Re-exports§

pub use audit::AuditExporter;
pub use dispatcher::AgentKernel;
pub use dispatcher::ToolRegistry;
pub use error::KernelError;
pub use error::KernelResult;
pub use fsm::AgentEvent;
pub use fsm::AgentState;
pub use fsm::StateMachine;
pub use mcp::McpServer;
pub use replay::ReplayStep;
pub use replay::ReplayTimeline;
pub use replay::SessionReplay;
pub use security::SecurityGuard;
pub use security::SecurityPolicy;
pub use traits::TransactionalTool;
pub use types::ActionStatus;
pub use types::DlqEntry;
pub use types::PersistedAction;
pub use types::PruneReport;
pub use types::ToolContext;
pub use types::ToolOutput;
pub use wal::Wal;

Modules§

audit
Structured audit export in formato OpenTelemetry — ingestione pronta per Datadog, Honeycomb o Jaeger.
dispatcher
Dispatcher & punto di ingresso unificato — Fase 3.
error
Gestione rigorosa degli errori del kernel.
fsm
FSM Guardrail — Fase 2.
mcp
Server MCP (Model Context Protocol) — JSON-RPC 2.0 su stdio.
replay
Deterministic session replay dal WAL — dry-run senza side-effect.
security
Sandboxing & Security Guardrail — Fase 4.
tools
Tool reali per Fase 3: effetti collaterali veri + compensazioni vere.
traits
Contratto dei tool transazionali (Saga Pattern).
types
Tipi fondamentali del kernel (Fase 1).
wal
Write-Ahead Log (WAL) su SQLite — Saga Pattern (Fase 1).