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::collections::HashMap;
use std::fmt::Write as _;
use std::sync::Mutex;

use crate::error::{ErrorCode, WriteSafetyError};
use crate::json::{JsonValue, MAX_SAFE_INTEGER};

pub const DEFAULT_SPENT_KEY_RETENTION_MS: i64 = 604_800_000;

pub const SQLITE_SCHEMA_SQL: &str = "CREATE TABLE IF NOT EXISTS mcp_write_receipts (
  scope TEXT NOT NULL,
  operation TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('in_progress', 'succeeded')),
  claim_token TEXT,
  input_hash TEXT NOT NULL,
  receipt_json TEXT,
  created_at_ms INTEGER NOT NULL,
  completed_at_ms INTEGER,
  lease_expires_at_ms INTEGER,
  expires_at_ms INTEGER,
  retain_until_ms INTEGER,
  PRIMARY KEY (scope, operation, idempotency_key)
);
CREATE INDEX IF NOT EXISTS mcp_write_receipts_expires_at_idx ON mcp_write_receipts(expires_at_ms);";

pub const POSTGRES_SCHEMA_SQL: &str = "CREATE TABLE IF NOT EXISTS mcp_write_receipts (
  scope TEXT NOT NULL,
  operation TEXT NOT NULL,
  idempotency_key TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('in_progress', 'succeeded')),
  claim_token TEXT,
  input_hash TEXT NOT NULL,
  receipt_json JSONB,
  created_at_ms BIGINT NOT NULL,
  completed_at_ms BIGINT,
  lease_expires_at_ms BIGINT,
  expires_at_ms BIGINT,
  retain_until_ms BIGINT,
  PRIMARY KEY (scope, operation, idempotency_key)
);
CREATE INDEX IF NOT EXISTS expiry_mcp_write_receipts ON mcp_write_receipts(expires_at_ms);";

pub const REDIS_CLAIM_LUA: &str = concat!("local action = 'claim'\n", include_str!("redis.lua"));
pub const REDIS_COMPLETE_LUA: &str = concat!("local action = 'complete'\n", include_str!("redis.lua"));
pub const REDIS_RELEASE_LUA: &str = concat!("local action = 'release'\n", include_str!("redis.lua"));
pub const REDIS_EXTEND_LEASE_LUA: &str = concat!("local action = 'extend'\n", include_str!("redis.lua"));

pub fn build_redis_store_key(prefix: &str, scope: &str, operation: &str, idempotency_key: &str) -> String {
    let mut output = prefix.to_owned();
    for (index, value) in [scope, operation, idempotency_key].iter().enumerate() {
        if index > 0 {
            output.push(':');
        }
        for byte in value.bytes() {
            if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
                output.push(char::from(byte));
            } else {
                write!(output, "%{byte:02X}").expect("write to String");
            }
        }
    }
    output
}

pub(crate) fn timestamp(value: i64) -> Result<i64, WriteSafetyError> {
    if !(0..=MAX_SAFE_INTEGER).contains(&value) {
        return Err(WriteSafetyError::new(ErrorCode::Validation, "Timestamp must be a non-negative safe integer."));
    }
    Ok(value)
}

pub(crate) fn duration(value: i64) -> Result<i64, WriteSafetyError> {
    if !(1..=MAX_SAFE_INTEGER).contains(&value) {
        return Err(WriteSafetyError::new(ErrorCode::Validation, "Duration must be a positive safe integer."));
    }
    Ok(value)
}

pub(crate) fn deadline(now: i64, value: i64) -> Result<i64, WriteSafetyError> {
    timestamp(timestamp(now)? + duration(value)?)
}

pub(crate) fn retention(ttl: i64, retain: i64) -> Result<i64, WriteSafetyError> {
    if duration(retain)? < duration(ttl)? {
        return Err(WriteSafetyError::new(ErrorCode::Validation, "spent_key_retention_ms must be greater than or equal to ttl_ms."));
    }
    Ok(retain)
}

#[derive(Debug, Clone, PartialEq)]
pub struct InProgressRecord {
    pub claim_token: String,
    pub input_hash: String,
    pub created_at_ms: i64,
    pub lease_expires_at_ms: i64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SucceededRecord {
    pub input_hash: String,
    pub receipt: JsonValue,
    pub created_at_ms: i64,
    pub completed_at_ms: i64,
    pub expires_at_ms: i64,
    pub retain_until_ms: i64,
    pub replay_unavailable: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ClaimResult {
    Claimed { took_over_expired_lease: bool },
    InProgress { record: InProgressRecord, store_now_ms: i64 },
    Existing { record: SucceededRecord, store_now_ms: i64 },
}

#[derive(Clone, Copy)]
pub struct ClaimRequest<'a> {
    pub scope: &'a str,
    pub operation: &'a str,
    pub idempotency_key: &'a str,
    pub input_hash: &'a str,
    pub claim_token: &'a str,
    pub now_ms: i64,
    pub lease_ms: i64,
}

#[derive(Clone)]
pub struct CompleteRequest<'a> {
    pub scope: &'a str,
    pub operation: &'a str,
    pub idempotency_key: &'a str,
    pub claim_token: &'a str,
    pub receipt: JsonValue,
    pub now_ms: i64,
    pub ttl_ms: i64,
    pub spent_key_retention_ms: i64,
    pub replay_unavailable: bool,
}

