stackdeck-mcp-writes 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes.egg-info → stackdeck_mcp_writes-0.2.0}/PKG-INFO +11 -1
  2. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/README.md +10 -0
  3. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/pyproject.toml +1 -1
  4. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/__init__.py +20 -2
  5. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/canonical.py +17 -9
  6. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/guard.py +13 -6
  7. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/stores.py +321 -35
  8. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/timing.py +1 -0
  9. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0/src/stackdeck_mcp_writes.egg-info}/PKG-INFO +11 -1
  10. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes.egg-info/SOURCES.txt +1 -0
  11. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/tests/fixtures/canonical-hash.json +35 -0
  12. stackdeck_mcp_writes-0.2.0/tests/fixtures/operator-replay.json +74 -0
  13. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/tests/fixtures/write-guard.json +28 -0
  14. stackdeck_mcp_writes-0.2.0/tests/test_conformance.py +404 -0
  15. stackdeck_mcp_writes-0.2.0/tests/test_live_stores.py +254 -0
  16. stackdeck_mcp_writes-0.1.0/tests/test_conformance.py +0 -210
  17. stackdeck_mcp_writes-0.1.0/tests/test_live_stores.py +0 -81
  18. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/LICENSE +0 -0
  19. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/MANIFEST.in +0 -0
  20. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/setup.cfg +0 -0
  21. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/errors.py +0 -0
  22. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/py.typed +0 -0
  23. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes/redis_script.py +0 -0
  24. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes.egg-info/dependency_links.txt +0 -0
  25. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/src/stackdeck_mcp_writes.egg-info/top_level.txt +0 -0
  26. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/tests/fixtures/redis-keys.json +0 -0
  27. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/tests/test_fastmcp.py +0 -0
  28. {stackdeck_mcp_writes-0.1.0 → stackdeck_mcp_writes-0.2.0}/tests/test_guard_failures.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stackdeck-mcp-writes
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies.
5
5
  Author: StackDeck
6
6
  License-Expression: MIT
@@ -98,6 +98,16 @@ async def refund_payment(payment_intent_id: str, amount_cents: int, ctx: Context
98
98
 
99
99
  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).
100
100
 
