Metadata-Version: 2.5
Name: mcpledger
Version: 0.1.0
Summary: Audit trail and analytics for MCP servers: records every tool call, redacts personal data before it leaves your server.
Project-URL: Source, https://github.com/thisismairaj/mcpledger
Author: Muhammad Mairaj
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,audit,audit-trail,mcp,model-context-protocol,observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Logging
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: mcp>=1.9
Provides-Extra: dev
Requires-Dist: anyio>=4; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# mcpledger (Python)

Records every tool call your Python MCP server handles and sends it to an mcpledger collector: who called,
which tool, the arguments, the result status, how long it took. Personal data is masked inside your server
before anything is sent.

Works with the official `mcp` package, version 1 (`FastMCP`, low-level `Server`) and version 2 (`MCPServer`,
low-level `Server`).

## Install

```sh
pip install mcpledger   # or: uv add mcpledger
```

## Use it

```python
from mcp.server.mcpserver import MCPServer  # mcp 1.x: from mcp.server.fastmcp import FastMCP
import os

from mcpledger import instrument

server = MCPServer("payments-ops", version="1.0.0")
trail = instrument(
    server,
    api_key=os.environ["MCPLEDGER_KEY"],
    endpoint="https://your-collector.example.com",
    identify=lambda ctx: current_user_id(),  # optional: the end user behind the call, from your auth
)
# register tools as usual, before or after instrument()
```

Options: `identify(ctx)` gets the request context and may be async. `redact_keys` adds argument names to mask
(strings or regex patterns). `flush_interval` (seconds, default 2) and `max_batch` (default 50) control sending.
`on_error` receives send failures. `disable_redaction=True` is for local testing only.

`trail.flush()` and `trail.close(timeout=5)` are async; `flush_sync()` and `close_sync()` exist for sync code. `close` sends
what is queued for at most `timeout` seconds and counts the rest as dropped. Queued events
are also sent when the process exits. `trail.dropped` counts events that could not be delivered.

## One sender per collector

Every `instrument()` call with the same `api_key` and `endpoint` in a process shares one sender: one queue and
one background thread. A server built per request (stateless HTTP) therefore still sends in batches.
`flush()` sends the shared queue, and `dropped` counts for every server on it. `close()` flushes, and only the
last Trail on a sender stops it. The sending options (`flush_interval`, `max_batch`, `max_queue`, `on_error`)
come from the first `instrument()` call for that destination; later calls do not change them. At normal
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
did before: your own handler runs, the default action ends the process, or an ignored signal stays ignored. The
hook is installed from the main thread only. A framework that installs its own SIGTERM handler later (uvicorn,
for one) replaces it, and its graceful shutdown then ends in a normal exit, which atexit covers. On Windows a
SIGTERM from another process ends the process without running any handler, so call `close()` yourself where
you can.

## What gets masked

Values under secret-looking keys (password, token, api key, authorization, cookie, session id, private key,
OTP, PIN, CVV) become `[redacted]`. Inside any string, emails become `[email]`, card numbers that pass the Luhn
check become `[card]` and IBANs become `[iban]`. Error text is masked the same way.

## Sessions

Each event carries the transport session id when there is one (streamable HTTP). Without one, each connection
gets its own `conn-...` id. On the stateless MCP protocol (2026-07-28, mcp 2.x) every request is its own
connection, so a stdio or in-process server uses one id for the whole process, and an HTTP server sends no
session id.

## Errors

The SDK never raises into your server. Sending runs on a background thread; when the collector is down, a batch
is tried three times with backoff and then dropped. A 4xx answer other than 429 is not retried. Events the collector
rejects (listed in its answer) count as dropped and go to `on_error`. Arguments over 32 KB are replaced by a size note.
Values masked by key are also masked where they reappear in error text, such as a validation error quoting the input.

On mcp 2.x, `MCPServer` tells the client only "Error executing tool <name>" when a tool raises. The event keeps
the real cause too, masked like all error text.

## Develop

```sh
uv venv --python 3.12 .venv
uv pip install --python .venv/Scripts/python.exe -e ".[dev]"
.venv/Scripts/python.exe -m pytest
```

Against a running collector: `python scripts/e2e.py http://localhost:8788 <api key>`.
