Metadata-Version: 2.4
Name: stackdeck-mcp-writes
Version: 0.1.0
Summary: Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies.
Author: StackDeck
License-Expression: MIT
Project-URL: Homepage, https://stackdeck.dev/mcp-writes
Project-URL: Documentation, https://github.com/stackdeckhq/mcp-writes/blob/main/SPEC.md
Project-URL: Source, https://github.com/stackdeckhq/mcp-writes
Project-URL: Issues, https://github.com/stackdeckhq/mcp-writes/issues
Keywords: mcp,fastmcp,model-context-protocol,idempotency,retries,receipts,write-safety,dry-run,ai-agents,stackdeck
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# 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](https://stackdeck.dev/mcp-writes) · [Specification](https://github.com/stackdeckhq/mcp-writes/blob/main/SPEC.md) · [Agent retry rules](https://github.com/stackdeckhq/mcp-writes/blob/main/docs/agents.md) · [Adoption guide](https://github.com/stackdeckhq/mcp-writes/blob/main/docs/SKILL.md) · [Source on GitHub](https://github.com/stackdeckhq/mcp-writes)

## 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.

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

## Install

```sh
pip install stackdeck-mcp-writes
```

## Quick start

```python
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`:

```python
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](https://github.com/stackdeckhq/mcp-writes/blob/main/examples/refund-tool-py/demo.py), [SPEC.md](https://github.com/stackdeckhq/mcp-writes/blob/main/SPEC.md), and [agent retry rules](https://github.com/stackdeckhq/mcp-writes/blob/main/docs/agents.md).

## License

MIT. See [LICENSE](https://github.com/stackdeckhq/mcp-writes/blob/main/LICENSE).
