Skip to main content

stackdeck-mcp-writes

Safe writes for Model Context Protocol (MCP) and FastMCP servers in Python 3.10+. Idempotency keys, SHA-256 input binding, authorization, leases, dry-run previews, human approval hooks, and replayable write receipts with zero runtime dependencies.

Docs and interactive retry demo · Specification · Agent retry rules · Adoption guide · Source on GitHub

Why this exists

When an MCP tool call times out after your server charges a card or writes to a database, the agent retries. Without an idempotency guard, the write runs twice.

Plain write handler:         2 charges ($50.00)  handler ran again
With stackdeck-mcp-writes:   1 charge  ($25.00)  replay: true

Install

pip install stackdeck-mcp-writes

Quick start

from stackdeck_mcp_writes import MemoryStore, WriteGuard, safe_write_tool

guard = WriteGuard(store=MemoryStore())
caller = {"workspace_id": "workspace_1"}

@safe_write_tool(guard, name="invoices.refund", resolve_scope=lambda _args, _ctx: caller["workspace_id"])
def refund_invoice(invoice_id: str, amount_cents: int) -> dict[str, object]:
    return {"refund_id": f"re_{invoice_id}", "amount_cents": amount_cents}

args = dict(invoice_id="invoice_42", amount_cents=500, idempotency_key="refund-42")
assert refund_invoice(**args)["replay"] is False
assert refund_invoice(**args)["replay"] is True

FastMCP and official MCP server integration

Pass an autocommit psycopg/DB-API connection (or a query_fn callable) to PostgresStore. Derive resolve_scope from a verified workspace identity (never from unverified request metadata such as ctx.client_id), authorize the verified actor against the target payment, and return a plain JSON dict:

from fastmcp import Context, FastMCP
from stackdeck_mcp_writes import PostgresStore, WriteContext, WriteGuard, safe_write_tool

# Pass an autocommit psycopg/DB-API connection (or a query_fn callable).
store = PostgresStore(pg_conn)
store.init()
guard = WriteGuard(store=store)
mcp = FastMCP("billing")

@mcp.tool()
@safe_write_tool(
    guard,
    name="payments.refund",
    resolve_scope=lambda _args, ctx: verified_actor(ctx).workspace_id,
    authorize=lambda args, write: can_refund_payment(current_verified_actor(), write.scope, args["payment_intent_id"]),
)
async def refund_payment(payment_intent_id: str, amount_cents: int, ctx: Context, write: WriteContext) -> dict[str, object]:
    refund = await stripe_refund(payment_intent_id, amount_cents, idempotency_key=write.provider_key)
    return {"refund_id": refund["id"], "amount_cents": refund["amount"], "status": refund["status"]}

Important usage rules

  • Keyword-only direct calls: Construct with WriteGuard(store=store) and call guard.execute(..., input_value=...) or await guard.execute_async(..., input_value=...).
  • Stores included: MemoryStore(), SqliteStore(path_or_memory) (store.init()), PostgresStore(pg_conn_or_query_fn) (store.init() with an autocommit DB-API connection or callable), and RedisStore(client, key_prefix=...) (redis-py client).
  • Async SQLite: Pass a database path or ":memory:" (not a sqlite3.Connection) to SqliteStore so worker threads can run safely, then call store.close() on shutdown.
  • Sync handlers with official mcp.server.fastmcp: Set async_tool=True on @safe_write_tool so the wrapper is async and offloads the handler and store calls to worker threads. FastMCP requires an idempotency_key string even on dry_run=True preview calls.
  • Plain JSON receipts and pre-effect errors: Return plain JSON (dict, list, str, int, float, bool, None), or pass both project_receipt and resolve_receipt. Raise PreEffectError only when a handler fails before attempting any side effect so the lock is released. Call await write.extend_lease(...) during slow writes.
  • Stress proof: Verified cross-language conformance with TypeScript and Rust, plus live PostgreSQL 18 and Redis 8 stress checks (99/99 in-flight duplicates blocked, 100/100 post-commit replays, 1 handler run, 0 leaked locks).

See the Python refund example, SPEC.md, and agent retry rules.

Added in v0.2.0

Pass binding_context= to guard.execute, guard.execute_async, canonical_binding_json, or canonical_hash to include trusted JSON context in the input hash. Omit it to keep the original hash. Python None binds JSON null. Changing the context for the same bound key returns conflict.

The guard's on_replay(result, input_value, ctx) hook runs after resolving a receipt and before returning a replay. Raise to deny replay while preserving the receipt. Use execute_async to await an async hook.

Pass PostgresStore(client=current_connection.get) when current_connection is a ContextVar containing a request's RLS-scoped psycopg connection. The resolver is synchronous and runs once per store operation. Request connections can run concurrently. The caller owns tenant setup, transaction boundaries, and connection cleanup. A static psycopg connection requires autocommit=True. The positional query_fn(sql, params) form remains available. Set the optional schema_name to target an existing PostgreSQL schema explicitly.

On memory, SQLite, and PostgreSQL, call store.list_stuck(scope=..., operation=..., limit=...) to find expired leases and unavailable receipts. Pass the last record's cursor with the same filters to get the next page. Once you confirm the outcome, pass the listed key, input_hash, and revision to store.reconcile. Use action="complete" with a JSON receipt or action="release" when the effect never occurred and the old worker can no longer perform it. If the result is False, fetch the current state before making another decision. Redis reconciliation is application-managed. See the operator contract.

License

MIT. See LICENSE.

Metadata

Release files for stackdeck-mcp-writes 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for stackdeck-mcp-writes 0.2.0
File Size Uploaded Provenance Actions
stackdeck_mcp_writes-0.2.0.tar.gz 45.9 kB With provenance Details for stackdeck_mcp_writes-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for stackdeck-mcp-writes 0.2.0
File Interpreter ABI Platform Actions
stackdeck_mcp_writes-0.2.0-py3-none-any.whl Python 3 none any Details for stackdeck_mcp_writes-0.2.0-py3-none-any.whl

Total release size: 73.4 kB

Release files / stackdeck_mcp_writes-0.2.0.tar.gz

Download URL stackdeck_mcp_writes-0.2.0.tar.gz
Size 45.9 kB
Tags Source
SHA-256 checksum
How to use checksums
df23a4a5ba09d37ebdc0b6120c93be6ae49117be7d16e476df561fbbfa60564a
BLAKE2b-256 checksum
How to use checksums
bb333abcc05f7e80fff79e35d79f1560f95e33d05a44d1c4fa94441feb4c6d54
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / stackdeck_mcp_writes-0.2.0-py3-none-any.whl

Download URL stackdeck_mcp_writes-0.2.0-py3-none-any.whl
Size 27.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
da08fc8552975762a4af209fc3ac5e5820a096441f60fcf6fe157c261320649f
BLAKE2b-256 checksum
How to use checksums
a392e8abd697a538811dc93d9cc2b91273b8f539c6d4bc9a59d2b012abfc82fe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for stackdeck-mcp-writes 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for stackdeck_mcp_writes-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page