mcpledger 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.
mcpledger/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """mcpledger: audit trail and analytics for MCP servers."""
2
+
3
+ from .instrument import Trail, instrument
4
+ from .redact import MASK, redact, redact_string
5
+
6
+ __all__ = ["MASK", "Trail", "instrument", "redact", "redact_string"]
7
+ __version__ = "0.1.0"
mcpledger/exit.py ADDED
@@ -0,0 +1,37 @@
1
+ """Flushes the shared senders when the process gets SIGTERM, then lets the signal do what it did before.
2
+
3
+ Normal interpreter exit is covered by atexit. SIGTERM's default action kills the process without running
4
+ atexit, so without this hook a server stopped by its supervisor loses whatever is still queued.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import signal
10
+ import threading
11
+ from collections.abc import Callable
12
+ from typing import Any
13
+
14
+ _installed = False
15
+ _previous: Any = None
16
+
17
+
18
+ def install_sigterm_flush(flush_all: Callable[[float], None], seconds: float) -> None:
19
+ """Installs the hook once, from the main thread only (Python allows signal handlers nowhere else)."""
20
+ global _installed, _previous
21
+ if _installed or not hasattr(signal, "SIGTERM") or threading.current_thread() is not threading.main_thread():
22
+ return
23
+ _installed = True
24
+ _previous = signal.getsignal(signal.SIGTERM)
25
+
26
+ def on_sigterm(signum: int, frame: Any) -> None:
27
+ # Flush on another thread: the signal may have interrupted this one while it held a sender lock.
28
+ worker = threading.Thread(target=flush_all, args=(seconds,), name="mcpledger-exit-flush", daemon=True)
29
+ worker.start()
30
+ worker.join(seconds + 0.5)
31
+ if callable(_previous):
32
+ _previous(signum, frame)
33
+ elif _previous != signal.SIG_IGN:
34
+ signal.signal(signum, signal.SIG_DFL)
35
+ signal.raise_signal(signum)
36
+
37
+ signal.signal(signal.SIGTERM, on_sigterm)
@@ -0,0 +1,306 @@
1
+ """Records every tools/call on an MCP server and sends it to the collector.
2
+
3
+ Works with the official `mcp` package, both major versions:
4
+ - mcp 2.x: `MCPServer` and the low-level `Server` (handlers in `_request_handlers`, keyed by method).
5
+ - mcp 1.x: `FastMCP` and the low-level `Server` (handlers in `request_handlers`, keyed by request type).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import inspect
12
+ import json
13
+ import re
14
+ import time
15
+ import uuid
16
+ import weakref
17
+ from contextvars import ContextVar
18
+ from collections.abc import Callable, Iterable
19
+ from datetime import datetime, timezone
20
+ from typing import Any
21
+
22
+ import anyio.to_thread
23
+
24
+ from .redact import _compile, mask_values, redact, redact_string, secret_values
25
+ from .transport import SenderLease, lease_sender
26
+
27
+ _MARK = "_mcpledger_wrapped"
28
+ _STATELESS_SINCE = "2026-07-28" # MCP protocol version that dropped the initialize handshake
29
+ MAX_ERROR = 500
30
+ MAX_ARGS_BYTES = 32_000 # the collector rejects larger args
31
+
32
+
33
+ class Trail:
34
+ """Handle returned by `instrument()`. Servers that report to the same collector with the same key share one
35
+ sender, so flush() sends their events too and `dropped` counts for all of them."""
36
+
37
+ def __init__(self, lease: SenderLease) -> None:
38
+ self._lease = lease
39
+ self._sender = lease.sender
40
+
41
+ @property
42
+ def dropped(self) -> int:
43
+ return self._sender.dropped
44
+
45
+ async def flush(self) -> None:
46
+ await anyio.to_thread.run_sync(self._sender.flush, abandon_on_cancel=True)
47
+
48
+ async def close(self, timeout: float = 5.0) -> None:
49
+ """Flushes. The last Trail on a shared sender also stops it: it sends for at most `timeout` seconds,
50
+ and whatever is still queued then counts as dropped."""
51
+ await anyio.to_thread.run_sync(self._lease.release, timeout, abandon_on_cancel=True)
52
+
53
+ def flush_sync(self) -> None:
54
+ self._sender.flush()
55
+
56
+ def close_sync(self, timeout: float = 5.0) -> None:
57
+ self._lease.release(timeout)
58
+
59
+
60
+ class _WrappingDict(dict):
61
+ """A handler dict that wraps the tools/call handler whenever one is set, so tools added later are covered."""
62
+
63
+ def __init__(self, data: dict, key: Any, wrap: Callable[[Any], Any]) -> None:
64
+ super().__init__()
65
+ self._key = key
66
+ self._wrap = wrap
67
+ self.update(data)
68
+
69
+ def __setitem__(self, k: Any, v: Any) -> None:
70
+ super().__setitem__(k, self._wrap(v) if k == self._key else v)
71
+
72
+ def update(self, *args: Any, **kwargs: Any) -> None:
73
+ for k, v in dict(*args, **kwargs).items():
74
+ self[k] = v
75
+
76
+ def setdefault(self, k: Any, default: Any = None) -> Any:
77
+ if k not in self:
78
+ self[k] = default
79
+ return self[k]
80
+
81
+
82
+ def _lowlevel(server: Any) -> tuple[Any, int]:
83
+ # MCPServer (2.x) keeps the low-level server in _lowlevel_server, FastMCP (1.x) in _mcp_server
84
+ for attr in ("_lowlevel_server", "_mcp_server"):
85
+ inner = getattr(server, attr, None)
86
+ if inner is not None:
87
+ server = inner
88
+ break
89
+ if isinstance(getattr(server, "_request_handlers", None), dict) and hasattr(server, "get_request_handler"):
90
+ return server, 2
91
+ if isinstance(getattr(server, "request_handlers", None), dict):
92
+ return server, 1
93
+ raise TypeError("mcpledger: pass an MCPServer, FastMCP or Server from the `mcp` package")
94
+
95
+
96
+ def _now_iso() -> str:
97
+ return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
98
+
99
+
100
+ def _get(obj: Any, *names: str) -> Any:
101
+ for n in names:
102
+ v = obj.get(n) if isinstance(obj, dict) else getattr(obj, n, None)
103
+ if v is not None:
104
+ return v
105
+ return None
106
+
107
+
108
+ def _first_text(result: Any) -> str | None:
109
+ for item in _get(result, "content") or []:
110
+ if _get(item, "type") == "text" and _get(item, "text"):
111
+ return str(_get(item, "text"))
112
+ return None
113
+
114
+
115
+ def _outcome(result: Any) -> tuple[str, str | None]:
116
+ result = getattr(result, "root", result) # 1.x wraps results in ServerResult
117
+ if _get(result, "is_error", "isError"):
118
+ return "error", _first_text(result)
119
+ if _get(result, "code") is not None and _get(result, "message") is not None and _get(result, "content") is None:
120
+ return "error", str(_get(result, "message")) # ErrorData returned by a low-level handler
121
+ return "ok", None
122
+
123
+
124
+ def _fit(args: Any) -> Any:
125
+ size = len(json.dumps(args, default=str))
126
+ return args if size <= MAX_ARGS_BYTES else {"[truncated]": f"{size} bytes of arguments"}
127
+
128
+
129
+ def _header(ctx: Any, name: str) -> str | None:
130
+ headers = getattr(getattr(ctx, "request", None), "headers", None)
131
+ try:
132
+ return headers.get(name) if headers is not None else None
133
+ except Exception:
134
+ return None
135
+
136
+
137
+ def instrument(
138
+ server: Any,
139
+ api_key: str,
140
+ endpoint: str = "http://localhost:8787",
141
+ identify: Callable[[Any], Any] | None = None,
142
+ redact_keys: Iterable[str | re.Pattern[str]] | None = None,
143
+ disable_redaction: bool = False,
144
+ flush_interval: float = 2.0,
145
+ max_batch: int = 50,
146
+ max_queue: int = 10_000,
147
+ on_error: Callable[[BaseException], None] | None = None,
148
+ ) -> Trail:
149
+ """Records every tools/call on this MCP server and sends it to the collector.
150
+
151
+ `identify(ctx)` gets the request context and may return the end user behind the session (sync or async).
152
+ `redact_keys` are extra argument names to mask, on top of passwords, tokens, keys, PINs and card codes.
153
+ `disable_redaction` is for local testing only.
154
+ """
155
+ low, major = _lowlevel(server)
156
+ lease = lease_sender(endpoint, api_key, flush_interval=flush_interval, max_batch=max_batch, max_queue=max_queue,
157
+ on_error=on_error)
158
+ sender = lease.sender
159
+ extra_keys = _compile(redact_keys)
160
+
161
+ def clean(error: str | None, secrets: list[str]) -> str | None:
162
+ if error and not disable_redaction:
163
+ error = mask_values(redact_string(error), secrets)
164
+ return error[:MAX_ERROR] if error else error # cut after masking, so a cut value cannot slip past
165
+
166
+ # stdio and in-memory connections carry no session id, so each connection gets its own
167
+ conn_ids: weakref.WeakKeyDictionary[Any, str] = weakref.WeakKeyDictionary()
168
+ fallback_ids: dict[int, str] = {}
169
+
170
+ process_id = f"conn-{uuid.uuid4()}"
171
+
172
+ def session_of(ctx: Any) -> str | None:
173
+ session = getattr(ctx, "session", None)
174
+ conn = getattr(session, "_connection", None) or session
175
+ sid = getattr(conn, "session_id", None) or _header(ctx, "mcp-session-id")
176
+ if sid:
177
+ return str(sid)
178
+ if str(getattr(ctx, "protocol_version", "") or "") >= _STATELESS_SINCE:
179
+ # Stateless protocol: every request gets a fresh Connection, so it cannot group calls. A stdio or
180
+ # in-process server serves one client, so the process is the session. Over HTTP there is none.
181
+ return None if getattr(ctx, "request", None) is not None else process_id
182
+ try:
183
+ cid = conn_ids.get(conn) if conn is not None else None
184
+ if cid is None:
185
+ cid = f"conn-{uuid.uuid4()}"
186
+ if conn is not None:
187
+ conn_ids[conn] = cid
188
+ return cid
189
+ except TypeError: # not weak-referenceable
190
+ return fallback_ids.setdefault(id(conn), f"conn-{uuid.uuid4()}")
191
+
192
+ def client_of(ctx: Any) -> tuple[str | None, str | None]:
193
+ params = getattr(getattr(ctx, "session", None), "client_params", None)
194
+ info = _get(params, "client_info", "clientInfo")
195
+ return _get(info, "name"), _get(info, "version")
196
+
197
+ async def user_of(ctx: Any) -> str | None:
198
+ if identify is None:
199
+ return None
200
+ try:
201
+ user = identify(ctx)
202
+ if inspect.isawaitable(user):
203
+ user = await user
204
+ return None if user is None else str(user)
205
+ except Exception:
206
+ return None
207
+
208
+ async def record(ctx: Any, params: Any, call: Callable[[], Any]) -> Any:
209
+ started = time.perf_counter()
210
+ try:
211
+ base = await describe(ctx, params)
212
+ except Exception:
213
+ return await call() # recording must never break the call
214
+
215
+ secrets = [] if disable_redaction else secret_values(_get(params, "arguments"), extra_keys)
216
+
217
+ def push(status: str, error: str | None) -> None:
218
+ sender.push({**base, "status": status, "error": clean(error, secrets),
219
+ "duration_ms": round((time.perf_counter() - started) * 1000)})
220
+
221
+ hidden: list[str] = []
222
+ token = hidden_cause.set(hidden)
223
+ try:
224
+ result = await call()
225
+ except BaseException as err: # recorded, then re-raised unchanged (cancellation too)
226
+ push("error", str(err) or type(err).__name__)
227
+ raise
228
+ finally:
229
+ hidden_cause.reset(token)
230
+ try:
231
+ status, error = _outcome(result)
232
+ push(status, (hidden[-1] if hidden and status == "error" else error))
233
+ except Exception:
234
+ pass
235
+ return result
236
+
237
+ async def describe(ctx: Any, params: Any) -> dict[str, Any]:
238
+ args = _get(params, "arguments")
239
+ client_name, client_version = client_of(ctx)
240
+ return {
241
+ "id": str(uuid.uuid4()),
242
+ "ts": _now_iso(),
243
+ "session_id": session_of(ctx),
244
+ "user_id": await user_of(ctx),
245
+ "client_name": client_name,
246
+ "client_version": client_version,
247
+ "server_name": getattr(low, "name", None),
248
+ "server_version": getattr(low, "version", None),
249
+ "tool": str(_get(params, "name") or "unknown"),
250
+ "args": _fit(args if disable_redaction else redact(args, extra_keys)),
251
+ }
252
+
253
+ def mark(fn: Any) -> Any:
254
+ setattr(fn, _MARK, True)
255
+ return fn
256
+
257
+ # MCPServer (2.x) shows the client only "Error executing tool <name>" for an unexpected exception.
258
+ # The audit log keeps the real cause, redacted like every other error.
259
+ hidden_cause: ContextVar[list[str] | None] = ContextVar("mcpledger_hidden_cause", default=None)
260
+ original_call_tool = getattr(server, "call_tool", None) if server is not low and major == 2 else None
261
+ if original_call_tool is not None and not getattr(original_call_tool, _MARK, False):
262
+ async def call_tool(*args: Any, **kwargs: Any) -> Any:
263
+ try:
264
+ return await original_call_tool(*args, **kwargs)
265
+ except Exception as err:
266
+ holder = hidden_cause.get()
267
+ if holder is not None and err.__cause__ is not None:
268
+ holder.append(f"{err}: {err.__cause__}")
269
+ raise
270
+
271
+ server.call_tool = mark(call_tool)
272
+
273
+ if major == 2:
274
+ def wrap(entry: Any) -> Any:
275
+ handler = getattr(entry, "handler", None)
276
+ if handler is None or getattr(handler, _MARK, False):
277
+ return entry
278
+
279
+ async def wrapped(ctx: Any, params: Any) -> Any:
280
+ return await record(ctx, params, lambda: handler(ctx, params))
281
+
282
+ return dataclasses.replace(entry, handler=mark(wrapped))
283
+
284
+ low._request_handlers = _WrappingDict(low._request_handlers, "tools/call", wrap)
285
+ else:
286
+ from mcp import types
287
+
288
+ def wrap(handler: Any) -> Any:
289
+ if getattr(handler, _MARK, False):
290
+ return handler
291
+
292
+ async def wrapped(req: Any) -> Any:
293
+ try:
294
+ ctx = low.request_context
295
+ except Exception:
296
+ ctx = None
297
+ return await record(ctx, getattr(req, "params", None), lambda: handler(req))
298
+
299
+ return mark(wrapped)
300
+
301
+ low.request_handlers = _WrappingDict(low.request_handlers, types.CallToolRequest, wrap)
302
+ experimental = getattr(low, "_experimental_handlers", None)
303
+ if experimental is not None: # created before instrument(): it registers into the dict it was given
304
+ experimental._request_handlers = low.request_handlers
305
+
306
+ return Trail(lease)
mcpledger/py.typed ADDED
File without changes
mcpledger/redact.py ADDED
@@ -0,0 +1,115 @@
1
+ """Redaction runs inside the customer's server, before any event leaves it.
2
+
3
+ Same rules as the TypeScript SDK (packages/sdk/src/redact.ts): values under secret-looking keys are masked,
4
+ and emails, Luhn-valid card numbers and IBANs inside strings are replaced.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Iterable, Mapping
11
+ from typing import Any
12
+
13
+ SECRET_KEY = re.compile(
14
+ r"pass(word)?|secret|token|api[_-]?key|authorization|auth|cookie|session[_-]?id|private[_-]?key|otp|pin|cvv|cvc",
15
+ re.IGNORECASE,
16
+ )
17
+ EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
18
+ IBAN = re.compile(r"\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]){11,30}\b", re.ASCII)
19
+ CARD_CANDIDATE = re.compile(r"\b(?:\d[ -]?){13,19}\b", re.ASCII)
20
+
21
+ MASK = "[redacted]"
22
+ _MAX_DEPTH = 12
23
+
24
+
25
+ def _luhn_ok(digits: str) -> bool:
26
+ total = 0
27
+ double = False
28
+ for ch in reversed(digits):
29
+ d = ord(ch) - 48
30
+ if double:
31
+ d *= 2
32
+ if d > 9:
33
+ d -= 9
34
+ total += d
35
+ double = not double
36
+ return total % 10 == 0
37
+
38
+
39
+ def _card(m: re.Match[str]) -> str:
40
+ text = m.group(0)
41
+ digits = re.sub(r"[ -]", "", text)
42
+ if not (13 <= len(digits) <= 19 and _luhn_ok(digits)):
43
+ return text
44
+ return "[card]" + text[len(text.rstrip(" -")):] # the pattern can swallow the separator after the number
45
+
46
+
47
+ def redact_string(s: str) -> str:
48
+ """Replaces emails, card numbers (Luhn-checked) and IBANs inside a string."""
49
+ out = EMAIL.sub("[email]", s)
50
+ out = CARD_CANDIDATE.sub(_card, out)
51
+ return IBAN.sub("[iban]", out)
52
+
53
+
54
+ def _compile(keys: Iterable[str | re.Pattern[str]] | None) -> list[re.Pattern[str]]:
55
+ return [k if isinstance(k, re.Pattern) else re.compile(k, re.IGNORECASE) for k in (keys or [])]
56
+
57
+
58
+ def redact(value: Any, extra_keys: Iterable[str | re.Pattern[str]] | None = None, _depth: int = 0) -> Any:
59
+ """Masks values under secret-looking keys, and emails, card numbers and IBANs inside strings.
60
+
61
+ `extra_keys` are more argument names to mask: regex patterns or strings (matched case-insensitively).
62
+ """
63
+ patterns = _compile(extra_keys)
64
+ if _depth > _MAX_DEPTH:
65
+ return MASK
66
+ if isinstance(value, str):
67
+ return redact_string(value)
68
+ if value is None or isinstance(value, (bool, int, float)):
69
+ return value
70
+ if isinstance(value, Mapping):
71
+ out: dict[str, Any] = {}
72
+ for k, v in value.items():
73
+ key = str(k)
74
+ secret = SECRET_KEY.search(key) is not None or any(p.search(key) for p in patterns)
75
+ out[key] = MASK if secret else redact(v, patterns, _depth + 1)
76
+ return out
77
+ if isinstance(value, (list, tuple, set, frozenset)):
78
+ return [redact(v, patterns, _depth + 1) for v in value]
79
+ # anything else (a model, a date) is sent as its text, redacted
80
+ return redact_string(str(value))
81
+
82
+
83
+ def secret_values(value: Any, extra_keys: Iterable[str | re.Pattern[str]] | None = None, _depth: int = 0) -> list[str]:
84
+ """The raw values `redact` masks by key, so they can be masked inside error text too (a validation error
85
+ quotes the input it rejected)."""
86
+ patterns = _compile(extra_keys)
87
+ found: list[str] = []
88
+ if _depth > _MAX_DEPTH:
89
+ return found
90
+ if isinstance(value, Mapping):
91
+ for k, v in value.items():
92
+ key = str(k)
93
+ if SECRET_KEY.search(key) or any(p.search(key) for p in patterns):
94
+ found.extend(_leaves(v))
95
+ else:
96
+ found.extend(secret_values(v, patterns, _depth + 1))
97
+ elif isinstance(value, (list, tuple, set, frozenset)):
98
+ for v in value:
99
+ found.extend(secret_values(v, patterns, _depth + 1))
100
+ return found
101
+
102
+
103
+ def _leaves(value: Any) -> list[str]:
104
+ if isinstance(value, Mapping):
105
+ return [s for v in value.values() for s in _leaves(v)]
106
+ if isinstance(value, (list, tuple, set, frozenset)):
107
+ return [s for v in value for s in _leaves(v)]
108
+ return [] if value is None or isinstance(value, bool) else [str(value)]
109
+
110
+
111
+ def mask_values(text: str, values: Iterable[str]) -> str:
112
+ # longest first, so a value that contains another is masked whole; very short values would mask noise
113
+ for v in sorted({v for v in values if len(v) >= 3}, key=len, reverse=True):
114
+ text = text.replace(v, MASK)
115
+ return text
mcpledger/transport.py ADDED
@@ -0,0 +1,256 @@
1
+ """Sends events in batches from a background thread.
2
+
3
+ Never raises into the MCP server: a down collector must not break tools.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import atexit
9
+ import json
10
+ import math
11
+ import os
12
+ import threading
13
+ import time
14
+ import urllib.error
15
+ import urllib.request
16
+ import weakref
17
+ from collections import deque
18
+ from collections.abc import Callable
19
+ from typing import Any
20
+
21
+ from .exit import install_sigterm_flush
22
+
23
+ HTTP_TIMEOUT = 10.0
24
+ EXIT_FLUSH_SECONDS = 2.0 # exit is never held longer than this
25
+
26
+ # post(url, body, headers, timeout) -> (HTTP status, response body). Raises on network errors.
27
+ PostFn = Callable[[str, bytes, dict[str, str], float], tuple[int, bytes]]
28
+
29
+
30
+ def urllib_post(url: str, body: bytes, headers: dict[str, str], timeout: float) -> tuple[int, bytes]:
31
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
32
+ try:
33
+ with urllib.request.urlopen(req, timeout=timeout) as res:
34
+ return int(res.status), res.read()
35
+ except urllib.error.HTTPError as err:
36
+ return int(err.code), b""
37
+
38
+
39
+ def _finite(value: Any) -> Any:
40
+ if isinstance(value, float) and not math.isfinite(value):
41
+ return str(value)
42
+ if isinstance(value, dict):
43
+ return {k: _finite(v) for k, v in value.items()}
44
+ if isinstance(value, (list, tuple)):
45
+ return [_finite(v) for v in value]
46
+ return value
47
+
48
+
49
+ def encode(batch: list[dict[str, Any]]) -> bytes:
50
+ """JSON the collector can parse: NaN and Infinity are not JSON, so they are sent as text."""
51
+ try:
52
+ return json.dumps({"events": batch}, default=str, allow_nan=False).encode()
53
+ except ValueError:
54
+ return json.dumps({"events": _finite(batch)}, default=str, allow_nan=False).encode()
55
+
56
+
57
+ class Sender:
58
+ def __init__(
59
+ self,
60
+ endpoint: str,
61
+ api_key: str,
62
+ flush_interval: float = 2.0,
63
+ max_batch: int = 50,
64
+ max_queue: int = 10_000,
65
+ post: PostFn | None = None,
66
+ on_error: Callable[[BaseException], None] | None = None,
67
+ backoff: float = 0.25,
68
+ ) -> None:
69
+ self.url = endpoint.rstrip("/") + "/v1/events"
70
+ self.api_key = api_key
71
+ self.max_batch = max(1, max_batch)
72
+ self.max_queue = max_queue
73
+ self.post = post or urllib_post
74
+ self.on_error = on_error
75
+ self.backoff = backoff
76
+ self.dropped = 0
77
+ self._interval = flush_interval
78
+ self._queue: deque[dict[str, Any]] = deque()
79
+ self._deadline: float | None = None # set by close(): nothing is sent after it
80
+ self._start()
81
+ if hasattr(os, "register_at_fork"):
82
+ ref = weakref.ref(self)
83
+ os.register_at_fork(after_in_child=lambda: (s := ref()) and s._start())
84
+
85
+ def _start(self) -> None:
86
+ self._lock = threading.Lock()
87
+ self._send_lock = threading.Lock() # one batch in flight at a time
88
+ self._wake = threading.Event()
89
+ self._closed = threading.Event()
90
+ self._thread = threading.Thread(target=self._run, name="mcpledger-sender", daemon=True)
91
+ self._thread.start()
92
+
93
+ def push(self, event: dict[str, Any]) -> None:
94
+ with self._lock:
95
+ if len(self._queue) >= self.max_queue:
96
+ self._queue.popleft()
97
+ self.dropped += 1
98
+ self._queue.append(event)
99
+ full = len(self._queue) >= self.max_batch
100
+ if full:
101
+ self._wake.set()
102
+
103
+ def _run(self) -> None:
104
+ while not self._closed.is_set():
105
+ # flush_interval <= 0 means: only when a batch is full or flush() is called
106
+ self._wake.wait(self._interval if self._interval > 0 else None)
107
+ self._wake.clear()
108
+ if self._closed.is_set():
109
+ return
110
+ self.flush()
111
+
112
+ def _left(self) -> float | None:
113
+ return None if self._deadline is None else self._deadline - time.monotonic()
114
+
115
+ def flush(self, wait: float | None = None) -> None:
116
+ """Sends everything queued so far. Blocks until done or past the close deadline; never raises.
117
+
118
+ `wait` bounds how long to wait for a send already in flight on the background thread.
119
+ """
120
+ if not self._send_lock.acquire(timeout=-1 if wait is None else max(0.0, wait)):
121
+ return # the background thread holds it and stops at the deadline on its own
122
+ try:
123
+ while True:
124
+ with self._lock:
125
+ if not self._queue:
126
+ return
127
+ left = self._left()
128
+ if left is not None and left <= 0:
129
+ self.dropped += len(self._queue)
130
+ self._queue.clear()
131
+ return
132
+ batch = [self._queue.popleft() for _ in range(min(self.max_batch, len(self._queue)))]
133
+ self._send(batch)
134
+ finally:
135
+ self._send_lock.release()
136
+
137
+ def _report(self, err: BaseException) -> None:
138
+ if self.on_error:
139
+ try:
140
+ self.on_error(err)
141
+ except Exception:
142
+ pass
143
+
144
+ def _rejected(self, body: bytes) -> list[Any]:
145
+ try:
146
+ rejected = json.loads(body or b"{}").get("rejected") or []
147
+ return rejected if isinstance(rejected, list) else []
148
+ except Exception:
149
+ return []
150
+
151
+ def _send(self, batch: list[dict[str, Any]]) -> None:
152
+ body = encode(batch)
153
+ headers = {"content-type": "application/json", "authorization": f"Bearer {self.api_key}"}
154
+ for attempt in range(3):
155
+ left = self._left()
156
+ if left is not None and left <= 0:
157
+ break
158
+ try:
159
+ status, reply = self.post(self.url, body, headers, HTTP_TIMEOUT if left is None else min(HTTP_TIMEOUT, left))
160
+ if 200 <= status < 300:
161
+ rejected = self._rejected(reply)
162
+ if rejected:
163
+ self._drop(len(rejected))
164
+ self._report(RuntimeError(f"mcpledger: collector rejected {len(rejected)} events: {rejected[:3]}"))
165
+ return
166
+ if 400 <= status < 500 and status != 429:
167
+ # a bad key or bad data will not get better by retrying
168
+ self._report(RuntimeError(f"mcpledger: collector refused the batch (HTTP {status})"))
169
+ break
170
+ if attempt == 2:
171
+ self._report(RuntimeError(f"mcpledger: collector failed (HTTP {status})"))
172
+ except Exception as err:
173
+ if attempt == 2:
174
+ self._report(err)
175
+ if attempt < 2:
176
+ pause = self.backoff * 2**attempt
177
+ left = self._left()
178
+ time.sleep(pause if left is None else max(0.0, min(pause, left)))
179
+ # give up on this batch but keep the server running
180
+ self._drop(len(batch))
181
+
182
+ def _drop(self, n: int) -> None:
183
+ with self._lock:
184
+ self.dropped += n
185
+
186
+ def flush_by(self, seconds: float) -> None:
187
+ """Sends what is queued for at most `seconds`; whatever is left then counts as dropped. Keeps running."""
188
+ self._deadline = time.monotonic() + seconds
189
+ try:
190
+ self.flush(wait=seconds)
191
+ finally:
192
+ if not self._closed.is_set():
193
+ self._deadline = None
194
+
195
+ def close(self, timeout: float = 5.0) -> None:
196
+ """Sends what is left, for at most `timeout` seconds, then stops. Anything unsent counts as dropped."""
197
+ if self._closed.is_set():
198
+ return
199
+ self._deadline = time.monotonic() + timeout
200
+ self._closed.set()
201
+ self._wake.set()
202
+ self.flush(wait=timeout)
203
+ self._thread.join(max(0.0, self._left() or 0.0))
204
+
205
+
206
+ # One sender per destination in a process, so a server built per request (stateless HTTP) still sends
207
+ # through one queue and one background thread.
208
+ _senders: dict[tuple[str, str], list[Any]] = {} # (api_key, endpoint) -> [sender, users]
209
+ _senders_lock = threading.Lock()
210
+
211
+
212
+ class SenderLease:
213
+ def __init__(self, key: tuple[str, str], sender: Sender) -> None:
214
+ self.key = key
215
+ self.sender = sender
216
+ self._released = False
217
+
218
+ def release(self, timeout: float = 5.0) -> None:
219
+ """Flushes. The last lease on a sender closes it (at most `timeout` seconds) and removes it."""
220
+ last = False
221
+ with _senders_lock:
222
+ if not self._released:
223
+ self._released = True
224
+ entry = _senders.get(self.key)
225
+ if entry is not None and entry[0] is self.sender:
226
+ entry[1] -= 1
227
+ last = entry[1] == 0
228
+ if last:
229
+ del _senders[self.key]
230
+ if last:
231
+ self.sender.close(timeout)
232
+ else:
233
+ self.sender.flush(wait=timeout)
234
+
235
+
236
+ def _flush_all(seconds: float) -> None:
237
+ end = time.monotonic() + seconds # one limit for all senders together
238
+ with _senders_lock:
239
+ senders = [entry[0] for entry in _senders.values()]
240
+ for sender in senders:
241
+ sender.flush_by(max(0.0, end - time.monotonic()))
242
+
243
+
244
+ def lease_sender(endpoint: str, api_key: str, **options: Any) -> SenderLease:
245
+ """Shares a sender with every other caller for the same key and endpoint. Sending options come from the
246
+ first caller."""
247
+ key = (api_key, endpoint.rstrip("/"))
248
+ with _senders_lock:
249
+ entry = _senders.get(key)
250
+ if entry is None:
251
+ sender = Sender(endpoint, api_key, **options)
252
+ atexit.register(sender.close, EXIT_FLUSH_SECONDS)
253
+ install_sigterm_flush(_flush_all, EXIT_FLUSH_SECONDS)
254
+ entry = _senders[key] = [sender, 0]
255
+ entry[1] += 1
256
+ return SenderLease(key, entry[0])
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcpledger
3
+ Version: 0.1.0
4
+ Summary: Audit trail and analytics for MCP servers: records every tool call, redacts personal data before it leaves your server.
5
+ Project-URL: Source, https://github.com/thisismairaj/mcpledger
6
+ Author: Muhammad Mairaj
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: ai-agents,audit,audit-trail,mcp,model-context-protocol,observability
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: System :: Logging
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: mcp>=1.9
21
+ Provides-Extra: dev
22
+ Requires-Dist: anyio>=4; extra == 'dev'
23
+ Requires-Dist: pytest>=8; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # mcpledger (Python)
27
+
28
+ Records every tool call your Python MCP server handles and sends it to an mcpledger collector: who called,
29
+ which tool, the arguments, the result status, how long it took. Personal data is masked inside your server
30
+ before anything is sent.
31
+
32
+ Works with the official `mcp` package, version 1 (`FastMCP`, low-level `Server`) and version 2 (`MCPServer`,
33
+ low-level `Server`).
34
+
35
+ ## Install
36
+
37
+ ```sh
38
+ pip install mcpledger # or: uv add mcpledger
39
+ ```
40
+
41
+ ## Use it
42
+
43
+ ```python
44
+ from mcp.server.mcpserver import MCPServer # mcp 1.x: from mcp.server.fastmcp import FastMCP
45
+ import os
46
+
47
+ from mcpledger import instrument
48
+
49
+ server = MCPServer("payments-ops", version="1.0.0")
50
+ trail = instrument(
51
+ server,
52
+ api_key=os.environ["MCPLEDGER_KEY"],
53
+ endpoint="https://your-collector.example.com",
54
+ identify=lambda ctx: current_user_id(), # optional: the end user behind the call, from your auth
55
+ )
56
+ # register tools as usual, before or after instrument()
57
+ ```
58
+
59
+ Options: `identify(ctx)` gets the request context and may be async. `redact_keys` adds argument names to mask
60
+ (strings or regex patterns). `flush_interval` (seconds, default 2) and `max_batch` (default 50) control sending.
61
+ `on_error` receives send failures. `disable_redaction=True` is for local testing only.
62
+
63
+ `trail.flush()` and `trail.close(timeout=5)` are async; `flush_sync()` and `close_sync()` exist for sync code. `close` sends
64
+ what is queued for at most `timeout` seconds and counts the rest as dropped. Queued events
65
+ are also sent when the process exits. `trail.dropped` counts events that could not be delivered.
66
+
67
+ ## One sender per collector
68
+
69
+ Every `instrument()` call with the same `api_key` and `endpoint` in a process shares one sender: one queue and
70
+ one background thread. A server built per request (stateless HTTP) therefore still sends in batches.
71
+ `flush()` sends the shared queue, and `dropped` counts for every server on it. `close()` flushes, and only the
72
+ last Trail on a sender stops it. The sending options (`flush_interval`, `max_batch`, `max_queue`, `on_error`)
73
+ come from the first `instrument()` call for that destination; later calls do not change them. At normal
74
+ interpreter exit the queue is flushed for at most 2 seconds. On SIGTERM it is flushed the same way, then the signal does what it
75
+ did before: your own handler runs, the default action ends the process, or an ignored signal stays ignored. The
76
+ hook is installed from the main thread only. A framework that installs its own SIGTERM handler later (uvicorn,
77
+ for one) replaces it, and its graceful shutdown then ends in a normal exit, which atexit covers. On Windows a
78
+ SIGTERM from another process ends the process without running any handler, so call `close()` yourself where
79
+ you can.
80
+
81
+ ## What gets masked
82
+
83
+ Values under secret-looking keys (password, token, api key, authorization, cookie, session id, private key,
84
+ OTP, PIN, CVV) become `[redacted]`. Inside any string, emails become `[email]`, card numbers that pass the Luhn
85
+ check become `[card]` and IBANs become `[iban]`. Error text is masked the same way.
86
+
87
+ ## Sessions
88
+
89
+ Each event carries the transport session id when there is one (streamable HTTP). Without one, each connection
90
+ gets its own `conn-...` id. On the stateless MCP protocol (2026-07-28, mcp 2.x) every request is its own
91
+ connection, so a stdio or in-process server uses one id for the whole process, and an HTTP server sends no
92
+ session id.
93
+
94
+ ## Errors
95
+
96
+ The SDK never raises into your server. Sending runs on a background thread; when the collector is down, a batch
97
+ is tried three times with backoff and then dropped. A 4xx answer other than 429 is not retried. Events the collector
98
+ rejects (listed in its answer) count as dropped and go to `on_error`. Arguments over 32 KB are replaced by a size note.
99
+ Values masked by key are also masked where they reappear in error text, such as a validation error quoting the input.
100
+
101
+ On mcp 2.x, `MCPServer` tells the client only "Error executing tool <name>" when a tool raises. The event keeps
102
+ the real cause too, masked like all error text.
103
+
104
+ ## Develop
105
+
106
+ ```sh
107
+ uv venv --python 3.12 .venv
108
+ uv pip install --python .venv/Scripts/python.exe -e ".[dev]"
109
+ .venv/Scripts/python.exe -m pytest
110
+ ```
111
+
112
+ Against a running collector: `python scripts/e2e.py http://localhost:8788 <api key>`.
@@ -0,0 +1,10 @@
1
+ mcpledger/__init__.py,sha256=74uKnLgXpDQn_kijXOJ9CzWnD3QF-GLAIseHCbOnFy8,243
2
+ mcpledger/exit.py,sha256=6Pge9XAY-8CxOu8_iZwY2GbJK9uy57RoUkjmkBn6YB4,1485
3
+ mcpledger/instrument.py,sha256=9MdC_t38iPvErrL2_-05eveFFbitUNtDD5CeTFjHg2Q,12119
4
+ mcpledger/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ mcpledger/redact.py,sha256=fxUj8RHzWfy-0qrCXLR7-AXT-VdCurs05CmdxTT8gXI,4348
6
+ mcpledger/transport.py,sha256=gSjSyt06pxKKJ1v4-oDSrTTGmMT46m7_lLFTHptraw4,9811
7
+ mcpledger-0.1.0.dist-info/METADATA,sha256=o-x5qrqKg9uJJ6kvgnR3F4un4EXVHBhKwo2IV9WsAyo,5273
8
+ mcpledger-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ mcpledger-0.1.0.dist-info/licenses/LICENSE,sha256=yJ3hbAfaTykakvRRqP-P87yEZnHnisgJ9chMk6c7urU,1072
10
+ mcpledger-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Muhammad Mairaj
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.