stackdeck-mcp-writes 0.1.0

Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies.
Documentation
use std::fmt;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCode {
    Validation,
    Forbidden,
    Conflict,
    InProgress,
    Expired,
    ReplayUnavailable,
    OutcomeUnknown,
    ApprovalRequired,
    StoreError,
}

impl ErrorCode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Validation => "validation",
            Self::Forbidden => "forbidden",
            Self::Conflict => "conflict",
            Self::InProgress => "in_progress",
            Self::Expired => "expired",
            Self::ReplayUnavailable => "replay_unavailable",
            Self::OutcomeUnknown => "outcome_unknown",
            Self::ApprovalRequired => "approval_required",
            Self::StoreError => "store_error",
        }
    }

    pub fn http_status(self) -> u16 {
        match self {
            Self::Validation => 400,
            Self::Forbidden => 403,
            Self::Conflict => 409,
            Self::InProgress => 409,
            Self::Expired => 409,
            Self::ReplayUnavailable => 409,
            Self::OutcomeUnknown => 500,
            Self::ApprovalRequired => 428,
            Self::StoreError => 503,
        }
    }

    pub fn default_retryable(self) -> bool {
        matches!(self, Self::InProgress | Self::StoreError)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteSafetyError {
    pub code: ErrorCode,
    pub message: String,
    pub status: u16,
    pub retryable: bool,
    pub reason: Option<&'static str>,
    pub retry_after_ms: Option<i64>,
}

#[derive(Debug)]
pub enum HandlerError<E> {
    /// The handler stopped before attempting any external side effect.
    BeforeEffect(E),
    /// The handler may have attempted an external side effect.
    MayHaveRun(E),
}

impl WriteSafetyError {
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            status: code.http_status(),
            retryable: code.default_retryable(),
            reason: None,
            retry_after_ms: None,
        }
    }

    pub fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    pub fn with_reason(mut self, reason: &'static str) -> Self {
        self.reason = Some(reason);
        self
    }

    /// Mark a handler error only when no external side effect was attempted.
    pub fn before_effect(self) -> HandlerError<Self> {
        HandlerError::BeforeEffect(self)
    }
}

impl fmt::Display for WriteSafetyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code.as_str(), self.message)
    }
}

impl std::error::Error for WriteSafetyError {}