stackdeck-mcp-writes 0.1.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 (25) hide show
  1. stackdeck_mcp_writes-0.1.0/LICENSE +21 -0
  2. stackdeck_mcp_writes-0.1.0/MANIFEST.in +1 -0
  3. stackdeck_mcp_writes-0.1.0/PKG-INFO +103 -0
  4. stackdeck_mcp_writes-0.1.0/README.md +78 -0
  5. stackdeck_mcp_writes-0.1.0/pyproject.toml +38 -0
  6. stackdeck_mcp_writes-0.1.0/setup.cfg +4 -0
  7. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/__init__.py +62 -0
  8. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/canonical.py +149 -0
  9. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/errors.py +86 -0
  10. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/guard.py +698 -0
  11. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/py.typed +0 -0
  12. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/redis_script.py +123 -0
  13. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/stores.py +526 -0
  14. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes/timing.py +34 -0
  15. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes.egg-info/PKG-INFO +103 -0
  16. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes.egg-info/SOURCES.txt +23 -0
  17. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes.egg-info/dependency_links.txt +1 -0
  18. stackdeck_mcp_writes-0.1.0/src/stackdeck_mcp_writes.egg-info/top_level.txt +1 -0
  19. stackdeck_mcp_writes-0.1.0/tests/fixtures/canonical-hash.json +79 -0
  20. stackdeck_mcp_writes-0.1.0/tests/fixtures/redis-keys.json +25 -0
  21. stackdeck_mcp_writes-0.1.0/tests/fixtures/write-guard.json +233 -0
  22. stackdeck_mcp_writes-0.1.0/tests/test_conformance.py +210 -0
  23. stackdeck_mcp_writes-0.1.0/tests/test_fastmcp.py +170 -0
  24. stackdeck_mcp_writes-0.1.0/tests/test_guard_failures.py +671 -0
  25. stackdeck_mcp_writes-0.1.0/tests/test_live_stores.py +81 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TrueWear, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ include tests/fixtures/*.json
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: stackdeck-mcp-writes
3
+ Version: 0.1.0
4
+ Summary: Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies.
5
+ Author: StackDeck
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://stackdeck.dev/mcp-writes
8
+ Project-URL: Documentation, https://github.com/stackdeckhq/mcp-writes/blob/main/SPEC.md
9
+ Project-URL: Source, https://github.com/stackdeckhq/mcp-writes
10
+ Project-URL: Issues, https://github.com/stackdeckhq/mcp-writes/issues
11
+ Keywords: mcp,fastmcp,model-context-protocol,idempotency,retries,receipts,write-safety,dry-run,ai-agents,stackdeck
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # stackdeck-mcp-writes
27
+
28
+ 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.
29
+
30
+ [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)
31
+
32
+ ## Why this exists
33
+
34
+ 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.
35
+
36
+ ```text
37
+ Plain write handler: 2 charges ($50.00) handler ran again
38
+ With stackdeck-mcp-writes: 1 charge ($25.00) replay: true
39
+ ```
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ pip install stackdeck-mcp-writes
45
+ ```
46
+
47
+ ## Quick start
48
+
49
+ ```python
50
+ from stackdeck_mcp_writes import MemoryStore, WriteGuard, safe_write_tool
51
+
52
+ guard = WriteGuard(store=MemoryStore())
53
+ caller = {"workspace_id": "workspace_1"}
54
+
55
+ @safe_write_tool(guard, name="invoices.refund", resolve_scope=lambda _args, _ctx: caller["workspace_id"])
56
+ def refund_invoice(invoice_id: str, amount_cents: int) -> dict[str, object]:
57
+ return {"refund_id": f"re_{invoice_id}", "amount_cents": amount_cents}
58
+
59
+ args = dict(invoice_id="invoice_42", amount_cents=500, idempotency_key="refund-42")
60
+ assert refund_invoice(**args)["replay"] is False
61
+ assert refund_invoice(**args)["replay"] is True
62
+ ```
63
+
64
+ ## FastMCP and official MCP server integration
65
+
66
+ 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`:
67
+
68
+ ```python
69
+ from fastmcp import Context, FastMCP
70
+ from stackdeck_mcp_writes import PostgresStore, WriteContext, WriteGuard, safe_write_tool
71
+
72
+ # Pass an autocommit psycopg/DB-API connection (or a query_fn callable).
73
+ store = PostgresStore(pg_conn)
74
+ store.init()
75
+ guard = WriteGuard(store=store)
76
+ mcp = FastMCP("billing")
77
+
78
+ @mcp.tool()
79
+ @safe_write_tool(
80
+ guard,
81
+ name="payments.refund",
82
+ resolve_scope=lambda _args, ctx: verified_actor(ctx).workspace_id,
83
+ authorize=lambda args, write: can_refund_payment(current_verified_actor(), write.scope, args["payment_intent_id"]),
84
+ )
85
+ async def refund_payment(payment_intent_id: str, amount_cents: int, ctx: Context, write: WriteContext) -> dict[str, object]:
86
+ refund = await stripe_refund(payment_intent_id, amount_cents, idempotency_key=write.provider_key)
87
+ return {"refund_id": refund["id"], "amount_cents": refund["amount"], "status": refund["status"]}
88
+ ```
89
+
90
+ ## Important usage rules
91
+
92
+ - **Keyword-only direct calls:** Construct with `WriteGuard(store=store)` and call `guard.execute(..., input_value=...)` or `await guard.execute_async(..., input_value=...)`.
93
+ - **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).
94
+ - **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.
95
+ - **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.
96
+ - **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.
97
+ - **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).
98
+
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
+
101
+ ## License
102
+
103
+ MIT. See [LICENSE](https://github.com/stackdeckhq/mcp-writes/blob/main/LICENSE).
@@ -0,0 +1,78 @@
1
+ # stackdeck-mcp-writes
2
+
3
+ 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.
4
+
5
+ [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)
6
+
7
+ ## Why this exists
8
+
9
+ 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.
10
+
11
+ ```text
12
+ Plain write handler: 2 charges ($50.00) handler ran again
13
+ With stackdeck-mcp-writes: 1 charge ($25.00) replay: true
14
+ ```
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pip install stackdeck-mcp-writes
20
+ ```
21
+
22
+ ## Quick start
23
+
24
+ ```python
25
+ from stackdeck_mcp_writes import MemoryStore, WriteGuard, safe_write_tool
26
+
27
+ guard = WriteGuard(store=MemoryStore())
28
+ caller = {"workspace_id": "workspace_1"}
29
+
30
+ @safe_write_tool(guard, name="invoices.refund", resolve_scope=lambda _args, _ctx: caller["workspace_id"])
31
+ def refund_invoice(invoice_id: str, amount_cents: int) -> dict[str, object]:
32
+ return {"refund_id": f"re_{invoice_id}", "amount_cents": amount_cents}
33
+
34
+ args = dict(invoice_id="invoice_42", amount_cents=500, idempotency_key="refund-42")
35
+ assert refund_invoice(**args)["replay"] is False
36
+ assert refund_invoice(**args)["replay"] is True
37
+ ```
38
+
39
+ ## FastMCP and official MCP server integration
40
+
41
+ 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`:
42
+
43
+ ```python
44
+ from fastmcp import Context, FastMCP
45
+ from stackdeck_mcp_writes import PostgresStore, WriteContext, WriteGuard, safe_write_tool
46
+
47
+ # Pass an autocommit psycopg/DB-API connection (or a query_fn callable).
48
+ store = PostgresStore(pg_conn)
49
+ store.init()
50
+ guard = WriteGuard(store=store)
51
+ mcp = FastMCP("billing")
52
+
53
+ @mcp.tool()
54
+ @safe_write_tool(
55
+ guard,
56
+ name="payments.refund",
57
+ resolve_scope=lambda _args, ctx: verified_actor(ctx).workspace_id,
58
+ authorize=lambda args, write: can_refund_payment(current_verified_actor(), write.scope, args["payment_intent_id"]),
59
+ )
60
+ async def refund_payment(payment_intent_id: str, amount_cents: int, ctx: Context, write: WriteContext) -> dict[str, object]:
61
+ refund = await stripe_refund(payment_intent_id, amount_cents, idempotency_key=write.provider_key)
62
+ return {"refund_id": refund["id"], "amount_cents": refund["amount"], "status": refund["status"]}
63
+ ```
64
+
65
+ ## Important usage rules
66
+
67
+ - **Keyword-only direct calls:** Construct with `WriteGuard(store=store)` and call `guard.execute(..., input_value=...)` or `await guard.execute_async(..., input_value=...)`.
68
+ - **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).
69
+ - **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.
70
+ - **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.
71
+ - **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.
72
+ - **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).
73
+
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
+
76
+ ## License
77
+
78
+ MIT. See [LICENSE](https://github.com/stackdeckhq/mcp-writes/blob/main/LICENSE).
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "stackdeck-mcp-writes"
7
+ version = "0.1.0"
8
+ description = "Safe writes for MCP servers: idempotency keys, conflict checks, in-flight locks, dry-run previews, and write receipts. Zero dependencies."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "StackDeck" }]
14
+ dependencies = []
15
+ keywords = ["mcp", "fastmcp", "model-context-protocol", "idempotency", "retries", "receipts", "write-safety", "dry-run", "ai-agents", "stackdeck"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Typing :: Typed",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://stackdeck.dev/mcp-writes"
30
+ Documentation = "https://github.com/stackdeckhq/mcp-writes/blob/main/SPEC.md"
31
+ Source = "https://github.com/stackdeckhq/mcp-writes"
32
+ Issues = "https://github.com/stackdeckhq/mcp-writes/issues"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.setuptools.package-data]
38
+ stackdeck_mcp_writes = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,62 @@
1
+ from .canonical import (
2
+ canonical_binding_json,
3
+ canonical_hash,
4
+ canonical_json,
5
+ validate_idempotency_key,
6
+ )
7
+ from .errors import WRITE_SAFETY_ERROR_CODES, PreEffectError, WriteSafetyError, WriteToolError
8
+ from .guard import ApprovalBinding, ApprovalHook, ApprovalRequest, WriteContext, WriteGuard, WriteOutcome, safe_write_tool
9
+ from .stores import (
10
+ POSTGRES_SCHEMA_SQL,
11
+ REDIS_CLAIM_LUA,
12
+ REDIS_COMPLETE_LUA,
13
+ REDIS_EXTEND_LEASE_LUA,
14
+ REDIS_RELEASE_LUA,
15
+ SQLITE_SCHEMA_SQL,
16
+ AsyncWriteStore,
17
+ ClaimResult,
18
+ MemoryStore,
19
+ PostgresStore,
20
+ RedisStore,
21
+ SqliteStore,
22
+ WriteStore,
23
+ build_redis_store_key,
24
+ postgres_schema_sql,
25
+ sqlite_schema_sql,
26
+ )
27
+ from .timing import DEFAULT_SPENT_KEY_RETENTION_MS
28
+
29
+ __all__ = [
30
+ "ApprovalBinding",
31
+ "ApprovalHook",
32
+ "ApprovalRequest",
33
+ "AsyncWriteStore",
34
+ "ClaimResult",
35
+ "MemoryStore",
36
+ "DEFAULT_SPENT_KEY_RETENTION_MS",
37
+ "POSTGRES_SCHEMA_SQL",
38
+ "PostgresStore",
39
+ "PreEffectError",
40
+ "REDIS_CLAIM_LUA",
41
+ "REDIS_COMPLETE_LUA",
42
+ "REDIS_EXTEND_LEASE_LUA",
43
+ "REDIS_RELEASE_LUA",
44
+ "RedisStore",
45
+ "SQLITE_SCHEMA_SQL",
46
+ "SqliteStore",
47
+ "WRITE_SAFETY_ERROR_CODES",
48
+ "WriteContext",
49
+ "WriteGuard",
50
+ "WriteOutcome",
51
+ "WriteSafetyError",
52
+ "WriteStore",
53
+ "WriteToolError",
54
+ "build_redis_store_key",
55
+ "canonical_binding_json",
56
+ "canonical_hash",
57
+ "canonical_json",
58
+ "postgres_schema_sql",
59
+ "safe_write_tool",
60
+ "sqlite_schema_sql",
61
+ "validate_idempotency_key",
62
+ ]
@@ -0,0 +1,149 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import re
7
+ from typing import Any
8
+
9
+ from .errors import WriteSafetyError
10
+
11
+ IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[\x21-\x7E]{1,200}$")
12
+ MAX_SAFE_INTEGER = 2**53 - 1
13
+
14
+
15
+ def validate_idempotency_key(value: Any) -> str:
16
+ if not isinstance(value, str) or not IDEMPOTENCY_KEY_PATTERN.fullmatch(value):
17
+ raise WriteSafetyError(
18
+ "validation",
19
+ "Writes require an idempotency_key of 1 to 200 printable ASCII characters with no spaces.",
20
+ details={"field": "idempotency_key"},
21
+ )
22
+ return value
23
+
24
+
25
+ def _immutable(*args: Any, **kwargs: Any) -> Any:
26
+ raise TypeError("Write input is immutable.")
27
+
28
+
29
+ class _FrozenList(list):
30
+ __slots__ = ()
31
+ __init__ = _immutable
32
+ __setitem__ = __delitem__ = __iadd__ = __imul__ = _immutable
33
+ append = clear = extend = insert = pop = remove = reverse = sort = _immutable
34
+
35
+
36
+ class _FrozenDict(dict):
37
+ __slots__ = ()
38
+ __init__ = _immutable
39
+ __setitem__ = __delitem__ = __ior__ = _immutable
40
+ clear = pop = popitem = setdefault = update = _immutable
41
+
42
+
43
+ def _valid_string(value: str) -> str:
44
+ if any(0xD800 <= ord(char) <= 0xDFFF for char in value):
45
+ raise WriteSafetyError("validation", "Write input contains an unpaired Unicode surrogate.")
46
+ return value
47
+
48
+
49
+ def _snapshot(value: Any, seen: set[int]) -> Any:
50
+ if value is None or type(value) is bool:
51
+ return value
52
+ if type(value) is str:
53
+ return _valid_string(value)
54
+ if type(value) is int:
55
+ if abs(value) <= MAX_SAFE_INTEGER:
56
+ return value
57
+ try:
58
+ value = float(value)
59
+ except OverflowError as exc:
60
+ raise WriteSafetyError("validation", "Write input must contain only finite JSON numbers.") from exc
61
+ if type(value) is float:
62
+ if not math.isfinite(value):
63
+ raise WriteSafetyError(
64
+ "validation",
65
+ "Write input must contain only finite JSON numbers.",
66
+ )
67
+ return value
68
+ obj_id = id(value)
69
+ if obj_id in seen:
70
+ raise WriteSafetyError("validation", "Write input contains a circular reference.")
71
+ if len(seen) >= 128:
72
+ raise WriteSafetyError("validation", "Write input is nested too deeply.")
73
+ seen.add(obj_id)
74
+ try:
75
+ if type(value) in (list, _FrozenList):
76
+ items = list.__new__(_FrozenList)
77
+ list.__init__(items, (_snapshot(item, seen) for item in value))
78
+ return items
79
+ if type(value) in (dict, _FrozenDict):
80
+ out = {}
81
+ for key, item in value.items():
82
+ if type(key) is not str:
83
+ raise WriteSafetyError("validation", "Object keys must be strings.")
84
+ out[_valid_string(key)] = _snapshot(item, seen)
85
+ result = dict.__new__(_FrozenDict)
86
+ dict.__init__(result, out)
87
+ return result
88
+ raise WriteSafetyError("validation", "Write input must contain only plain JSON values.")
89
+ finally:
90
+ seen.remove(obj_id)
91
+
92
+
93
+ def snapshot_json(value: Any) -> Any:
94
+ return _snapshot(value, set())
95
+
96
+
97
+ def _float_json(value: float) -> str:
98
+ if value == 0:
99
+ return "0"
100
+ sign = "-" if value < 0 else ""
101
+ mantissa, _, exponent = repr(abs(value)).partition("e")
102
+ integer, _, fraction = mantissa.partition(".")
103
+ digits = integer + fraction
104
+ leading_zeroes = len(digits) - len(digits.lstrip("0"))
105
+ digits = digits.strip("0")
106
+ point = len(integer) + int(exponent or "0") - leading_zeroes
107
+ if 0 < point <= 21:
108
+ return sign + digits[:point].ljust(point, "0") + ("." + digits[point:] if point < len(digits) else "")
109
+ if -6 < point <= 0:
110
+ return sign + "0." + "0" * -point + digits
111
+ fraction = "." + digits[1:] if len(digits) > 1 else ""
112
+ return f"{sign}{digits[0]}{fraction}e{point - 1:+d}"
113
+
114
+
115
+ def _serialize(value: Any) -> str:
116
+ if type(value) is float:
117
+ return _float_json(value)
118
+ if isinstance(value, list):
119
+ return "[" + ",".join(_serialize(item) for item in value) + "]"
120
+ if isinstance(value, dict):
121
+ return "{" + ",".join(_serialize(key) + ":" + _serialize(value[key]) for key in sorted(value)) + "}"
122
+ return json.dumps(value, ensure_ascii=False, allow_nan=False)
123
+
124
+
125
+ def canonical_json(value: Any) -> str:
126
+ return _serialize(snapshot_json(value))
127
+
128
+
129
+ def canonical_binding_json(operation: str, scope: str, input_value: Any) -> str:
130
+ return _serialize_binding(operation, scope, snapshot_json(input_value))
131
+
132
+
133
+ def canonical_hash(operation: str, scope: str, input_value: Any) -> str:
134
+ payload = canonical_binding_json(operation, scope, input_value)
135
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
136
+
137
+
138
+ def hash_snapshot(operation: str, scope: str, input_value: Any) -> str:
139
+ payload = _serialize_binding(operation, scope, input_value)
140
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
141
+
142
+
143
+ def _serialize_binding(operation: str, scope: str, input_value: Any) -> str:
144
+ return _serialize({
145
+ "version": 1,
146
+ "operation": _valid_string(operation),
147
+ "scope": _valid_string(scope),
148
+ "input": input_value,
149
+ })
@@ -0,0 +1,86 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ WRITE_SAFETY_ERROR_CODES = (
7
+ "validation",
8
+ "forbidden",
9
+ "conflict",
10
+ "in_progress",
11
+ "expired",
12
+ "replay_unavailable",
13
+ "outcome_unknown",
14
+ "approval_required",
15
+ "store_error",
16
+ )
17
+
18
+ HTTP_STATUS_BY_CODE: dict[str, int] = {
19
+ "validation": 400,
20
+ "forbidden": 403,
21
+ "conflict": 409,
22
+ "in_progress": 409,
23
+ "expired": 409,
24
+ "replay_unavailable": 409,
25
+ "outcome_unknown": 500,
26
+ "approval_required": 428,
27
+ "store_error": 503,
28
+ }
29
+
30
+ DEFAULT_RETRYABLE_BY_CODE: dict[str, bool] = {
31
+ "validation": False,
32
+ "forbidden": False,
33
+ "conflict": False,
34
+ "in_progress": True,
35
+ "expired": False,
36
+ "replay_unavailable": False,
37
+ "outcome_unknown": False,
38
+ "approval_required": False,
39
+ "store_error": True,
40
+ }
41
+
42
+
43
+ class WriteSafetyError(Exception):
44
+ def __init__(
45
+ self,
46
+ code: str,
47
+ message: str,
48
+ *,
49
+ retryable: bool | None = None,
50
+ details: dict[str, Any] | None = None,
51
+ ) -> None:
52
+ super().__init__(message)
53
+ if code not in HTTP_STATUS_BY_CODE:
54
+ raise ValueError(f"Unknown WriteSafetyError code: {code}")
55
+ self.code = code
56
+ self.message = message
57
+ self.status = HTTP_STATUS_BY_CODE[code]
58
+ self.http_status = self.status
59
+ self.retryable = DEFAULT_RETRYABLE_BY_CODE[code] if retryable is None else retryable
60
+ self.details = details
61
+
62
+ def to_payload(self) -> dict[str, Any]:
63
+ error: dict[str, Any] = {
64
+ "code": self.code,
65
+ "message": self.message,
66
+ "status": self.status,
67
+ "retryable": self.retryable,
68
+ }
69
+ if self.details is not None:
70
+ error["details"] = self.details
71
+ return {"ok": False, "error": error}
72
+
73
+
74
+ class PreEffectError(WriteSafetyError):
75
+ """The handler failed before attempting any external side effect."""
76
+
77
+ def __init__(self, message: str) -> None:
78
+ super().__init__("validation", message)
79
+
80
+
81
+ class WriteToolError(Exception):
82
+ """Sanitized MCP tool error when no FastMCP exception class is installed."""
83
+
84
+ def __init__(self, payload: dict[str, Any]) -> None:
85
+ super().__init__(json.dumps(payload))
86
+ self.payload = payload