Skip to main content
Glama

EffectFence

CI crates.io docs.rs License: MIT

Your swarm doesn't need more memory. It needs a causal fence around tool side effects.

⚑ effectfence β€” THE STORM
1,000 attempts to charge order #777 ($49.00): concurrent racers + late retries…

ACTUAL EXECUTIONS     :      1   ← the whole point
served sealed receipt :    995
told to stand down    :      4
elapsed               : 22.33ms

πŸ’° double-charges prevented this run: $48,951.00
βœ… ONE execution. Every other attempt was fenced, replayed, or refused.

Run the attack yourself:

cargo run --release --example storm

EffectFence is a causal concurrency fence for multi-agent tool calls. When more than one agent (or retry, or re-dispatch) can end up trying to run the same side-effecting operation β€” charge a card, send a payout, provision a resource β€” EffectFence guarantees exactly one attempt ever executes it: same-instant races are decided by an atomic compare-exchange reservation, and late duplicates get the recorded outcome replayed instead of running again. Every effect that does run gets a content-addressed certificate chained to whatever it was causally built on.

It ships as a Rust library (effectfence::fence) and as a stdio MCP server exposing three tools β€” fence_prepare, fence_commit, fence_abort β€” so agents can route side-effecting tool calls through the fence instead of racing each other directly.

The problem

In a multi-agent gateway, more than one caller can end up trying to run the same effect:

  • Two agents independently decide "charge the customer for order #123" needs to happen β€” at the same instant.

  • A supervisor times out waiting for a tool call and re-dispatches it while the original is still in flight.

  • A retried or duplicated event triggers the same decision again, minutes after the first attempt already succeeded.

Naively, any of these double-runs the effect. Naively rejecting every duplicate with no memory of outcome is also wrong: if the first attempt crashed, the effect never runs at all, and a duplicate that arrives after success gets an error instead of the result it needs. EffectFence closes all of it with optimistic concurrency control (OCC) plus an intent ledger: attempts don't block each other, exactly one executes, and every other attempt learns what actually happened.

Related MCP server: emilia-mcp-server

Architecture

Four pieces compose into the fencing protocol:

The intent ledger is what stops duplicates, not just races. Every effect carries an intent β€” a stable id for the logical action (e.g. "charge:order-123"). Attempts sharing an intent are the same action: the first is admitted and holds a lease; concurrent duplicates are told an attempt is in flight; duplicates arriving after success get the recorded certificate replayed verbatim; duplicates after a failure are fenced (the side effect may or may not have fired β€” that must be reconciled, not blindly retried) until explicitly cleared. Crashed holders lose their lease after a TTL so the action isn't stuck forever.

Vector clocks (VectorClock) track causal "happened-before" relationships across agents β€” one logical counter per agent, joined via elementwise-max merge, compared via a le partial order, with a concurrent check for genuinely unordered events and a stable SHA-256 digest for inclusion in certificates.

OCC read-sets (ReadSetEntry) record the causal dependencies a decision was based on: "when I decided to act, domain D was at sequence S." Both prepare_effect_fence and commit_effect_cert validate every entry against live state β€” if anything moved, the attempt is rejected as stale rather than allowed to act on outdated information.

CAS domain fencing is where same-instant races are decided. Each domain (a named contention scope, e.g. "order:123") has an AtomicU64 sequence counter. The decision is a single atomic compare_exchange β€” exactly one concurrent caller can win for any given expected sequence. (Precision note: the counter lookup sits behind a short mutex; only the race decision itself is lock-free. Ideas for a fully lock-free path are welcome.)

              β”Œ intent gate ──────── already done? β†’ Replay(recorded cert)   [do NOT run]
              β”‚                      in flight / failed? β†’ rejected          [do NOT run]
 EffectRequest─
              β”œ read-set check ───── dependency moved? β†’ ReadSetStale        [do NOT run]
              β”‚
              β”” domain CAS ────────── lost the race? β†’ DomainRace            [do NOT run]
                     β”‚
                     β”” Fresh(ticket) β†’ run the effect β†’ commit_effect_cert β†’ EffectCert
                                                      β†˜ abort_effect (failed; fenced until reconciled)

Every committed effect becomes an EffectCert: a SHA-256 content hash over {intent, parent, domain, seq, tool, args, result, vector_clock, read_set, agent}, chained to a parent cert hash for causal lineage. Two certs with the same hash are, by definition, records of the same effect β€” EffectCert::verify() recomputes the hash and confirms it hasn't been tampered with or hand-built incorrectly.

Scope

