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.
File without changes
@@ -0,0 +1,123 @@
1
+ # Keep this script identical to the TypeScript and Rust source copies.
2
+ _REDIS_WRITE_LUA = """
3
+ local key = KEYS[1]
4
+ local token = ARGV[1]
5
+ local max_safe = 9007199254740991
6
+
7
+ local function uint(value)
8
+ if not value or not string.match(value, '^%d+$') then return nil end
9
+ local number = tonumber(value)
10
+ if number and number <= max_safe then return number end
11
+ end
12
+
13
+ local function text(number)
14
+ return string.format('%.0f', number)
15
+ end
16
+
17
+ local function store_error()
18
+ return redis.error_reply('ERR malformed mcp-writes record or response')
19
+ end
20
+
21
+ local kind = redis.call('TYPE', key).ok
22
+ if kind ~= 'none' and kind ~= 'hash' then return store_error() end
23
+ local record = {}
24
+ if kind == 'hash' then
25
+ local fields = redis.call('HGETALL', key)
26
+ for index = 1, #fields, 2 do record[fields[index]] = fields[index + 1] end
27
+ local created = uint(record.createdAtMs)
28
+ if not created or not record.inputHash or record.inputHash == ''
29
+ or not record.claimToken or record.claimToken == '' then
30
+ return store_error()
31
+ end
32
+ if record.status == 'in_progress' then
33
+ if not uint(record.leaseExpiresAtMs) or uint(record.leaseExpiresAtMs) <= created
34
+ or record.completedAtMs or record.expiresAtMs or record.retainUntilMs
35
+ or record.receiptJson or record.replayUnavailable then return store_error() end
36
+ elseif record.status == 'succeeded' then
37
+ local completed = uint(record.completedAtMs)
38
+ local expires = uint(record.expiresAtMs)
39
+ local retain = uint(record.retainUntilMs)
40
+ if not completed or not expires or not retain or expires <= completed or retain < expires
41
+ or record.leaseExpiresAtMs
42
+ or (record.replayUnavailable ~= '0' and record.replayUnavailable ~= '1')
43
+ or (record.replayUnavailable == '0' and (not record.receiptJson or record.receiptJson == ''))
44
+ or (record.replayUnavailable == '1' and record.receiptJson) then
45
+ return store_error()
46
+ end
47
+ else
48
+ return store_error()
49
+ end
50
+ end
51
+
52
+ if action == 'release' then
53
+ if record.status ~= 'in_progress' or record.claimToken ~= token then return 0 end
54
+ return redis.call('DEL', key)
55
+ end
56
+
57
+ local now
58
+ if ARGV[2] == '' then
59
+ local clock = redis.call('TIME')
60
+ now = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
61
+ else
62
+ now = uint(ARGV[2])
63
+ end
64
+ local duration = uint(ARGV[3])
65
+ if not now or not duration or duration == 0 or now + duration > max_safe
66
+ or not token or token == '' then
67
+ return redis.error_reply('ERR invalid mcp-writes timestamp or duration')
68
+ end
69
+ local deadline = now + duration
70
+
71
+ if action == 'claim' then
72
+ local hash = ARGV[4]
73
+ if not hash or hash == '' then return store_error() end
74
+ if record.status == 'succeeded' and (record.replayUnavailable == '1' or now < uint(record.retainUntilMs)) then
75
+ return {'existing', text(now), record.inputHash, record.createdAtMs,
76
+ record.completedAtMs, record.expiresAtMs, record.retainUntilMs,
77
+ record.replayUnavailable, record.receiptJson or ''}
78
+ end
79
+ if record.status == 'in_progress' then
80
+ return {'in_progress', text(now), record.inputHash, record.createdAtMs,
81
+ record.claimToken, record.leaseExpiresAtMs}
82
+ end
83
+ if kind == 'hash' then redis.call('DEL', key) end
84
+ redis.call('HSET', key, 'status', 'in_progress', 'claimToken', token,
85
+ 'inputHash', hash, 'createdAtMs', text(now), 'leaseExpiresAtMs', text(deadline))
86
+ return {'claimed', '0'}
87
+ end
88
+
89
+ if action == 'extend' then
90
+ if record.status ~= 'in_progress' or record.claimToken ~= token
91
+ or now >= uint(record.leaseExpiresAtMs) then return 0 end
92
+ redis.call('HSET', key, 'leaseExpiresAtMs', text(math.max(deadline, uint(record.leaseExpiresAtMs))))
93
+ return 1
94
+ end
95
+
96
+ if action == 'complete' then
97
+ local retain = uint(ARGV[4])
98
+ local marker = ARGV[5]
99
+ local receipt = ARGV[6]
100
+ if not retain or retain < duration or now + retain > max_safe
101
+ or (marker ~= '0' and marker ~= '1')
102
+ or (marker == '0' and (not receipt or receipt == '')) then return store_error() end
103
+ if record.claimToken ~= token then return 0 end
104
+ if record.status == 'succeeded' then return 1 end
105
+ redis.call('HSET', key, 'status', 'succeeded', 'completedAtMs', text(now),
106
+ 'expiresAtMs', text(deadline), 'retainUntilMs', text(now + retain), 'replayUnavailable', marker)
107
+ redis.call('HDEL', key, 'leaseExpiresAtMs')
108
+ if marker == '0' then
109
+ redis.call('HSET', key, 'receiptJson', receipt)
110
+ redis.call('PEXPIRE', key, text(retain))
111
+ else
112
+ redis.call('PERSIST', key)
113
+ end
114
+ return 1
115
+ end
116
+
117
+ return store_error()
118
+ """.strip()
119
+
120
+ REDIS_CLAIM_LUA = "local action = 'claim'\n" + _REDIS_WRITE_LUA
121
+ REDIS_COMPLETE_LUA = "local action = 'complete'\n" + _REDIS_WRITE_LUA
122
+ REDIS_RELEASE_LUA = "local action = 'release'\n" + _REDIS_WRITE_LUA
123
+ REDIS_EXTEND_LEASE_LUA = "local action = 'extend'\n" + _REDIS_WRITE_LUA
@@ -0,0 +1,526 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import json
5
+ import math
6
+ import re
7
+ import sqlite3
8
+ import threading
9
+ from collections.abc import Callable, Iterator, Sequence
10
+ from contextlib import contextmanager
11
+ from dataclasses import dataclass
12
+ from os import PathLike
13
+ from typing import Any, Literal, NoReturn, Protocol
14
+ from urllib.parse import quote
15
+
16
+ from .canonical import MAX_SAFE_INTEGER, snapshot_json
17
+ from .errors import WriteSafetyError
18
+ from .redis_script import REDIS_CLAIM_LUA, REDIS_COMPLETE_LUA, REDIS_EXTEND_LEASE_LUA, REDIS_RELEASE_LUA
19
+ from .timing import DEFAULT_SPENT_KEY_RETENTION_MS, current_ms, deadline, retention, timestamp
20
+
21
+ TABLE_NAME_PATTERN = re.compile(r"[a-z_][a-z0-9_]{0,62}")
22
+ DEFAULT_TABLE_NAME = "mcp_write_receipts"
23
+ _PG_NOW = "floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint"
24
+ _SQL_FIELDS = """status, claim_token, input_hash, {receipt} AS receipt_json, created_at_ms,
25
+ completed_at_ms, lease_expires_at_ms, expires_at_ms, retain_until_ms"""
26
+
27
+
28
+ def _validate_table_name(name: str) -> str:
29
+ if not TABLE_NAME_PATTERN.fullmatch(name):
30
+ raise WriteSafetyError("validation", "Table name must use lowercase letters, digits, and underscores.")
31
+ return name
32
+
33
+
34
+ def _table_sql(table_name: str, clock_type: str, receipt_type: str) -> str:
35
+ return f"""CREATE TABLE IF NOT EXISTS {_validate_table_name(table_name)} (
36
+ scope TEXT NOT NULL,
37
+ operation TEXT NOT NULL,
38
+ idempotency_key TEXT NOT NULL,
39
+ status TEXT NOT NULL CHECK (status IN ('in_progress', 'succeeded')),
40
+ claim_token TEXT,
41
+ input_hash TEXT NOT NULL,
42
+ receipt_json {receipt_type},
43
+ created_at_ms {clock_type} NOT NULL,
44
+ completed_at_ms {clock_type},
45
+ lease_expires_at_ms {clock_type},
46
+ expires_at_ms {clock_type},
47
+ retain_until_ms {clock_type},
48
+ PRIMARY KEY (scope, operation, idempotency_key)
49
+ );"""
50
+
51
+
52
+ def sqlite_schema_sql(table_name: str = DEFAULT_TABLE_NAME) -> str:
53
+ return _table_sql(table_name, "INTEGER", "TEXT") + (
54
+ f"\nCREATE INDEX IF NOT EXISTS {table_name}_expires_at_idx ON {table_name}(expires_at_ms);"
55
+ )
56
+
57
+
58
+ def postgres_schema_sql(table_name: str = DEFAULT_TABLE_NAME) -> str:
59
+ return _table_sql(table_name, "BIGINT", "JSONB") + (
60
+ f"\nCREATE INDEX IF NOT EXISTS expiry_{table_name} ON {table_name}(expires_at_ms);"
61
+ )
62
+
63
+
64
+ SQLITE_SCHEMA_SQL = sqlite_schema_sql()
65
+ POSTGRES_SCHEMA_SQL = postgres_schema_sql()
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class ClaimResult:
70
+ outcome: Literal["claimed", "in_progress", "existing"]
71
+ record: dict[str, Any] | None = None
72
+ took_over_expired_lease: bool = False
73
+ now_ms: int | None = None
74
+
75
+
76
+ class WriteStore(Protocol):
77
+ def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
78
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult: ...
79
+
80
+ def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
81
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
82
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
83
+ replay_unavailable: bool = False) -> bool: ...
84
+
85
+ def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool: ...
86
+
87
+ def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
88
+ lease_ms: int, now_ms: int | None = None) -> bool: ...
89
+
90
+
91
+ class AsyncWriteStore(Protocol):
92
+ async def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
93
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult: ...
94
+
95
+ async def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
96
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
97
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
98
+ replay_unavailable: bool = False) -> bool: ...
99
+
100
+ async def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool: ...
101
+
102
+ async def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
103
+ lease_ms: int, now_ms: int | None = None) -> bool: ...
104
+
105
+
106
+ def _now(now_ms: int | None) -> int:
107
+ return timestamp(current_ms() if now_ms is None else now_ms)
108
+
109
+
110
+ def _receipt_json(receipt: Any, unavailable: bool) -> str | None:
111
+ return None if unavailable else json.dumps(snapshot_json(receipt), ensure_ascii=False, allow_nan=False)
112
+
113
+
114
+ def _reject_non_finite(_: str) -> NoReturn:
115
+ raise ValueError("Non-finite JSON number.")
116
+
117
+
118
+ def _receipt_float(token: str) -> float:
119
+ value = float(token)
120
+ if not math.isfinite(value):
121
+ _reject_non_finite(token)
122
+ return value
123
+
124
+
125
+ def _receipt_int(token: str) -> int | float:
126
+ value = int(token)
127
+ return value if abs(value) <= MAX_SAFE_INTEGER else _receipt_float(token)
128
+
129
+
130
+ def _decode_receipt(encoded: str | None) -> Any:
131
+ if encoded is None:
132
+ return None
133
+ try:
134
+ receipt = json.loads(encoded, parse_constant=_reject_non_finite, parse_float=_receipt_float, parse_int=_receipt_int)
135
+ snapshot_json(receipt)
136
+ return receipt
137
+ except (ValueError, RecursionError, WriteSafetyError) as exc:
138
+ raise WriteSafetyError("store_error", "Store returned an invalid receipt.") from exc
139
+
140
+
141
+ def _record_ms(value: Any) -> int:
142
+ try:
143
+ if isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
144
+ value = int(value)
145
+ return timestamp(value)
146
+ except (ValueError, WriteSafetyError) as exc:
147
+ raise WriteSafetyError("store_error", "Store returned an invalid timestamp.") from exc
148
+
149
+
150
+ def _decode_claim(row: Sequence[Any], now_ms: int) -> ClaimResult:
151
+ status, token, input_hash, receipt, created, completed, lease, expires, retain = row
152
+ if not isinstance(input_hash, str) or not input_hash:
153
+ raise WriteSafetyError("store_error", "Store returned an invalid input hash.")
154
+ record = {"status": status, "inputHash": input_hash, "createdAtMs": _record_ms(created)}
155
+ if status == "in_progress" and isinstance(token, str) and token:
156
+ record.update(claimToken=token, leaseExpiresAtMs=_record_ms(lease))
157
+ return ClaimResult("in_progress", record, now_ms=now_ms)
158
+ if status == "succeeded" and (receipt is None or isinstance(receipt, str)):
159
+ record.update(receipt=_decode_receipt(receipt),
160
+ completedAtMs=_record_ms(completed), expiresAtMs=_record_ms(expires),
161
+ retainUntilMs=_record_ms(retain))
162
+ if record["expiresAtMs"] <= record["completedAtMs"] or record["retainUntilMs"] < record["expiresAtMs"]:
163
+ raise WriteSafetyError("store_error", "Store returned an invalid receipt lifetime.")
164
+ if receipt is None:
165
+ record["replayUnavailable"] = True
166
+ return ClaimResult("existing", record, now_ms=now_ms)
167
+ raise WriteSafetyError("store_error", "Store returned an invalid write record.")
168
+
169
+
170
+ class MemoryStore:
171
+ def __init__(self) -> None:
172
+ self._lock = threading.Lock()
173
+ self._records: dict[tuple[str, str, str], dict[str, Any]] = {}
174
+
175
+ def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
176
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult:
177
+ key = (scope, operation, idempotency_key)
178
+ now = _now(now_ms)
179
+ expires = deadline(now, lease_ms, "lease_ms")
180
+ with self._lock:
181
+ existing = self._records.get(key)
182
+ if existing is not None and existing["status"] == "succeeded":
183
+ if existing.get("replayUnavailable") or now < existing["retainUntilMs"]:
184
+ return ClaimResult("existing", copy.deepcopy(existing), now_ms=now)
185
+ existing = None
186
+ if existing is not None:
187
+ return ClaimResult("in_progress", copy.deepcopy(existing), now_ms=now)
188
+ self._records[key] = dict(status="in_progress", claimToken=claim_token, inputHash=input_hash,
189
+ createdAtMs=now, leaseExpiresAtMs=expires)
190
+ return ClaimResult("claimed")
191
+
192
+ def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
193
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
194
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
195
+ replay_unavailable: bool = False) -> bool:
196
+ key = (scope, operation, idempotency_key)
197
+ now = _now(now_ms)
198
+ expires = deadline(now, ttl_ms, "ttl_ms")
199
+ retain = deadline(now, retention(ttl_ms, spent_key_retention_ms), "spent_key_retention_ms")
200
+ with self._lock:
201
+ existing = self._records.get(key)
202
+ if existing is None or existing["claimToken"] != claim_token:
203
+ return False
204
+ if existing["status"] == "succeeded":
205
+ return True
206
+ encoded = _receipt_json(receipt, replay_unavailable)
207
+ self._records[key] = dict(status="succeeded", claimToken=claim_token,
208
+ inputHash=existing["inputHash"], createdAtMs=existing["createdAtMs"],
209
+ receipt=_decode_receipt(encoded), completedAtMs=now,
210
+ expiresAtMs=expires, retainUntilMs=retain)
211
+ if replay_unavailable:
212
+ self._records[key]["replayUnavailable"] = True
213
+ return True
214
+
215
+ def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool:
216
+ key = (scope, operation, idempotency_key)
217
+ with self._lock:
218
+ existing = self._records.get(key)
219
+ if existing is None or existing["status"] != "in_progress" or existing["claimToken"] != claim_token:
220
+ return False
221
+ del self._records[key]
222
+ return True
223
+
224
+ def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
225
+ lease_ms: int, now_ms: int | None = None) -> bool:
226
+ now = _now(now_ms)
227
+ expires = deadline(now, lease_ms, "lease_ms")
228
+ with self._lock:
229
+ existing = self._records.get((scope, operation, idempotency_key))
230
+ if (existing is None or existing["status"] != "in_progress" or existing["claimToken"] != claim_token
231
+ or existing["leaseExpiresAtMs"] <= now):
232
+ return False
233
+ existing["leaseExpiresAtMs"] = max(expires, existing["leaseExpiresAtMs"])
234
+ return True
235
+
236
+ def purge_expired(self, before_ms: int) -> int:
237
+ timestamp(before_ms, "before_ms")
238
+ with self._lock:
239
+ keys = [key for key, rec in self._records.items()
240
+ if rec["status"] == "succeeded" and not rec.get("replayUnavailable") and rec["retainUntilMs"] <= before_ms]
241
+ for key in keys:
242
+ del self._records[key]
243
+ return len(keys)
244
+
245
+ def size(self) -> int:
246
+ with self._lock:
247
+ return len(self._records)
248
+
249
+
250
+ class SqliteStore:
251
+ _key_where = "scope = ? AND operation = ? AND idempotency_key = ?"
252
+ _owned_where = _key_where + " AND status = 'in_progress' AND claim_token = ?"
253
+
254
+ def __init__(self, conn: sqlite3.Connection | str | PathLike[str], table_name: str = DEFAULT_TABLE_NAME) -> None:
255
+ self._table = _validate_table_name(table_name)
256
+ self.schema_sql = sqlite_schema_sql(self._table)
257
+ self._lock = threading.Lock()
258
+ self._owns_connection = not isinstance(conn, sqlite3.Connection)
259
+ self._conn = conn if isinstance(conn, sqlite3.Connection) else sqlite3.connect(conn, check_same_thread=False)
260
+
261
+ def close(self) -> None:
262
+ """Close a connection opened by this store."""
263
+ with self._lock:
264
+ if self._owns_connection:
265
+ self._conn.close()
266
+
267
+ @contextmanager
268
+ def _transaction(self) -> Iterator[sqlite3.Connection]:
269
+ with self._lock:
270
+ if self._conn.in_transaction:
271
+ raise WriteSafetyError("store_error", "SQLite write store requires a connection outside application transactions.")
272
+ self._conn.execute("BEGIN IMMEDIATE")
273
+ try:
274
+ yield self._conn
275
+ self._conn.execute("COMMIT")
276
+ except BaseException:
277
+ self._conn.execute("ROLLBACK")
278
+ raise
279
+
280
+ def init(self) -> None:
281
+ with self._transaction() as db:
282
+ for statement in self.schema_sql.split(";"):
283
+ if statement.strip():
284
+ db.execute(statement)
285
+ if not db.execute(f"SELECT name FROM pragma_table_info('{self._table}') WHERE name = 'retain_until_ms'").fetchone():
286
+ db.execute(f"ALTER TABLE {self._table} ADD COLUMN retain_until_ms INTEGER")
287
+ db.execute(f"""UPDATE {self._table}
288
+ SET retain_until_ms = MAX(expires_at_ms, completed_at_ms + {DEFAULT_SPENT_KEY_RETENTION_MS})
289
+ WHERE status = 'succeeded' AND retain_until_ms IS NULL""")
290
+ db.execute(f"CREATE INDEX IF NOT EXISTS {self._table}_retain_until_idx ON {self._table}(retain_until_ms)")
291
+
292
+ def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
293
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult:
294
+ key = (scope, operation, idempotency_key)
295
+ with self._transaction() as db:
296
+ now = _now(now_ms)
297
+ expires = deadline(now, lease_ms, "lease_ms")
298
+ fields = _SQL_FIELDS.format(receipt="receipt_json")
299
+ row = db.execute(f"SELECT {fields} FROM {self._table} WHERE {self._key_where}", key).fetchone()
300
+ if row is not None:
301
+ existing = _decode_claim(row, now)
302
+ assert existing.record is not None
303
+ if (existing.outcome != "existing" or existing.record.get("replayUnavailable")
304
+ or now < existing.record["retainUntilMs"]):
305
+ return existing
306
+ db.execute(f"DELETE FROM {self._table} WHERE {self._key_where}", key)
307
+ db.execute(f"""INSERT INTO {self._table} (scope, operation, idempotency_key, status,
308
+ claim_token, input_hash, created_at_ms, lease_expires_at_ms)
309
+ VALUES (?, ?, ?, 'in_progress', ?, ?, ?, ?)""", (*key, claim_token, input_hash, now, expires))
310
+ return ClaimResult("claimed")
311
+
312
+ def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
313
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
314
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
315
+ replay_unavailable: bool = False) -> bool:
316
+ owned = (scope, operation, idempotency_key, claim_token)
317
+ with self._transaction() as db:
318
+ now = _now(now_ms)
319
+ expires = deadline(now, ttl_ms, "ttl_ms")
320
+ retain = deadline(now, retention(ttl_ms, spent_key_retention_ms), "spent_key_retention_ms")
321
+ result = db.execute(f"""UPDATE {self._table} SET status = 'succeeded', receipt_json = ?,
322
+ completed_at_ms = ?, expires_at_ms = ?, retain_until_ms = ?, lease_expires_at_ms = NULL
323
+ WHERE {self._owned_where}""", (_receipt_json(receipt, replay_unavailable), now, expires, retain, *owned))
324
+ return result.rowcount > 0 or db.execute(f"""SELECT 1 FROM {self._table} WHERE {self._key_where}
325
+ AND status = 'succeeded' AND claim_token = ?""", owned).fetchone() is not None
326
+
327
+ def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool:
328
+ with self._transaction() as db:
329
+ return db.execute(f"DELETE FROM {self._table} WHERE {self._owned_where}",
330
+ (scope, operation, idempotency_key, claim_token)).rowcount > 0
331
+
332
+ def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
333
+ lease_ms: int, now_ms: int | None = None) -> bool:
334
+ with self._transaction() as db:
335
+ now = _now(now_ms)
336
+ return db.execute(f"""UPDATE {self._table}
337
+ SET lease_expires_at_ms = MAX(lease_expires_at_ms, ?)
338
+ WHERE {self._owned_where} AND lease_expires_at_ms > ?""",
339
+ (deadline(now, lease_ms, "lease_ms"), scope, operation, idempotency_key, claim_token, now)).rowcount > 0
340
+
341
+ def purge_expired(self, before_ms: int) -> int:
342
+ with self._transaction() as db:
343
+ return db.execute(f"""DELETE FROM {self._table}
344
+ WHERE status = 'succeeded' AND receipt_json IS NOT NULL AND retain_until_ms <= ?""",
345
+ (timestamp(before_ms, "before_ms"),)).rowcount
346
+
347
+
348
+ def _pg_query_adapter(source: Any) -> Callable[[str, tuple[Any, ...]], Sequence[Sequence[Any]]]:
349
+ if callable(source):
350
+ return source
351
+ cursor_fn = getattr(source, "cursor", None)
352
+ if not callable(cursor_fn):
353
+ raise WriteSafetyError("validation", "PostgresStore requires a query callable or an autocommit DB-API connection.")
354
+ if getattr(source, "autocommit", None) is not True:
355
+ raise WriteSafetyError("validation", "PostgresStore requires a connection with autocommit=True.")
356
+ lock = threading.Lock()
357
+
358
+ def run(sql: str, params: tuple[Any, ...]) -> Sequence[Sequence[Any]]:
359
+ if getattr(source, "autocommit", None) is not True:
360
+ raise WriteSafetyError("store_error", "PostgresStore connection must stay in autocommit=True mode.")
361
+ with lock, source.cursor() as cur:
362
+ cur.execute(sql, params or None)
363
+ return cur.fetchall() if cur.description is not None else []
364
+
365
+ return run
366
+
367
+
368
+ class PostgresStore:
369
+ """Accepts an autocommit DB-API/psycopg connection or a query callable."""
370
+
371
+ _key_where = "scope = %s AND operation = %s AND idempotency_key = %s"
372
+ _owned_where = _key_where + " AND status = 'in_progress' AND claim_token = %s"
373
+
374
+ def __init__(self, query_fn: Any, table_name: str = DEFAULT_TABLE_NAME) -> None:
375
+ self._query = _pg_query_adapter(query_fn)
376
+ self._table = _validate_table_name(table_name)
377
+ self.schema_sql = postgres_schema_sql(self._table)
378
+
379
+ def init(self) -> None:
380
+ for statement in self.schema_sql.split(";"):
381
+ if statement.strip():
382
+ self._query(statement, ())
383
+ self._query(f"ALTER TABLE {self._table} ADD COLUMN IF NOT EXISTS retain_until_ms BIGINT", ())
384
+ self._query(f"""UPDATE {self._table}
385
+ SET retain_until_ms = GREATEST(expires_at_ms, completed_at_ms + {DEFAULT_SPENT_KEY_RETENTION_MS})
386
+ WHERE status = 'succeeded' AND retain_until_ms IS NULL""", ())
387
+ self._query(f"CREATE INDEX IF NOT EXISTS retention_{self._table} ON {self._table}(retain_until_ms)", ())
388
+
389
+ def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
390
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult:
391
+ deadline(_now(now_ms), lease_ms, "lease_ms")
392
+ observed = f"COALESCE(%s::bigint, {_PG_NOW})"
393
+ key = (scope, operation, idempotency_key)
394
+ for _ in range(3):
395
+ rows = self._query(f"""INSERT INTO {self._table} AS stored (
396
+ scope, operation, idempotency_key, status, claim_token, input_hash, created_at_ms, lease_expires_at_ms
397
+ ) SELECT %s, %s, %s, 'in_progress', %s, %s, observed.now_ms, observed.now_ms + %s::bigint
398
+ FROM (SELECT {observed} AS now_ms) AS observed
399
+ WHERE observed.now_ms BETWEEN 0 AND {MAX_SAFE_INTEGER} - %s::bigint
400
+ ON CONFLICT (scope, operation, idempotency_key) DO UPDATE SET
401
+ status = 'in_progress', claim_token = EXCLUDED.claim_token, input_hash = EXCLUDED.input_hash,
402
+ created_at_ms = {observed},
403
+ lease_expires_at_ms = {observed} + %s::bigint,
404
+ receipt_json = NULL, completed_at_ms = NULL, expires_at_ms = NULL, retain_until_ms = NULL
405
+ WHERE stored.status = 'succeeded' AND stored.receipt_json IS NOT NULL AND stored.retain_until_ms <= {observed}
406
+ AND {observed} BETWEEN 0 AND {MAX_SAFE_INTEGER} - %s::bigint
407
+ RETURNING 1""",
408
+ (*key, claim_token, input_hash, lease_ms, now_ms, lease_ms, now_ms, now_ms, lease_ms,
409
+ now_ms, now_ms, lease_ms))
410
+ if rows:
411
+ return ClaimResult("claimed")
412
+ fields = _SQL_FIELDS.format(receipt="receipt_json::text")
413
+ rows = self._query(f"""SELECT {fields}, {observed} AS now_ms FROM {self._table}
414
+ WHERE {self._key_where}""", (now_ms, *key))
415
+ if not rows:
416
+ continue
417
+ now = _record_ms(rows[0][-1])
418
+ existing = _decode_claim(rows[0][:-1], now)
419
+ assert existing.record is not None
420
+ if (existing.outcome == "existing" and not existing.record.get("replayUnavailable")
421
+ and existing.record["retainUntilMs"] <= now):
422
+ continue
423
+ return existing
424
+ raise WriteSafetyError("store_error", "Postgres claim contended repeatedly.")
425
+
426
+ def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
427
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
428
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
429
+ replay_unavailable: bool = False) -> bool:
430
+ retain = retention(ttl_ms, spent_key_retention_ms)
431
+ deadline(_now(now_ms), retain, "spent_key_retention_ms")
432
+ owned = (scope, operation, idempotency_key, claim_token)
433
+ rows = self._query(f"""WITH observed AS MATERIALIZED (SELECT COALESCE(%s::bigint, {_PG_NOW}) AS now_ms)
434
+ UPDATE {self._table} SET status = 'succeeded', receipt_json = %s::jsonb, completed_at_ms = observed.now_ms,
435
+ expires_at_ms = observed.now_ms + %s::bigint, retain_until_ms = observed.now_ms + %s::bigint,
436
+ lease_expires_at_ms = NULL FROM observed WHERE {self._owned_where}
437
+ AND observed.now_ms BETWEEN 0 AND {MAX_SAFE_INTEGER} - %s::bigint RETURNING idempotency_key""",
438
+ (now_ms, _receipt_json(receipt, replay_unavailable), ttl_ms, retain, *owned, retain))
439
+ return bool(rows or self._query(f"""SELECT 1 FROM {self._table} WHERE {self._key_where}
440
+ AND status = 'succeeded' AND claim_token = %s""", owned))
441
+
442
+ def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool:
443
+ return bool(self._query(f"DELETE FROM {self._table} WHERE {self._owned_where} RETURNING idempotency_key",
444
+ (scope, operation, idempotency_key, claim_token)))
445
+
446
+ def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
447
+ lease_ms: int, now_ms: int | None = None) -> bool:
448
+ deadline(_now(now_ms), lease_ms, "lease_ms")
449
+ now = f"COALESCE(%s::bigint, {_PG_NOW})"
450
+ return bool(self._query(f"""UPDATE {self._table} SET lease_expires_at_ms = GREATEST(lease_expires_at_ms, {now} + %s::bigint)
451
+ WHERE {self._owned_where} AND lease_expires_at_ms > {now}
452
+ AND {now} BETWEEN 0 AND {MAX_SAFE_INTEGER} - %s::bigint RETURNING idempotency_key""",
453
+ (now_ms, lease_ms, scope, operation, idempotency_key, claim_token, now_ms, now_ms, lease_ms)))
454
+
455
+ def purge_expired(self, before_ms: int) -> int:
456
+ rows = self._query(f"""WITH deleted AS (DELETE FROM {self._table}
457
+ WHERE status = 'succeeded' AND receipt_json IS NOT NULL AND retain_until_ms <= %s RETURNING 1)
458
+ SELECT count(*) FROM deleted""", (timestamp(before_ms, "before_ms"),))
459
+ return int(rows[0][0])
460
+
461
+
462
+ def build_redis_store_key(prefix: str, scope: str, operation: str, idempotency_key: str) -> str:
463
+ return prefix + ":".join(quote(value, safe="") for value in (scope, operation, idempotency_key))
464
+
465
+
466
+ class RedisStore:
467
+ """Atomic store using the redis-py eval(script, numkeys, key, *args) interface."""
468
+
469
+ def __init__(self, client: Any, *, key_prefix: str = "mcp-writes:") -> None:
470
+ self._client = client
471
+ self._prefix = key_prefix
472
+
473
+ def _eval(self, script: str, key: tuple[str, str, str], *args: str) -> Any:
474
+ try:
475
+ return self._client.eval(script, 1, build_redis_store_key(self._prefix, *key), *args)
476
+ except Exception as exc:
477
+ raise WriteSafetyError("store_error", "Redis write store operation failed.") from exc
478
+
479
+ @staticmethod
480
+ def _flag(value: Any) -> bool:
481
+ if type(value) is not int or value not in (0, 1):
482
+ raise WriteSafetyError("store_error", "Redis returned an invalid write status.")
483
+ return value == 1
484
+
485
+ def claim(self, *, scope: str, operation: str, idempotency_key: str, input_hash: str,
486
+ claim_token: str, lease_ms: int, now_ms: int | None = None) -> ClaimResult:
487
+ deadline(_now(now_ms), lease_ms, "lease_ms")
488
+ raw = self._eval(REDIS_CLAIM_LUA, (scope, operation, idempotency_key), claim_token,
489
+ "" if now_ms is None else str(now_ms), str(lease_ms), input_hash)
490
+ try:
491
+ if isinstance(raw, (list, tuple)) and all(isinstance(field, (str, bytes)) for field in raw):
492
+ fields = [field.decode("utf-8") if isinstance(field, bytes) else field for field in raw]
493
+ if len(fields) == 2 and fields[0] == "claimed" and fields[1] in ("0", "1"):
494
+ return ClaimResult("claimed", took_over_expired_lease=fields[1] == "1")
495
+ if len(fields) == 6 and fields[0] == "in_progress":
496
+ _, now, matched_hash, created, token, lease = fields
497
+ if _record_ms(lease) > _record_ms(created):
498
+ return _decode_claim(("in_progress", token, matched_hash, None, created, None, lease, None, None),
499
+ _record_ms(now))
500
+ if len(fields) == 9 and fields[0] == "existing":
501
+ _, now, matched_hash, created, completed, expires, retain, marker, receipt = fields
502
+ if (marker == "0" and receipt) or (marker == "1" and receipt == ""):
503
+ return _decode_claim(("succeeded", None, matched_hash, receipt if marker == "0" else None,
504
+ created, completed, None, expires, retain), _record_ms(now))
505
+ except UnicodeError as exc:
506
+ raise WriteSafetyError("store_error", "Redis returned invalid UTF-8.") from exc
507
+ raise WriteSafetyError("store_error", "Redis returned an invalid write record.")
508
+
509
+ def complete(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
510
+ receipt: Any, ttl_ms: int, now_ms: int | None = None,
511
+ spent_key_retention_ms: int = DEFAULT_SPENT_KEY_RETENTION_MS,
512
+ replay_unavailable: bool = False) -> bool:
513
+ retain = retention(ttl_ms, spent_key_retention_ms)
514
+ deadline(_now(now_ms), retain, "spent_key_retention_ms")
515
+ return self._flag(self._eval(REDIS_COMPLETE_LUA, (scope, operation, idempotency_key), claim_token,
516
+ "" if now_ms is None else str(now_ms), str(ttl_ms), str(retain),
517
+ "1" if replay_unavailable else "0", _receipt_json(receipt, replay_unavailable) or ""))
518
+
519
+ def release(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str) -> bool:
520
+ return self._flag(self._eval(REDIS_RELEASE_LUA, (scope, operation, idempotency_key), claim_token))
521
+
522
+ def extend_lease(self, *, scope: str, operation: str, idempotency_key: str, claim_token: str,
523
+ lease_ms: int, now_ms: int | None = None) -> bool:
524
+ deadline(_now(now_ms), lease_ms, "lease_ms")
525
+ return self._flag(self._eval(REDIS_EXTEND_LEASE_LUA, (scope, operation, idempotency_key), claim_token,
526
+ "" if now_ms is None else str(now_ms), str(lease_ms)))