101
+ ## Added in v0.2.0
102
+
103
+ 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`.
104
+
105
+ 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.
106
+
107
+ 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.
108
+
109
+ 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](../../SPEC.md#7-operator-reconciliation).
110
+
101
111
  ## License
102
112
 
103
113
  MIT. See [LICENSE](https://github.com/stackdeckhq/mcp-writes/blob/main/LICENSE).
@@ -73,6 +73,16 @@ async def refund_payment(payment_intent_id: str, amount_cents: int, ctx: Context
73
73
 
74
74
  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).
75
75
 
76
+ ## Added in v0.2.0
77
+
78
+ 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`.
79
+
80
+ 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.
81
+
82
+ 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.
83
+
84
+ 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](../../SPEC.md#7-operator-reconciliation).
85
+
76
86
  ## License
77
87
 
78
88
  MIT. See [LICENSE](https://github.com/stackdeckhq/mcp-writes/blob/main/LICENSE).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stackdeck-mcp-writes"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  description = "Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -5,7 +5,7 @@ from .canonical import (
5
5
  validate_idempotency_key,
6
6
  )
7
7
  from .errors import WRITE_SAFETY_ERROR_CODES, PreEffectError, WriteSafetyError, WriteToolError
8
- from .guard import ApprovalBinding, ApprovalHook, ApprovalRequest, WriteContext, WriteGuard, WriteOutcome, safe_write_tool
8
+ from .guard import ApprovalBinding, ApprovalHook, ApprovalRequest, ReplayHook, WriteContext, WriteGuard, WriteOutcome, safe_write_tool
9
9
  from .stores import (
10
10
  POSTGRES_SCHEMA_SQL,
11
11
  REDIS_CLAIM_LUA,
@@ -16,15 +16,23 @@ from .stores import (
16
16
  AsyncWriteStore,
17
17
  ClaimResult,
18
18
  MemoryStore,
19
+ PostgresClient,
20
+ PostgresClientResolver,
21
+ PostgresConnection,
22
+ PostgresQuery,
19
23
  PostgresStore,
24
+ ReconcileAction,
25
+ ReconcilableWriteStore,
20
26
  RedisStore,
21
27
  SqliteStore,
28
+ StuckReason,
29
+ StuckWriteRecord,
22
30
  WriteStore,
23
31
  build_redis_store_key,
24
32
  postgres_schema_sql,
25
33
  sqlite_schema_sql,
26
34
  )
27
- from .timing import DEFAULT_SPENT_KEY_RETENTION_MS
35
+ from .timing import DEFAULT_SPENT_KEY_RETENTION_MS, DEFAULT_TTL_MS
28
36
 
29
37
  __all__ = [
30
38
  "ApprovalBinding",
@@ -34,16 +42,26 @@ __all__ = [
34
42
  "ClaimResult",
35
43
  "MemoryStore",
36
44
  "DEFAULT_SPENT_KEY_RETENTION_MS",
45
+ "DEFAULT_TTL_MS",
37
46
  "POSTGRES_SCHEMA_SQL",
47
+ "PostgresClient",
48
+ "PostgresClientResolver",
49
+ "PostgresConnection",
50
+ "PostgresQuery",
38
51
  "PostgresStore",
39
52
  "PreEffectError",
40
53
  "REDIS_CLAIM_LUA",
41
54
  "REDIS_COMPLETE_LUA",
42
55
  "REDIS_EXTEND_LEASE_LUA",
43
56
  "REDIS_RELEASE_LUA",
57
+ "ReconcileAction",
58
+ "ReconcilableWriteStore",
44
59
  "RedisStore",
60
+ "ReplayHook",
45
61
  "SQLITE_SCHEMA_SQL",
46
62
  "SqliteStore",
63
+ "StuckReason",
64
+ "StuckWriteRecord",
47
65
  "WRITE_SAFETY_ERROR_CODES",
48
66
  "WriteContext",
49
67
  "WriteGuard",
@@ -10,6 +10,7 @@ from .errors import WriteSafetyError
10
10
 
11
11
  IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[\x21-\x7E]{1,200}$")
12
12
  MAX_SAFE_INTEGER = 2**53 - 1
13
+ _OMITTED = object()
13
14
 
14
15
 
15
16
  def validate_idempotency_key(value: Any) -> str:
@@ -126,24 +127,31 @@ def canonical_json(value: Any) -> str:
126
127
  return _serialize(snapshot_json(value))
127
128
 
128
129
 
129
- def canonical_binding_json(operation: str, scope: str, input_value: Any) -> str:
130
- return _serialize_binding(operation, scope, snapshot_json(input_value))
130
+ def snapshot_binding_context(value: Any) -> Any:
131
+ return _OMITTED if value is _OMITTED else snapshot_json(value)
131
132
 
132
133
 
133
- def canonical_hash(operation: str, scope: str, input_value: Any) -> str:
134
- payload = canonical_binding_json(operation, scope, input_value)
134
+ def canonical_binding_json(operation: str, scope: str, input_value: Any, *, binding_context: Any = _OMITTED) -> str:
135
+ return _serialize_binding(operation, scope, snapshot_json(input_value), snapshot_binding_context(binding_context))
136
+
137
+
138
+ def canonical_hash(operation: str, scope: str, input_value: Any, *, binding_context: Any = _OMITTED) -> str:
139
+ payload = canonical_binding_json(operation, scope, input_value, binding_context=binding_context)
135
140
  return hashlib.sha256(payload.encode("utf-8")).hexdigest()
136
141
 
137
142
 
138
- def hash_snapshot(operation: str, scope: str, input_value: Any) -> str:
139
- payload = _serialize_binding(operation, scope, input_value)
143
+ def hash_snapshot(operation: str, scope: str, input_value: Any, binding_context: Any) -> str:
144
+ payload = _serialize_binding(operation, scope, input_value, binding_context)
140
145
  return hashlib.sha256(payload.encode("utf-8")).hexdigest()
141
146
 
142
147
 
143
- def _serialize_binding(operation: str, scope: str, input_value: Any) -> str:
144
- return _serialize({
148
+ def _serialize_binding(operation: str, scope: str, input_value: Any, binding_context: Any) -> str:
149
+ envelope = {
145
150
  "version": 1,
146
151
  "operation": _valid_string(operation),
147
152
  "scope": _valid_string(scope),
148
153
  "input": input_value,
149
- })
154
+ }
155
+ if binding_context is not _OMITTED:
156
+ envelope["bindingContext"] = binding_context
157
+ return _serialize(envelope)
@@ -13,17 +13,17 @@ from concurrent.futures import ThreadPoolExecutor
13
13
  from dataclasses import dataclass, replace
14
14
  from typing import Any, TypedDict, get_origin, get_type_hints
15
15
 
16
- from .canonical import canonical_json, hash_snapshot, snapshot_json, validate_idempotency_key
16
+ from .canonical import _OMITTED, canonical_json, hash_snapshot, snapshot_binding_context, snapshot_json, validate_idempotency_key
17
17
  from .errors import PreEffectError, WriteSafetyError, WriteToolError
18
18
  from .stores import AsyncWriteStore, SqliteStore, WriteStore
19
- from .timing import DEFAULT_SPENT_KEY_RETENTION_MS, current_ms, deadline, duration, retention
19
+ from .timing import DEFAULT_SPENT_KEY_RETENTION_MS, DEFAULT_TTL_MS, current_ms, deadline, duration, retention
20
20
 
21
21
  DEFAULT_LEASE_MS = 30_000
22
- DEFAULT_TTL_MS = 86_400_000
23
22
  DEFAULT_SCOPE = "default"
24
23
 
25
24
  ToolHook = Callable[[Any, "WriteContext"], Any]
26
25
  ReceiptHook = Callable[[Any, Any, "WriteContext"], Any]
26
+ ReplayHook = Callable[[Any, Any, "WriteContext"], None | Awaitable[None]]
27
27
 
28
28
 
29
29
  def _default_generate_id(prefix: str) -> str:
@@ -316,11 +316,13 @@ class WriteGuard:
316
316
  lease_ms: int | None = None, ttl_ms: int | None = None, spent_key_retention_ms: int | None = None,
317
317
  preview: ToolHook | None = None, authorize: ToolHook | None = None, approval: ApprovalHook | None = None,
318
318
  project_receipt: ReceiptHook | None = None, resolve_receipt: ReceiptHook | None = None,
319
+ binding_context: Any = _OMITTED, on_replay: ReplayHook | None = None,
319
320
  ) -> WriteOutcome:
320
321
  return _drive_sync(self._flow(operation=operation, input_value=snapshot_json(input_value), handler=handler,
321
322
  scope=scope, idempotency_key=idempotency_key, dry_run=dry_run, intent=intent, lease_ms=lease_ms,
322
323
  ttl_ms=ttl_ms, spent_key_retention_ms=spent_key_retention_ms, preview=preview, authorize=authorize,
323
- approval=approval, project_receipt=project_receipt, resolve_receipt=resolve_receipt))
324
+ approval=approval, project_receipt=project_receipt, resolve_receipt=resolve_receipt,
325
+ binding_context=snapshot_binding_context(binding_context), on_replay=on_replay))
324
326
 
325
327
  def execute_async(
326
328
  self, *, operation: str, input_value: Any, handler: ToolHook, scope: str = DEFAULT_SCOPE,
@@ -328,11 +330,13 @@ class WriteGuard:
328
330
  lease_ms: int | None = None, ttl_ms: int | None = None, spent_key_retention_ms: int | None = None,
329
331
  preview: ToolHook | None = None, authorize: ToolHook | None = None, approval: ApprovalHook | None = None,
330
332
  project_receipt: ReceiptHook | None = None, resolve_receipt: ReceiptHook | None = None,
333
+ binding_context: Any = _OMITTED, on_replay: ReplayHook | None = None,
331
334
  ) -> Coroutine[Any, Any, WriteOutcome]:
332
335
  return _drive_async(self._flow(operation=operation, input_value=snapshot_json(input_value), handler=handler,
333
336
  scope=scope, idempotency_key=idempotency_key, dry_run=dry_run, intent=intent, lease_ms=lease_ms,
334
337
  ttl_ms=ttl_ms, spent_key_retention_ms=spent_key_retention_ms, preview=preview, authorize=authorize,
335
- approval=approval, project_receipt=project_receipt, resolve_receipt=resolve_receipt, async_mode=True))
338
+ approval=approval, project_receipt=project_receipt, resolve_receipt=resolve_receipt, async_mode=True,
339
+ binding_context=snapshot_binding_context(binding_context), on_replay=on_replay))
336
340
 
