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 callguard.execute(..., input_value=...)orawait 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), andRedisStore(client, key_prefix=...)(redis-py client). - Async SQLite: Pass a database path or
":memory:"(not asqlite3.Connection) toSqliteStoreso worker threads can run safely, then callstore.close()on shutdown. - Sync handlers with official
mcp.server.fastmcp: Setasync_tool=Trueon@safe_write_toolso the wrapper is async and offloads the handler and store calls to worker threads. FastMCP requires anidempotency_keystring even ondry_run=Truepreview calls. - Plain JSON receipts and pre-effect errors: Return plain JSON (
dict,list,str,int,float,bool,None), or pass bothproject_receiptandresolve_receipt. RaisePreEffectErroronly when a handler fails before attempting any side effect so the lock is released. Callawait 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/99in-flight duplicates blocked,100/100post-commit replays,1handler run,0leaked 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)
| 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)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| 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 logRelease 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 logSecurity 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.
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 logA 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.