mcpledger 0.1.0__tar.gz
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-0.1.0/.gitignore +3 -0
- mcpledger-0.1.0/LICENSE +21 -0
- mcpledger-0.1.0/PKG-INFO +112 -0
- mcpledger-0.1.0/README.md +87 -0
- mcpledger-0.1.0/pyproject.toml +46 -0
- mcpledger-0.1.0/src/mcpledger/__init__.py +7 -0
- mcpledger-0.1.0/src/mcpledger/exit.py +37 -0
- mcpledger-0.1.0/src/mcpledger/instrument.py +306 -0
- mcpledger-0.1.0/src/mcpledger/py.typed +0 -0
- mcpledger-0.1.0/src/mcpledger/redact.py +115 -0
- mcpledger-0.1.0/src/mcpledger/transport.py +256 -0
- mcpledger-0.1.0/tests/conftest.py +126 -0
- mcpledger-0.1.0/tests/sigterm_child.py +46 -0
- mcpledger-0.1.0/tests/test_instrument.py +246 -0
- mcpledger-0.1.0/tests/test_redact.py +52 -0
- mcpledger-0.1.0/tests/test_shared_sender.py +79 -0
- mcpledger-0.1.0/tests/test_sigterm.py +51 -0
- mcpledger-0.1.0/tests/test_transport.py +71 -0
mcpledger-0.1.0/LICENSE
ADDED
|
@@ -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.
|
mcpledger-0.1.0/PKG-INFO
ADDED
|
@@ -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,87 @@
|
|
|
1
|
+
# mcpledger (Python)
|
|
2
|
+
|
|
3
|
+
Records every tool call your Python MCP server handles and sends it to an mcpledger collector: who called,
|
|
4
|
+
which tool, the arguments, the result status, how long it took. Personal data is masked inside your server
|
|
5
|
+
before anything is sent.
|
|
6
|
+
|
|
7
|
+
Works with the official `mcp` package, version 1 (`FastMCP`, low-level `Server`) and version 2 (`MCPServer`,
|
|
8
|
+
low-level `Server`).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pip install mcpledger # or: uv add mcpledger
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Use it
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
from mcp.server.mcpserver import MCPServer # mcp 1.x: from mcp.server.fastmcp import FastMCP
|
|
20
|
+
import os
|
|
21
|
+
|
|
22
|
+
from mcpledger import instrument
|
|
23
|
+
|
|
24
|
+
server = MCPServer("payments-ops", version="1.0.0")
|
|
25
|
+
trail = instrument(
|
|
26
|
+
server,
|
|
27
|
+
api_key=os.environ["MCPLEDGER_KEY"],
|
|
28
|
+
endpoint="https://your-collector.example.com",
|
|
29
|
+
identify=lambda ctx: current_user_id(), # optional: the end user behind the call, from your auth
|
|
30
|
+
)
|
|
31
|
+
# register tools as usual, before or after instrument()
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Options: `identify(ctx)` gets the request context and may be async. `redact_keys` adds argument names to mask
|
|
35
|
+
(strings or regex patterns). `flush_interval` (seconds, default 2) and `max_batch` (default 50) control sending.
|
|
36
|
+
`on_error` receives send failures. `disable_redaction=True` is for local testing only.
|
|
37
|
+
|
|
38
|
+
`trail.flush()` and `trail.close(timeout=5)` are async; `flush_sync()` and `close_sync()` exist for sync code. `close` sends
|
|
39
|
+
what is queued for at most `timeout` seconds and counts the rest as dropped. Queued events
|
|
40
|
+
are also sent when the process exits. `trail.dropped` counts events that could not be delivered.
|
|
41
|
+
|
|
42
|
+
## One sender per collector
|
|
43
|
+
|
|
44
|
+
Every `instrument()` call with the same `api_key` and `endpoint` in a process shares one sender: one queue and
|
|
45
|
+
one background thread. A server built per request (stateless HTTP) therefore still sends in batches.
|
|
46
|
+
`flush()` sends the shared queue, and `dropped` counts for every server on it. `close()` flushes, and only the
|
|
47
|
+
last Trail on a sender stops it. The sending options (`flush_interval`, `max_batch`, `max_queue`, `on_error`)
|
|
48
|
+
come from the first `instrument()` call for that destination; later calls do not change them. At normal
|
|
49
|
+
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
|
|
50
|
+
did before: your own handler runs, the default action ends the process, or an ignored signal stays ignored. The
|
|
51
|
+
hook is installed from the main thread only. A framework that installs its own SIGTERM handler later (uvicorn,
|
|
52
|
+
for one) replaces it, and its graceful shutdown then ends in a normal exit, which atexit covers. On Windows a
|
|
53
|
+
SIGTERM from another process ends the process without running any handler, so call `close()` yourself where
|
|
54
|
+
you can.
|
|
55
|
+
|
|
56
|
+
## What gets masked
|
|
57
|
+
|
|
58
|
+
Values under secret-looking keys (password, token, api key, authorization, cookie, session id, private key,
|
|
59
|
+
OTP, PIN, CVV) become `[redacted]`. Inside any string, emails become `[email]`, card numbers that pass the Luhn
|
|
60
|
+
check become `[card]` and IBANs become `[iban]`. Error text is masked the same way.
|
|
61
|
+
|
|
62
|
+
## Sessions
|
|
63
|
+
|
|
64
|
+
Each event carries the transport session id when there is one (streamable HTTP). Without one, each connection
|
|
65
|
+
gets its own `conn-...` id. On the stateless MCP protocol (2026-07-28, mcp 2.x) every request is its own
|
|
66
|
+
connection, so a stdio or in-process server uses one id for the whole process, and an HTTP server sends no
|
|
67
|
+
session id.
|
|
68
|
+
|
|
69
|
+
## Errors
|
|
70
|
+
|
|
71
|
+
The SDK never raises into your server. Sending runs on a background thread; when the collector is down, a batch
|
|
72
|
+
is tried three times with backoff and then dropped. A 4xx answer other than 429 is not retried. Events the collector
|
|
73
|
+
rejects (listed in its answer) count as dropped and go to `on_error`. Arguments over 32 KB are replaced by a size note.
|
|
74
|
+
Values masked by key are also masked where they reappear in error text, such as a validation error quoting the input.
|
|
75
|
+
|
|
76
|
+
On mcp 2.x, `MCPServer` tells the client only "Error executing tool <name>" when a tool raises. The event keeps
|
|
77
|
+
the real cause too, masked like all error text.
|
|
78
|
+
|
|
79
|
+
## Develop
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
uv venv --python 3.12 .venv
|
|
83
|
+
uv pip install --python .venv/Scripts/python.exe -e ".[dev]"
|
|
84
|
+
.venv/Scripts/python.exe -m pytest
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Against a running collector: `python scripts/e2e.py http://localhost:8788 <api key>`.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.26"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
# The published name. Renaming the package is this line plus "name" in packages/sdk/package.json (docs/release.md).
|
|
7
|
+
name = "mcpledger"
|
|
8
|
+
dynamic = ["version"]
|
|
9
|
+
description = "Audit trail and analytics for MCP servers: records every tool call, redacts personal data before it leaves your server."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
authors = [{ name = "Muhammad Mairaj" }]
|
|
15
|
+
keywords = ["mcp", "model-context-protocol", "audit", "audit-trail", "ai-agents", "observability"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: System :: Logging",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
dependencies = ["mcp>=1.9"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Source = "https://github.com/thisismairaj/mcpledger"
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
dev = ["pytest>=8", "anyio>=4"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.version]
|
|
36
|
+
path = "src/mcpledger/__init__.py"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/mcpledger"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["/src/mcpledger", "/tests", "/README.md", "/LICENSE", "/pyproject.toml"]
|
|
43
|
+
exclude = ["**/__pycache__"]
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
@@ -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)
|
|
File without changes
|