data-vault-mcp 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.
c26t/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """C26T: a prototype attested agentic data vault."""
@@ -0,0 +1 @@
1
+ {"git_revision": "17d9de4a342d9a2cbf78077c6fc57d91dae29828", "git_dirty": false, "source_sha256": "bab5226ed4836a58df41c9acef2f2cd36b345ed54ebac81cfe7fdca5a649874f", "package_version": "0.1.0", "self_reported": true}
c26t/build_version.py ADDED
@@ -0,0 +1,67 @@
1
+ """Bounded public version schema. Build stamps are reports, not attestation proofs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ PUBLIC_FIELDS = frozenset(
12
+ {
13
+ "git_revision",
14
+ "git_dirty",
15
+ "source_sha256",
16
+ "package_version",
17
+ "started_at_utc",
18
+ "provenance",
19
+ "self_reported",
20
+ }
21
+ )
22
+
23
+
24
+ def valid_hex(value: object, length: int) -> bool:
25
+ return isinstance(value, str) and re.fullmatch(f"[0-9a-f]{{{length}}}", value) is not None
26
+
27
+
28
+ def source_digest(package_dir: Path) -> str:
29
+ """Hash exact Python source bytes/names; exclude generated JSON and bytecode."""
30
+ digest = hashlib.sha256()
31
+ for path in sorted(package_dir.rglob("*.py")):
32
+ digest.update(path.relative_to(package_dir).as_posix().encode())
33
+ digest.update(b"\0")
34
+ digest.update(path.read_bytes())
35
+ return digest.hexdigest()
36
+
37
+
38
+ def validate_public_metadata(value: object) -> dict[str, Any]:
39
+ """Reject unknown keys, paths and malformed remote version reports."""
40
+ if not isinstance(value, dict) or set(value) != PUBLIC_FIELDS:
41
+ raise ValueError("invalid component version fields")
42
+ for key, length in (("git_revision", 40), ("source_sha256", 64)):
43
+ if value[key] is not None and not valid_hex(value[key], length):
44
+ raise ValueError("invalid component version digest")
45
+ if value["git_dirty"] is not None and type(value["git_dirty"]) is not bool:
46
+ raise ValueError("invalid component version dirty state")
47
+ if value["provenance"] not in ("checkout", "build_stamp", "unknown"):
48
+ raise ValueError("invalid component version provenance")
49
+ version = value["package_version"]
50
+ if not isinstance(version, str) or not re.fullmatch(r"[A-Za-z0-9.+_-]{1,128}", version):
51
+ raise ValueError("invalid component package version")
52
+ started = value["started_at_utc"]
53
+ if not isinstance(started, str) or len(started) > 40:
54
+ raise ValueError("invalid component start time")
55
+ try:
56
+ parsed = datetime.fromisoformat(started)
57
+ if parsed.utcoffset() is None or parsed.utcoffset().total_seconds() != 0:
58
+ raise ValueError("not UTC")
59
+ except ValueError as exc:
60
+ raise ValueError("invalid component start time") from exc
61
+ if value["provenance"] == "unknown" and value["git_revision"] is not None:
62
+ raise ValueError("unknown provenance cannot claim Git revision")
63
+ if type(value["self_reported"]) is not bool or value["self_reported"] != (
64
+ value["provenance"] == "build_stamp"
65
+ ):
66
+ raise ValueError("invalid component self-report state")
67
+ return dict(value)
@@ -0,0 +1,61 @@
1
+ """Public prototype client credentials compiled into the CVM worker and MCP.
2
+
3
+ These keys identify the disposable Shelbynet app to paid infrastructure. They
4
+ are copyable API client credentials, never the ACE root, worker signing key,
5
+ or a Gas Station Server key. This release reuses the disposable Shelbynet
6
+ client credentials only after the Gas Station policy includes its new module
7
+ address. Any other deployment needs an explicit policy and key review.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+
14
+ _SHELBYNET_CHAIN_ID = 119
15
+ _SHELBYNET_MODULE_ADDRESS = "0x9c303c89de51d9b5b67732462b320a577deb5e5895e3d304d2a6d095714629e5"
16
+ _SHELBYNET_FULLNODE_URL = "https://api.shelbynet.shelby.xyz/v1"
17
+ _SHELBYNET_GAS_STATION_URL = "https://api.shelbynet.shelby.xyz/gs/v1"
18
+
19
+ # Public Client key also embedded in the c26t MCP for this disposable app.
20
+ # The Gas Station policy, not secrecy of this value, bounds sponsored calls.
21
+ _BUNDLED_GAS_STATION_CLIENT_KEY = "AG-AL9R8P5UEKDJB6NHB3H6K2TVW2GHEXKVU"
22
+
23
+ # Separate public Client key for the c26t-cvm-prototype-client Shelby API
24
+ # resource. Fullnode, ACE, and Shelby calls all use this same API endpoint.
25
+ _BUNDLED_SHELBY_NODE_CLIENT_KEY = "AG-9TYW5IAKQEKGYGRPFYM85N8QCRXHPIK2G"
26
+
27
+
28
+ class CVMOperationalKeyError(RuntimeError):
29
+ """No approved public Client keys exist for this worker deployment."""
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class CVMOperationalKeys:
34
+ gas_station_api_key: str
35
+ shelby_api_key: str
36
+
37
+
38
+ def _valid_header_value(value: str | None) -> bool:
39
+ return (
40
+ isinstance(value, str)
41
+ and 1 <= len(value) <= 4096
42
+ and all(33 <= ord(character) <= 126 for character in value)
43
+ )
44
+
45
+
46
+ def bundled_operational_keys(
47
+ *, chain_id: int, module_address: str, fullnode_url: str, gas_station_url: str
48
+ ) -> CVMOperationalKeys:
49
+ """Return only the approved public keys for this exact prototype app."""
50
+ if (
51
+ chain_id != _SHELBYNET_CHAIN_ID
52
+ or module_address != _SHELBYNET_MODULE_ADDRESS
53
+ or fullnode_url != _SHELBYNET_FULLNODE_URL
54
+ or gas_station_url != _SHELBYNET_GAS_STATION_URL
55
+ ):
56
+ raise CVMOperationalKeyError("no bundled Client keys for this deployment")
57
+ if not _valid_header_value(_BUNDLED_GAS_STATION_CLIENT_KEY):
58
+ raise CVMOperationalKeyError("bundled Gas Station Client key is unavailable")
59
+ if not _valid_header_value(_BUNDLED_SHELBY_NODE_CLIENT_KEY):
60
+ raise CVMOperationalKeyError("bundled Shelby Client key is unavailable")
61
+ return CVMOperationalKeys(_BUNDLED_GAS_STATION_CLIENT_KEY, _BUNDLED_SHELBY_NODE_CLIENT_KEY)
c26t/cvm_crypto.py ADDED
@@ -0,0 +1,291 @@
1
+ """Domain-separated keys and authenticated ciphertexts for the CVM variant.
2
+
3
+ The stable root is reconstructed only inside an attested CVM. No caller-held
4
+ recovery key or mutable encrypted key snapshot is involved in this variant.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import re
13
+ import secrets
14
+ from dataclasses import dataclass
15
+
16
+ from aptos_sdk.bcs import Deserializer, Serializer
17
+ from cryptography.exceptions import InvalidTag
18
+ from cryptography.hazmat.primitives import hashes, serialization
19
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
20
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
21
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
22
+
23
+ _ADDRESS = re.compile(r"0x[0-9a-fA-F]{1,64}\Z")
24
+ _FRAME_VERSION = b"c26t-aead-v1\x00"
25
+ _NONCE_BYTES = 12
26
+ _MAX_RECORD_BYTES = 16 * 1024 - len(_FRAME_VERSION) - _NONCE_BYTES - 16
27
+ _MAX_INDEX_OBJECT_BYTES = 16 * 1024 * 1024
28
+
29
+
30
+ def _part(value: bytes) -> bytes:
31
+ return len(value).to_bytes(4, "big") + value
32
+
33
+
34
+ def _text(value: str, name: str) -> bytes:
35
+ if not isinstance(value, str) or not value or len(value) > 1024:
36
+ raise ValueError(f"{name} must be a nonempty bounded string")
37
+ encoded = value.encode("utf-8")
38
+ if len(encoded) > 4096 or any(ord(character) < 32 for character in value):
39
+ raise ValueError(f"{name} contains invalid characters")
40
+ return encoded
41
+
42
+
43
+ def aptos_address_bytes(address: str) -> bytes:
44
+ """Parse an Aptos account or object address into its 32-byte representation."""
45
+ if not isinstance(address, str) or _ADDRESS.fullmatch(address) is None:
46
+ raise ValueError("invalid Aptos address")
47
+ return bytes.fromhex(address[2:].zfill(64))
48
+
49
+
50
+ def aptos_address_text(address: bytes) -> str:
51
+ if not isinstance(address, bytes) or len(address) != 32:
52
+ raise ValueError("Aptos address must have 32 bytes")
53
+ return "0x" + address.hex()
54
+
55
+
56
+ def _open(key: bytes, aad: bytes, frame: bytes) -> bytes:
57
+ if (
58
+ not isinstance(frame, bytes)
59
+ or not frame.startswith(_FRAME_VERSION)
60
+ or len(frame) < len(_FRAME_VERSION) + _NONCE_BYTES + 16
61
+ ):
62
+ raise ValueError("invalid ciphertext frame")
63
+ offset = len(_FRAME_VERSION)
64
+ nonce = frame[offset : offset + _NONCE_BYTES]
65
+ ciphertext = frame[offset + _NONCE_BYTES :]
66
+ try:
67
+ return AESGCM(key).decrypt(nonce, ciphertext, aad)
68
+ except InvalidTag as exc:
69
+ raise ValueError("ciphertext authentication failed") from exc
70
+
71
+
72
+ def _seal(key: bytes, aad: bytes, plaintext: bytes, *, limit: int = _MAX_RECORD_BYTES) -> bytes:
73
+ if not isinstance(plaintext, bytes) or len(plaintext) > limit:
74
+ raise ValueError("plaintext is not bounded bytes")
75
+ nonce = secrets.token_bytes(_NONCE_BYTES)
76
+ return _FRAME_VERSION + nonce + AESGCM(key).encrypt(nonce, plaintext, aad)
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class CVMKeySchedule:
81
+ """A stable service root scoped to one chain and one Move deployment."""
82
+
83
+ root_seed: bytes
84
+ chain_id: int
85
+ module_address: str
86
+
87
+ def __post_init__(self) -> None:
88
+ if not isinstance(self.root_seed, bytes) or len(self.root_seed) != 32:
89
+ raise ValueError("root_seed must have 32 bytes")
90
+ if (
91
+ not isinstance(self.chain_id, int)
92
+ or isinstance(self.chain_id, bool)
93
+ or not 0 <= self.chain_id <= 255
94
+ ):
95
+ raise ValueError("chain_id must be an Aptos u8")
96
+ aptos_address_bytes(self.module_address)
97
+
98
+ def derive(self, purpose: str, *fields: bytes) -> bytes:
99
+ label = _text(purpose, "purpose")
100
+ if any(not isinstance(field, bytes) for field in fields):
101
+ raise ValueError("KDF fields must be bytes")
102
+ deployment = bytes([self.chain_id]) + aptos_address_bytes(self.module_address)
103
+ salt = hashlib.sha256(b"c26t/kdf-salt/v1\x00" + deployment).digest()
104
+ info = b"c26t/kdf-info/v1\x00" + _part(label) + b"".join(_part(field) for field in fields)
105
+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=info).derive(
106
+ self.root_seed
107
+ )
108
+
109
+ def user_private_key(self, issuer: str, subject: str) -> Ed25519PrivateKey:
110
+ seed = self.derive("user-sign", _text(issuer, "issuer"), _text(subject, "subject"))
111
+ return Ed25519PrivateKey.from_private_bytes(seed)
112
+
113
+ def user_address(self, issuer: str, subject: str) -> str:
114
+ public = (
115
+ self.user_private_key(issuer, subject)
116
+ .public_key()
117
+ .public_bytes(
118
+ encoding=serialization.Encoding.Raw,
119
+ format=serialization.PublicFormat.Raw,
120
+ )
121
+ )
122
+ return aptos_address_text(hashlib.sha3_256(public + b"\x00").digest())
123
+
124
+ def index_publisher_private_key(self) -> Ed25519PrivateKey:
125
+ return Ed25519PrivateKey.from_private_bytes(self.derive("index-publisher"))
126
+
127
+ def registrar_private_key(self) -> Ed25519PrivateKey:
128
+ return Ed25519PrivateKey.from_private_bytes(self.derive("identity-registrar"))
129
+
130
+ def seal_identity(self, actor: str, issuer: str, subject: str) -> bytes:
131
+ address = aptos_address_bytes(actor)
132
+ claims = {
133
+ "iss": _text(issuer, "issuer").decode(),
134
+ "sub": _text(subject, "subject").decode(),
135
+ }
136
+ payload = json.dumps(claims, separators=(",", ":"), sort_keys=True).encode()
137
+ return _seal(
138
+ self.derive("identity", address), b"c26t/identity-aad/v1\x00" + address, payload
139
+ )
140
+
141
+ def open_identity(self, actor: str, frame: bytes) -> tuple[str, str]:
142
+ address = aptos_address_bytes(actor)
143
+ payload = _open(
144
+ self.derive("identity", address), b"c26t/identity-aad/v1\x00" + address, frame
145
+ )
146
+ try:
147
+ claims = json.loads(payload)
148
+ if not isinstance(claims, dict) or set(claims) != {"iss", "sub"}:
149
+ raise ValueError("invalid identity envelope")
150
+ issuer = _text(claims["iss"], "issuer").decode()
151
+ subject = _text(claims["sub"], "subject").decode()
152
+ except (UnicodeDecodeError, json.JSONDecodeError, TypeError) as exc:
153
+ raise ValueError("invalid identity envelope") from exc
154
+ if self.user_address(issuer, subject) != aptos_address_text(address):
155
+ raise ValueError("identity does not match account")
156
+ return issuer, subject
157
+
158
+ def email_lookup_hash(self, normalized_email: str) -> bytes:
159
+ email = _text(normalized_email, "email")
160
+ if normalized_email != normalized_email.strip().lower() or b"@" not in email:
161
+ raise ValueError("email must be normalized")
162
+ return hmac.digest(self.derive("email-lookup"), email, "sha256")
163
+
164
+ def record_request_commitment(
165
+ self,
166
+ thread_id: str,
167
+ actor: str,
168
+ request_id: bytes,
169
+ message: str,
170
+ attachments: list[str],
171
+ ) -> bytes:
172
+ """Commit to a retry's cleartext without exposing a public dictionary oracle."""
173
+ thread = aptos_address_bytes(thread_id)
174
+ if not isinstance(request_id, bytes) or len(request_id) != 32:
175
+ raise ValueError("request ID must be 32 bytes")
176
+ if not isinstance(message, str) or not isinstance(attachments, list):
177
+ raise TypeError("invalid record request")
178
+ body = (
179
+ b"c26t/record-request/v1\x00"
180
+ + aptos_address_bytes(actor)
181
+ + request_id
182
+ + _part(message.encode("utf-8"))
183
+ + len(attachments).to_bytes(4, "big")
184
+ + b"".join(_part(uri.encode("utf-8")) for uri in attachments)
185
+ )
186
+ return hmac.digest(self.derive("record-request-commitment", thread), body, "sha256")
187
+
188
+ def seal_intent(self, thread_id: str, intent: str) -> bytes:
189
+ thread = aptos_address_bytes(thread_id)
190
+ return _seal(
191
+ self.derive("intent", thread),
192
+ b"c26t/intent-aad/v1\x00" + thread,
193
+ _text(intent, "intent"),
194
+ )
195
+
196
+ def open_intent(self, thread_id: str, frame: bytes) -> str:
197
+ thread = aptos_address_bytes(thread_id)
198
+ plaintext = _open(self.derive("intent", thread), b"c26t/intent-aad/v1\x00" + thread, frame)
199
+ return plaintext.decode("utf-8")
200
+
201
+ def seal_record(
202
+ self,
203
+ thread_id: str,
204
+ sequence: int,
205
+ writer: str,
206
+ created_at: int,
207
+ message: str,
208
+ attachments: list[str],
209
+ ) -> bytes:
210
+ """Encrypt the exact BCS RecordPayload documented by the Move package."""
211
+ thread = aptos_address_bytes(thread_id)
212
+ if (
213
+ not isinstance(created_at, int)
214
+ or isinstance(created_at, bool)
215
+ or not 0 <= created_at < 2**64
216
+ ):
217
+ raise ValueError("created_at must be a u64")
218
+ if not isinstance(message, str) or not isinstance(attachments, list):
219
+ raise TypeError("invalid record payload")
220
+ serializer = Serializer()
221
+ serializer.fixed_bytes(aptos_address_bytes(writer))
222
+ serializer.u64(created_at)
223
+ serializer.to_bytes(message.encode("utf-8"))
224
+ serializer.sequence([uri.encode("utf-8") for uri in attachments], Serializer.to_bytes)
225
+ return _seal(
226
+ self.derive("record", thread), self._record_aad(thread, sequence), serializer.output()
227
+ )
228
+
229
+ def open_record(self, thread_id: str, sequence: int, frame: bytes) -> dict:
230
+ thread = aptos_address_bytes(thread_id)
231
+ plaintext = _open(self.derive("record", thread), self._record_aad(thread, sequence), frame)
232
+ try:
233
+ decoder = Deserializer(plaintext)
234
+ writer = aptos_address_text(decoder.fixed_bytes(32))
235
+ created_at = decoder.u64()
236
+ message = decoder.to_bytes().decode("utf-8")
237
+ attachments = [
238
+ item.decode("utf-8") for item in decoder.sequence(Deserializer.to_bytes)
239
+ ]
240
+ if decoder.remaining() != 0:
241
+ raise ValueError("trailing record bytes")
242
+ except (ValueError, UnicodeError, OverflowError) as exc:
243
+ raise ValueError("invalid encrypted record payload") from exc
244
+ return {
245
+ "writer": writer,
246
+ "created_at": created_at,
247
+ "message": message,
248
+ "attachment_uris": attachments,
249
+ }
250
+
251
+ def _record_aad(self, thread: bytes, sequence: int) -> bytes:
252
+ if (
253
+ not isinstance(sequence, int)
254
+ or isinstance(sequence, bool)
255
+ or not 0 <= sequence < 2**64
256
+ ):
257
+ raise ValueError("sequence must be a u64")
258
+ return (
259
+ b"c26t/record/v1\x00"
260
+ + bytes([self.chain_id])
261
+ + thread
262
+ + sequence.to_bytes(8, "little")
263
+ )
264
+
265
+ def seal_index_object(
266
+ self, thread_id: str, generation: int, object_id: bytes, plaintext: bytes
267
+ ) -> bytes:
268
+ thread = aptos_address_bytes(thread_id)
269
+ aad = self._index_aad(thread, generation, object_id)
270
+ return _seal(self.derive("index", thread), aad, plaintext, limit=_MAX_INDEX_OBJECT_BYTES)
271
+
272
+ def open_index_object(
273
+ self, thread_id: str, generation: int, object_id: bytes, frame: bytes
274
+ ) -> bytes:
275
+ thread = aptos_address_bytes(thread_id)
276
+ aad = self._index_aad(thread, generation, object_id)
277
+ return _open(self.derive("index", thread), aad, frame)
278
+
279
+ @staticmethod
280
+ def _index_aad(thread: bytes, generation: int, object_id: bytes) -> bytes:
281
+ if (
282
+ not isinstance(generation, int)
283
+ or isinstance(generation, bool)
284
+ or not 0 <= generation < 2**64
285
+ ):
286
+ raise ValueError("generation must be a u64")
287
+ if not isinstance(object_id, bytes) or not object_id or len(object_id) > 256:
288
+ raise ValueError("invalid index object id")
289
+ return (
290
+ b"c26t/index-aad/v1\x00" + thread + generation.to_bytes(8, "little") + _part(object_id)
291
+ )
c26t/mcp_logging.py ADDED
@@ -0,0 +1,134 @@
1
+ """Private, per-process diagnostics for the local stdio MCP.
2
+
3
+ The log deliberately contains no tool arguments, results, exception messages,
4
+ or traceback locals. A tool error ID connects the harness response to its
5
+ exception types and code locations in this file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import os
12
+ import secrets
13
+ import stat
14
+ import sys
15
+ from datetime import UTC, datetime
16
+ from logging.handlers import RotatingFileHandler
17
+ from pathlib import Path
18
+
19
+ _LOG = logging.getLogger("c26t.mcp_diagnostics")
20
+ _LOG.addHandler(logging.NullHandler())
21
+ _LOG.propagate = False
22
+ _HANDLER: RotatingFileHandler | None = None
23
+ _LOG_FILE: Path | None = None
24
+ _KNOWN_TOOLS = frozenset({
25
+ "get_mcp_version", "list_threads", "link_thread", "attach_thread", "detach_thread",
26
+ "create_thread", "get_thread_metadata", "thread_search", "add_thread_record",
27
+ "fetch_thread_artifact", "read_thread_record", "set_thread_intent", "share_thread",
28
+ "unshare_thread",
29
+ "list_vaults", "start_vault_session", "create_vault", "get_vault_metadata",
30
+ "add_record", "read_records", "search", "forget_record", "download_attachment",
31
+ "update_vault_metadata", "list_accessors", "set_accessor",
32
+ })
33
+
34
+
35
+ class _PrivateRotatingFileHandler(RotatingFileHandler):
36
+ def _open(self):
37
+ flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
38
+ fd = os.open(self.baseFilename, flags, 0o600)
39
+ return os.fdopen(fd, self.mode, encoding=self.encoding, errors=self.errors)
40
+
41
+
42
+ def default_mcp_log_dir() -> Path:
43
+ from .mcp_gas_station import PROTOTYPE_DEPLOYMENT_SLUG
44
+
45
+ override = os.environ.get("C26T_MCP_LOG_DIR")
46
+ if override:
47
+ path = Path(override).expanduser()
48
+ if not path.is_absolute():
49
+ raise ValueError("C26T_MCP_LOG_DIR must be an absolute path")
50
+ return path
51
+ if sys.platform == "darwin":
52
+ return Path.home() / "Library" / "Logs" / PROTOTYPE_DEPLOYMENT_SLUG
53
+ state_root = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state")
54
+ if not state_root.is_absolute():
55
+ raise ValueError("XDG_STATE_HOME must be an absolute path")
56
+ return state_root / PROTOTYPE_DEPLOYMENT_SLUG
57
+
58
+
59
+ def configure_mcp_logging(*, log_dir: Path | None = None) -> Path:
60
+ """Create a 0600 log before importing the rest of the MCP application."""
61
+ global _HANDLER, _LOG_FILE
62
+ if _LOG_FILE is not None:
63
+ return _LOG_FILE
64
+ log_dir = log_dir if log_dir is not None else default_mcp_log_dir()
65
+ if log_dir.is_symlink():
66
+ raise ValueError("c26t MCP log directory must not be a symlink")
67
+ log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
68
+ if stat.S_IMODE(log_dir.stat().st_mode) & 0o077:
69
+ raise PermissionError("c26t MCP log directory must be private (0700)")
70
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
71
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
72
+ for _ in range(5):
73
+ path = log_dir / f"mcp-{stamp}-{os.getpid()}-{secrets.token_hex(3)}.log"
74
+ try:
75
+ fd = os.open(path, flags, 0o600)
76
+ except FileExistsError:
77
+ continue
78
+ os.close(fd)
79
+ break
80
+ else:
81
+ raise FileExistsError("could not allocate a unique c26t MCP log")
82
+ handler = _PrivateRotatingFileHandler(
83
+ path, maxBytes=5 * 1024 * 1024, backupCount=2, encoding="utf-8"
84
+ )
85
+ handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
86
+ _LOG.addHandler(handler)
87
+ _LOG.setLevel(logging.INFO)
88
+ _HANDLER, _LOG_FILE = handler, path
89
+ _LOG.info("mcp-log-ready pid=%d", os.getpid())
90
+ return path
91
+
92
+
93
+ def close_mcp_logging() -> None:
94
+ global _HANDLER, _LOG_FILE
95
+ if _HANDLER is not None:
96
+ _LOG.removeHandler(_HANDLER)
97
+ _HANDLER.close()
98
+ _HANDLER, _LOG_FILE = None, None
99
+
100
+
101
+ def log_event(event: str, *, tool: str | None = None, detail: str | None = None) -> None:
102
+ """Write only caller-controlled, non-user-data event fields."""
103
+ tool_name = tool if isinstance(tool, str) and tool in _KNOWN_TOOLS else "-"
104
+ if detail is None:
105
+ _LOG.info("event=%s tool=%s", event, tool_name)
106
+ else:
107
+ _LOG.info("event=%s tool=%s detail=%s", event, tool_name, detail)
108
+
109
+
110
+ def log_failure(stage: str, exc: BaseException, *, tool: str | None = None) -> str:
111
+ """Log exception classes and code positions, never exception text or inputs."""
112
+ diagnostic_id = secrets.token_hex(5)
113
+ tool_name = tool if isinstance(tool, str) and tool in _KNOWN_TOOLS else "-"
114
+ chain: list[str] = []
115
+ current: BaseException | None = exc
116
+ seen: set[int] = set()
117
+ while current is not None and id(current) not in seen and len(chain) < 5:
118
+ seen.add(id(current))
119
+ frames: list[str] = []
120
+ tb = current.__traceback__
121
+ while tb is not None:
122
+ code = tb.tb_frame.f_code
123
+ frames.append(f"{Path(code.co_filename).name}:{tb.tb_lineno}:{code.co_name}")
124
+ tb = tb.tb_next
125
+ chain.append(
126
+ f"{type(current).__module__}.{type(current).__qualname__}"
127
+ f" at {','.join(frames[-8:]) or '-'}"
128
+ )
129
+ current = current.__cause__ or (None if current.__suppress_context__ else current.__context__)
130
+ _LOG.error(
131
+ "failure id=%s stage=%s tool=%s chain=%s",
132
+ diagnostic_id, stage, tool_name, " <- ".join(chain),
133
+ )
134
+ return diagnostic_id