337
341
  def _flow(
338
342
  self, *, operation: str, input_value: Any, handler: ToolHook, scope: str,
@@ -340,6 +344,7 @@ class WriteGuard:
340
344
  ttl_ms: int | None, spent_key_retention_ms: int | None, preview: ToolHook | None,
341
345
  authorize: ToolHook | None, approval: ApprovalHook | None, project_receipt: ReceiptHook | None,
342
346
  resolve_receipt: ReceiptHook | None, async_mode: bool = False, offload_handler: bool = False,
347
+ binding_context: Any = _OMITTED, on_replay: ReplayHook | None = None,
343
348
  ) -> Generator[Any, Any, WriteOutcome]:
344
349
  store_call = _store_call_async if async_mode else _store_call
345
350
  if not isinstance(operation, str) or not operation.strip() or not isinstance(scope, str) or not scope.strip():
@@ -362,7 +367,7 @@ class WriteGuard:
362
367
 
363
368
  checked_time(now_override())
364
369
  key = None if dry_run and idempotency_key is None else validate_idempotency_key(idempotency_key)
365
- input_hash = hash_snapshot(operation, scope, input_value)
370
+ input_hash = hash_snapshot(operation, scope, input_value, binding_context)
366
371
  context = WriteContext(operation=operation, scope=scope, correlation_id=self._generate_id("corr"),
367
372
  input_hash=input_hash, idempotency_key=key, intent=intent,
368
373
  provider_key=None if key is None else _binding_key("mcpw_", scope, operation, key))
@@ -407,6 +412,8 @@ class WriteGuard:
407
412
  result = receipt["value"]
408
413
  else:
409
414
  raise _replay_unavailable()
415
+ if on_replay is not None:
416
+ yield on_replay(result, input_value, context)
410
417
  return WriteOutcome(**outcome, dry_run=False, replay=True, result=result, receipt=receipt)
411
418
  if claim.outcome != "claimed":
412
419
  raise WriteSafetyError("store_error", "Idempotency store returned an invalid claim.")