stackdeck-mcp-writes 0.1.0__py3-none-any.whl

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