#[derive(Clone, Copy)]
pub struct ReleaseRequest<'a> {
    pub scope: &'a str,
    pub operation: &'a str,
    pub idempotency_key: &'a str,
    pub claim_token: &'a str,
}

pub struct ExtendLeaseRequest<'a> {
    pub owner: ReleaseRequest<'a>,
    pub now_ms: i64,
    pub lease_ms: i64,
}

pub trait WriteStore: Send + Sync {
    fn claim(&self, req: ClaimRequest<'_>) -> Result<ClaimResult, WriteSafetyError>;
    fn complete(&self, req: CompleteRequest<'_>) -> Result<bool, WriteSafetyError>;
    fn release(&self, req: ReleaseRequest<'_>) -> Result<bool, WriteSafetyError>;
    fn extend_lease(&self, req: ExtendLeaseRequest<'_>) -> Result<bool, WriteSafetyError>;
}

#[derive(Debug)]
enum StoredEntry {
    InProgress(InProgressRecord),
    Succeeded { claim_token: String, record: SucceededRecord },
}

type Key = (String, String, String);
type Records = HashMap<Key, StoredEntry>;

fn key(scope: &str, operation: &str, id: &str) -> Key {
    (scope.to_owned(), operation.to_owned(), id.to_owned())
}

#[derive(Default)]
pub struct MemoryStore {
    records: Mutex<Records>,
}

impl MemoryStore {
    pub fn new() -> Self {
        Self::default()
    }

    fn lock(&self) -> Result<std::sync::MutexGuard<'_, Records>, WriteSafetyError> {
        self.records.lock().map_err(|_| WriteSafetyError::new(ErrorCode::StoreError, "Store lock poisoned."))
    }

    pub fn purge_expired(&self, before_ms: i64) -> Result<usize, WriteSafetyError> {
        timestamp(before_ms)?;
        let mut records = self.lock()?;
        let before = records.len();
        records.retain(|_, entry| !matches!(entry, StoredEntry::Succeeded { record, .. }
            if !record.replay_unavailable && record.retain_until_ms <= before_ms));
        Ok(before - records.len())
    }
}

impl WriteStore for MemoryStore {
    fn claim(&self, req: ClaimRequest<'_>) -> Result<ClaimResult, WriteSafetyError> {
        let lease_expires_at_ms = deadline(req.now_ms, req.lease_ms)?;
        let mut records = self.lock()?;
        let key = key(req.scope, req.operation, req.idempotency_key);
        match records.get(&key) {
            Some(StoredEntry::Succeeded { record, .. }) if record.replay_unavailable || req.now_ms < record.retain_until_ms => {
                return Ok(ClaimResult::Existing { record: record.clone(), store_now_ms: req.now_ms });
            }
            Some(StoredEntry::InProgress(record)) => {
                return Ok(ClaimResult::InProgress { record: record.clone(), store_now_ms: req.now_ms });
            }
            _ => {}
        }
        records.insert(key, StoredEntry::InProgress(InProgressRecord {
            claim_token: req.claim_token.to_owned(),
            input_hash: req.input_hash.to_owned(),
            created_at_ms: req.now_ms,
            lease_expires_at_ms,
        }));
        Ok(ClaimResult::Claimed { took_over_expired_lease: false })
    }

    fn complete(&self, req: CompleteRequest<'_>) -> Result<bool, WriteSafetyError> {
        let expires_at_ms = deadline(req.now_ms, req.ttl_ms)?;
        let retain_until_ms = deadline(req.now_ms, retention(req.ttl_ms, req.spent_key_retention_ms)?)?;
        let mut records = self.lock()?;
        let key = key(req.scope, req.operation, req.idempotency_key);
        match records.get(&key) {
            Some(StoredEntry::Succeeded { claim_token, .. }) => Ok(claim_token == req.claim_token),
            Some(StoredEntry::InProgress(existing)) if existing.claim_token == req.claim_token => {
                let record = SucceededRecord {
                    input_hash: existing.input_hash.clone(),
                    receipt: if req.replay_unavailable { JsonValue::Null } else { req.receipt },
                    created_at_ms: existing.created_at_ms,
                    completed_at_ms: req.now_ms,
                    expires_at_ms,
                    retain_until_ms,
                    replay_unavailable: req.replay_unavailable,
                };
                records.insert(key, StoredEntry::Succeeded { claim_token: req.claim_token.to_owned(), record });
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    fn release(&self, req: ReleaseRequest<'_>) -> Result<bool, WriteSafetyError> {
        let mut records = self.lock()?;
        let key = key(req.scope, req.operation, req.idempotency_key);
        if matches!(records.get(&key), Some(StoredEntry::InProgress(record)) if record.claim_token == req.claim_token) {
            records.remove(&key);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn extend_lease(&self, req: ExtendLeaseRequest<'_>) -> Result<bool, WriteSafetyError> {
        let expires = deadline(req.now_ms, req.lease_ms)?;
        let mut records = self.lock()?;
        let owner = req.owner;
        let Some(StoredEntry::InProgress(record)) = records.get_mut(&key(owner.scope, owner.operation, owner.idempotency_key)) else {
            return Ok(false);
        };
        if record.claim_token != owner.claim_token || record.lease_expires_at_ms <= req.now_ms {
            return Ok(false);
        }
        record.lease_expires_at_ms = record.lease_expires_at_ms.max(expires);
        Ok(true)
    }
}