Safe writes for Model Context Protocol (MCP) servers. Idempotency keys, SHA-256 input binding, authorization, leases, dry-run previews, and replayable write receipts.
stackdeck.dev/mcp-writes · Try the retry demo · Specification · Agent retry rules · llms.txt · SKILL.md
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
- Exact replays. A retry with the same
idempotency_keyand canonical input returns the saved receipt (replay: true) while the receipt is available. - Conflict detection. Reusing a key with changed arguments returns
409 conflictusing canonical SHA-256 hashing across TypeScript, Python, and Rust. - Fail-closed leases and provider keys. An expired lease or an ambiguous handler error keeps the key bound and returns
outcome_unknown. Pass the handler's scoped provider idempotency key to downstream APIs or commit the write and receipt in one database transaction. - Zero runtime dependencies. TypeScript, Python, and Rust ship with zero runtime dependencies and pass one shared conformance suite.
The library core supports Node 22. The SQLite quick start requires Node 22.13+ for unflagged node:sqlite support.
npm install @stackdeck/mcp-writesimport assert from "node:assert/strict";
import { DatabaseSync } from "node:sqlite";
import { createWriteGuard } from "@stackdeck/mcp-writes";
import { createSqliteStore } from "@stackdeck/mcp-writes/stores/sqlite";
const db = new DatabaseSync(":memory:");
const store = createSqliteStore({ db });
store.init();
const guard = createWriteGuard({ store });
const caller = { workspaceId: "workspace_1", canRefund: true };
const execute = () => guard.execute({
operation: "invoices.refund",
scope: caller.workspaceId,
authorize: () => caller.canRefund,
idempotencyKey: "refund-42",
input: { amountCents: 500 },
handler: ({ amountCents }) => ({ refundId: "refund_42", amountCents }),
});
assert.equal((await execute()).replay, false);
assert.equal((await execute()).replay, true);
db.close();Use registerSafeWriteTool(server, guard, options) from @stackdeck/mcp-writes/mcp with the MCP SDK and Zod. Construct options.inputSchema with withWriteEnvelope(z, { ...toolFields }) so MCP advertises and preserves the write fields. Use authenticated server metadata in resolveScope. The MCP SDK and Zod are optional peers. The refund example uses a scoped provider key. The database example projects a receipt to a record ID and resolves it on replay.
pip install stackdeck-mcp-writesimport sqlite3
from stackdeck_mcp_writes import SqliteStore, WriteGuard
conn = sqlite3.connect(":memory:")
store = SqliteStore(conn)
store.init()
guard = WriteGuard(store=store)
caller = {"workspace_id": "workspace_1", "can_refund": True}
options = dict(
operation="invoices.refund",
scope=caller["workspace_id"],
authorize=lambda _data, _ctx: caller["can_refund"],
idempotency_key="refund-42",
input_value={"amount_cents": 500},
handler=lambda data, _ctx: {"refund_id": "refund_42", **data},
)
assert guard.execute(**options).replay is False
assert guard.execute(**options).replay is True
conn.close()Apply @safe_write_tool(guard, name=..., resolve_scope=...) before registering the resulting function with FastMCP. Annotate a handler parameter as WriteContext to receive the provider key and lease extension method. Use await guard.execute_async(...) with async callbacks and await ctx.extend_lease() in the handler. For async SQLite writes, pass a database path or ":memory:" to SqliteStore so it can open a connection for worker threads. FastMCP requires an idempotency_key string on preview calls as well.
When registering a synchronous handler with the official Python MCP server, set async_tool=True on safe_write_tool. The wrapper is async and runs the handler and synchronous store calls on worker threads. With the default setting, a synchronous handler remains directly callable.
cargo add stackdeck-mcp-writesuse stackdeck_mcp_writes::{ExecuteRequest, JsonValue, MemoryStore, WriteGuard, WriteOutcome, WriteSafetyError};
fn main() -> Result<(), WriteSafetyError> {
let guard = WriteGuard::new(MemoryStore::new());
let caller_workspace = "workspace_1";
let execute = || {
let request = ExecuteRequest {
scope: Some(caller_workspace),
idempotency_key: Some("refund-42"),
..ExecuteRequest::new("invoices.refund", JsonValue::Int(500))
};
guard.execute(request, |_, _| Ok::<_, WriteSafetyError>(JsonValue::String("refund_42".into())))
};
assert!(matches!(execute()?, WriteOutcome::Committed { replay: false, .. }));
assert!(matches!(execute()?, WriteOutcome::Committed { replay: true, .. }));
Ok(())
}Derive scope from a verified workspace or tenant identity (never from unverified request metadata or a shared OAuth application ID), authorize the verified actor against the target payment, and return a plain JSON receipt.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { createWriteGuard } from "@stackdeck/mcp-writes";
import { registerSafeWriteTool, withWriteEnvelope } from "@stackdeck/mcp-writes/mcp";
import { createPostgresStore } from "@stackdeck/mcp-writes/stores/postgres";
const server = new McpServer({ name: "billing", version: "1.0.0" });
const store = createPostgresStore({ client: pgPool });
await store.init();
const guard = createWriteGuard({ store });
registerSafeWriteTool(server, guard, {
name: "payments.refund",
description: "Refund a payment once per idempotency key.",
inputSchema: withWriteEnvelope(z, {
payment_intent_id: z.string(),
amount_cents: z.number().int().positive(),
}),
resolveScope: (_args, extra) => verifiedWorkspaceId(extra.authInfo),
authorize: (input, _ctx, extra) => canRefundPayment(extra.authInfo, input.payment_intent_id),
preview: (input) => ({ summary: `Will refund ${input.amount_cents} cents on ${input.payment_intent_id}` }),
handler: async (input, ctx) => {
const refund = await stripe.refunds.create(
{ payment_intent: input.payment_intent_id, amount: input.amount_cents },
{ idempotencyKey: ctx.providerKey },
);
return { refund_id: refund.id, amount_cents: refund.amount, status: refund.status };
},
});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"]}| Capability | TypeScript | Python | Rust |
|---|---|---|---|
| Minimum runtime | Node 22 | Python 3.10 | Rust 1.80 on Unix or Windows |
| Guard, canonical SHA-256, dry-run, and default JSON receipts | Yes | Yes | Yes |
| Optional binding context | Yes | Yes | Yes |
| Authorization, provider idempotency key, and lease extension | Yes | Yes | Yes |
| Post-resolution replay hook | Yes | Yes | Application-managed |
| Project and resolve compact receipts | Yes | Yes | Default receipts only |
| Human approval hooks | Yes | Yes | Application-managed |
| MCP adapter | MCP SDK with Zod | FastMCP, sync and async tools | Application-managed |
| Memory store | Included | Included | Included |
| SQLite and PostgreSQL stores | Included | Included | SQL schema constants |
| PostgreSQL client resolver and operator reconciliation | Included | Included | Application-managed |
| Redis store | Included | Included | Lua script and key encoding helpers |
| Runtime package dependencies | Zero | Zero | Zero |
- TypeScript uses
@stackdeck/mcp-writes. - Python and Rust both use the package name
stackdeck-mcp-writeson their respective registries. - Scope note: TypeScript and Python are the primary full-adapter packages. The Rust crate intentionally ships only the core write guard,
MemoryStore,WriteStoretrait, and SQL/Lua constants rather than full database or MCP framework adapters.
Initialize SQLite and PostgreSQL stores with init(). Memory and Redis stores are ready on construction. Call verifyWriteSafetyStore from @stackdeck/mcp-writes/testing to test a custom TypeScript store.
The TypeScript Redis store accepts a RedisEvalClient with eval(script, keys, args), plus built-in nodeRedisClient(redis) and ioRedisClient(redis) helpers from @stackdeck/mcp-writes/stores/redis. Python PostgresStore accepts an autocommit psycopg/DB-API connection or a query_fn callable, and RedisStore(client, key_prefix=...) accepts a redis-py client.
Return plain JSON values from handlers (no raw SDK objects with non-enumerable properties, custom prototypes, dataclasses, or Pydantic models), or supply both projectReceipt/resolveReceipt (project_receipt/resolve_receipt in Python). The default receipt window is 24 hours. A key with a saved receipt remains spent for seven days from completion. During that period an expired receipt returns expired. An uncertain write returns outcome_unknown and keeps its binding even after the lease expires. When the store saves a terminal marker, later calls return replay_unavailable. If a handler fails before attempting any side effect, signal it with PreEffectError in TypeScript or Python. In Rust, use execute_with_pre_effect and return HandlerError::BeforeEffect(error).
See the specification, agent retry rules, llms.txt, and SKILL.md.
Direct guards can bind extra server-controlled JSON context to the input hash in TypeScript, Python, and Rust. Omit the context to keep the original hash. Explicit JSON null is a binding value. Changing context on a spent key returns conflict.
TypeScript and Python add a replay hook for access checks that need the resolved result. TypeScript captures the hook when execute starts. PostgreSQL stores can resolve a tenant-scoped request connection at call time. Python request connections can run concurrently. Set schemaName in TypeScript or schema_name in Python to select a PostgreSQL schema explicitly.
Memory, SQLite, and PostgreSQL stores can list and reconcile stuck writes. Use the last record's cursor to fetch the next page. Pass the record's revision along with its key and input hash so an older operator decision cannot change a later attempt. See the TypeScript guide, Python guide, Rust guide, and upgrade notes.
Run pnpm bench to execute packages/mcp-writes/benchmarks/stress.ts: 1 held owner write with 99 concurrent in-flight duplicates (all asserted in_progress), 100 concurrent post-commit replays, 20 payload-mismatch probes, a PreEffectError lock-release check, and 500 latency iterations per store (repeated reads of one key for replay). Pass MCP_WRITES_POSTGRES_URL and MCP_WRITES_REDIS_URL to include live PostgreSQL and Redis.
Measured locally on Node 25.9 (Apple Silicon, local PostgreSQL 18 and Redis 8 containers):
| Store | In-flight blocked | Post-commit replays | Handler runs | Conflicts blocked | Leaked locks | Fresh write p50 / p95 | Single-key replay p50 / p95 |
|---|---|---|---|---|---|---|---|
| Memory | 99/99 | 100/100 | 1 | 20/20 | 0 | 0.102 ms / 0.667 ms | 0.104 ms / 2.07 ms |
| SQLite (WAL) | 99/99 | 100/100 | 1 | 20/20 | 0 | 0.180 ms / 1.66 ms | 0.056 ms / 0.391 ms |
| PostgreSQL | 99/99 | 100/100 | 1 | 20/20 | 0 | 4.88 ms / 11.41 ms | 4.67 ms / 23.48 ms |
| Redis | 99/99 | 100/100 | 1 | 20/20 | 0 | 4.19 ms / 16.34 ms | 1.96 ms / 6.88 ms |
pnpm install
pnpm gate
pnpm benchRunnable examples: examples/refund-tool/demo.ts, examples/db-write-tool/demo.ts, and examples/refund-tool-py/demo.py.
The live integration job supplies PostgreSQL and Redis connection URLs and installs FastMCP and Python drivers in an isolated environment.
MIT. See LICENSE.
The MIT license covers the code in this repository, not trademarks. "StackDeck", "StackDeck MCP Writes" and their logos and brand marks remain the property of TrueWear, LLC. Forks and derivative works may not use these names or marks in a way that implies endorsement or official affiliation.