This is an in-memory, single-process fence β€” state lives behind an Arc and is lost on restart. That's enough to close races and duplicates between concurrent threads/tasks in one gateway process. Two things it deliberately does not do (yet):

  • Cross-process/cross-restart fencing. A horizontally scaled gateway needs the same intent/domain/read-set model backed by a shared store (e.g. SETNX+CAS in Redis, or an optimistic version column in Postgres) β€” the types here are meant to carry over directly to that backend.

  • Enforcement. The fence protects agents that route their effects through it; it cannot stop an agent that bypasses it entirely. Deploy it at the one choke point your agents share (the gateway process that owns the tools).

Memory is bounded: finished outcomes expire after a configurable TTL (FenceConfig::result_ttl, swept by EffectFence::sweep), queries never create tracking state, and domain counters are tiny and manually evictable (evict_domain).

Quickstart: library

use effectfence::fence::{
    prepare_effect_fence, commit_effect_cert, Admission, EffectFence, EffectRequest, VectorClock,
};

let fence = EffectFence::new();

let req = EffectRequest {
    intent: "charge:order-123".into(),   // same action -> same intent, always
    parent: None,                        // hash of the cert this follows, if any
    domain: "order:123".into(),          // contention scope
    tool: "charge_card".into(),
    args: serde_json::json!({"amount_cents": 1999}),
    read_set: vec![],                    // other domains this decision cross-checked
    agent: "agent-a".into(),
    known_clock: VectorClock::new(),
};

match prepare_effect_fence(&fence, req)? {
    Admission::Fresh(prepared) => {
        // This attempt won. Actually run the charge...
        let cert = commit_effect_cert(
            &fence,
            prepared,
            serde_json::json!({"charge_id": "ch_123"}),
        )?;
        assert!(cert.verify());
        // (on failure: abort_effect(&fence, prepared, "why") instead)
    }
    Admission::Replay(cert) => {
        // This exact action already ran -- use cert.result, charge nothing.
    }
}

A concurrent duplicate of the same intent gets Err(FenceError::IntentInFlight); a same-instant race on the domain gets Err(FenceError::DomainRace); either way it must not run the effect.

Quickstart: MCP server

Install

With a Rust toolchain (rustup.rs):

cargo install effectfence

Or build from a clone of this repo:

cargo build --release   # binary at ./target/release/effectfence

Add it to Claude

Claude Code (one command):

claude mcp add effectfence -- effectfence

(If you built from source instead of cargo install, use the full path: claude mcp add effectfence -- /path/to/target/release/effectfence.)

Claude Desktop β€” add to claude_desktop_config.json:

{
  "mcpServers": {
    "effectfence": {
      "command": "effectfence"
    }
  }
}

Any project (team-shared) β€” commit a .mcp.json at the project root:

{
  "mcpServers": {
    "effectfence": {
      "command": "effectfence"
    }
  }
}

That's it β€” no configuration, no environment variables, no accounts. The server holds its fence state in memory for the life of the process.

The tools

It exposes:

  • fence_prepare β€” { intent, domain, tool, args, agent, read_set?, parent?, known_clock? } β†’ {status: "fresh", prepared} when this attempt wins (run the tool, then report back), or {status: "already_done", cert} when this exact action already ran (use the recorded result β€” do NOT run the tool). Errors mean do not run.

  • fence_commit β€” { prepared, result } β†’ {status: "committed", cert}. Later duplicates of the intent now replay this cert.

  • fence_abort β€” { prepared, reason } β†’ {status: "aborted"}. The intent stays fenced until reconciled and cleared.

Tool input schemas are generated automatically from the Rust types (via schemars), so any MCP client can introspect them with tools/list.

Testing

cargo test    # unit tests + chaos tests
cargo clippy --all-targets

tests/chaos_test.rs uses real OS threads to prove the two guarantees separately: a forced same-instant domain race (synchronization deliberately constructed so the collision is guaranteed, not hoped for) admits exactly one winner every time, and 16 concurrent duplicates of one intent admit exactly one execution β€” with late duplicates replaying the committed cert. A 32-thread stress test additionally asserts sequence numbers are never double-allocated.

License

MIT β€” see LICENSE.

A
license - permissive license
-
quality - not tested
A
maintenance

Maintenance

–Maintainers
–Response time
0dRelease cycle
2Releases (12mo)
Commit activity

Related MCP Servers

View all related MCP servers

Related MCP Connectors

  • Coordinate multiple AI agents over MCP: atomic claims, leases, shared ledger, handoffs, tasks.

  • Preflight, approve, and prove consequential agent actions with signed evidence and x402 tools.

  • Post-quantum, tamper-evident receipts for agent actions. Ed25519 + ML-DSA-65, offline verify.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/aurumflux20/effectfence'

If you have feedback or need assistance with the MCP directory API, please join our Discord server