Offline, LLM-free safety & conformance auditor for the MCP sampling channel (sampling/createMessage).
The client's LLM is the understudy an untrusted server directs.
understudy(the tool) watches that borrowed performance and reports when the server oversteps.
understudy replays a captured sampling/createMessage exchange against a rule
catalog spanning six families and emits a scored report plus a CI exit-code
gate. It never calls a model — every check is static analysis of the captured
JSON. Pure Python standard library, zero dependencies.
Most MCP security tooling looks at the tool-call surface (server → client tools). Two adjacent human-in-the-loop channels get far less scrutiny:
- Elicitation (
elicitation/create) — server → user. Audited by experiment 014 (askance). - Sampling (
sampling/createMessage) — server → client's LLM. This is its uncovered inverse, and the subject of this experiment.
Sampling inverts control: an MCP server stops being a passive tool and becomes an
active prompt author with influence over both what the client's model sees
(systemPrompt, messages, includeContext) and what it produces. Published
research in 2026 (Palo Alto Unit 42, Blueinfy, arXiv SoK 2512.08290) demonstrates
this channel driving prompt injection, cross-server context exfiltration, covert
tool invocation, and compute-draining token bombs — with reported attack success
rates of 58–72%.
Meanwhile the protocol itself moved: the 2026-07-28 revision deprecated
sampling entirely (SEP-2577) and gated cross-server context behind a new
sampling.context capability (SEP-2596). So a real auditor now has to reason
about both live abuse signatures and the new deprecation/capability contract.
understudy is the smallest thing that proves the idea: feed it a capture of the
sampling traffic your client received, and it tells you — deterministically,
offline, in CI — whether each exchange upholds the sampling contract and the
human-in-the-loop safety model, or whether an untrusted server is abusing the
borrowed LLM.
| Family | Rules | What it catches |
|---|---|---|
| Deprecation & capability | DEP001, CAP001–CAP005 |
sampling deprecation advisory (SEP-2577); includeContext values used without the sampling.context capability, and tool-enabled sampling without sampling.tools (SEP-2596) |
| Schema & structure | SCH001–SCH011 |
required/positive maxTokens; legal message roles & content types; image/audio data+mimeType; the tool_result no-mixing rule; the tool_use ↔ tool_result balance rule; priority/temperature/toolChoice sanity |
| Context confidentiality | CTX001, CTX002 |
includeContext: "allServers" as a cross-server exfiltration channel; "thisServer" as a same-server data-attachment risk |
| Injection & perception | INJ001–INJ004, PERC001–PERC003 |
prompt-injection markers in systemPrompt/messages; covert tool-invocation & exfiltration phrases; post-task token-drain piggybacks; invisible/zero-width & bidi characters; mixed-script (homoglyph) tool names |
| Resource abuse | COST001, COST002 |
maxTokens token bombs; modelPreferences steering toward the most expensive model |
| Human-in-the-loop & result | HITL001, HITL002, RES001–RES004 |
missing attestation that a human reviewed the prompt / response; CreateMessageResult role, content, model, and stopReason: "toolUse" conformance |
Run understudy --list-rules for the catalog straight from the code.
No third-party dependencies are required to run the tool; pytest is only needed
for the test suite.
# From the project root:
make install # creates .venv and installs the package + pytest (editable)
make test # run the test suite (46 tests)
make demo # audit both reference captures
# …or without make / without installing anything:
python -m understudy examples/conformant.json # score 100/A, exits 0
python -m understudy examples/malicious.json # score 0/F, exits 1
python -m understudy examples/malicious.json --format json
python -m understudy --list-rulesunderstudy CAPTURE [--format text|json] [--fail-on SEVERITY] [--color]
understudy --list-rules
--fail-onsets the CI gate threshold (info|low|medium|high|critical, defaulthigh). Any finding at or above it makes the process exit1.- Exit codes:
0gate passed ·1gate failed ·2usage / capture error.
A capture is a JSON document describing the sampling traffic your client
observed. understudy audits the logical sampling request, so it works whether
the request was sent directly (MCP 2025-06-18 / 2025-11-25) or wrapped inside an
InputRequiredResult.inputRequests under the draft MRT delivery — you record the
params either way.
result and humanReview are optional (a request-only capture is valid); when
present they unlock the result-conformance and human-in-the-loop families.
capture.json
│
▼
loader.py ──▶ Capture (typed view + structural load-errors)
│
▼
rules.py ──▶ 15 rule functions across 6 families ─▶ [Finding]
│ (each Finding: rule id, severity, family, exchange, locator, evidence)
▼
report.py ─▶ score (100 − Σ penalties, clamped) ─▶ grade A–F ─▶ text | json
│
▼
cli.py ────▶ exit 0 / 1 / 2 (CI gate keyed on --fail-on)
model.py—Severity,Family,Finding,Capture; the penalty table and capability lookup. No I/O, no rule logic.unicode_scan.py— self-contained invisible / bidi / mixed-script detection (no third-party confusables dependency).loader.py— lenient parsing: document-level failures raise; per-exchange shape problems become reportable findings so the audit degrades gracefully on hostile input rather than crashing.rules.py— the catalog. Every rule is a generator yieldingFindings; aRULESregistry documents each and powers--list-rules.report.py— deterministic scoring, grading, and rendering.cli.py— argument parsing and the exit-code gate.
-
Dynamic driver (chosen path for experiment 011
gauntlet/ 012courier): actually stand up a client, let a server issue sampling requests, and observe live behaviour. Rejected here. Sampling requires a real LLM in the loop to be interesting; driving it live would mean either burning tokens against a paid model (a secret/cost we don't have) or a stub that invalidates the injection findings. High CPU/maintenance, non-deterministic tests. -
Static capture auditor (chosen). Audit a recorded exchange. Trade-off: it cannot see abuse that only manifests in the model's output, and it relies on the client having captured the traffic. In return it is deterministic, dependency-free, instantly CI-gateable, safe to run on hostile input, and — the deciding factor — the injection/exfiltration/deprecation checks that matter most are all visible in the request JSON itself. Memory and CPU are negligible (a single pass over the document).
The scoring model is intentionally simple (fixed per-severity penalties, clamped to 0) so a score is explainable from the finding list alone rather than an opaque weighting.
Auditing the clean reference capture:
$ python -m understudy examples/conformant.json
understudy — MCP sampling safety & conformance audit
source: examples/conformant.json
============================================================
score: 100/100 grade: A
findings: 1 (critical=0 high=0 medium=0 low=0 info=1)
[INFO ] DEP001 (*)
sampling/createMessage is deprecated as of MCP 2026-07-28 (SEP-2577); new
implementations SHOULD NOT adopt it and existing ones SHOULD migrate to
integrating directly with LLM provider APIs
at capture.exchanges[*].request.method
Auditing the hostile reference capture (truncated — 30 findings, exit code 1):
$ python -m understudy examples/malicious.json ; echo "EXIT=$?"
understudy — MCP sampling safety & conformance audit
source: examples/malicious.json
============================================================
score: 0/100 grade: F
findings: 30 (critical=0 high=13 medium=11 low=5 info=1)
[HIGH ] CAP001 (m-1-injection)
includeContext='allServers' used without the client declaring the
'sampling.context' capability (SEP-2596)
at request.params.includeContext evidence: 'allServers'
[HIGH ] CTX001 (m-1-injection)
includeContext='allServers' lets one server harvest context from every
connected server — a cross-server exfiltration channel
at request.params.includeContext evidence: 'allServers'
[HIGH ] INJ001 (m-1-injection)
prompt-injection marker 'ignore previous' found in systemPrompt
at request.params.systemPrompt evidence: 'ignore previous'
[HIGH ] PERC001 (m-1-injection)
1 invisible/zero-width character(s) hidden in prompt text
(first: ZERO WIDTH SPACE @ 18)
at request.params.messages[0].content[0].text evidence: 'ZERO WIDTH SPACE'
[HIGH ] SCH007 (m-2-schema)
tool_use id(s) ['call_9'] have no matching tool_result
at request.params.messages[2].content evidence: "['call_9']"
... (23 more) ...
EXIT=1
examples/malicious.json is a deliberately hostile capture. tests/test_examples.py
asserts that understudy reports exactly this set of distinct rules — no
more, no fewer — so any drift breaks the build:
- m-1-injection:
CAP001,CAP003,CTX001(allServers exfil w/o capability),INJ001/INJ002(injection in system prompt + message),INJ003(covert tool write),INJ004(token-drain piggyback),PERC001(zero-width space),COST002(max-intelligence steering),HITL001(no prompt approval). - m-2-schema:
CAP002(tools w/o capability),SCH001(missing maxTokens),SCH003(bad role),SCH007(broken tool_use/tool_result balance),SCH008(priority > 1),SCH009(temperature 5),SCH010(badtoolChoice),PERC003(Cyrillic homoglyph tool name),RES001/RES002/RES003/RES004(result contract),HITL001/HITL002. - m-3-cost:
CAP001,CAP004,CTX002(thisServer),COST001(50k-token bomb). - Plus the capture-wide
DEP001advisory.
- Static, not behavioural.
understudyaudits the captured request/result JSON. It cannot detect abuse that only appears in the model's generated text, nor confirm that a client actually enforced human review — only that the capture attests to it. ThehumanReviewblock is an attestation you record; its absence is flagged, not proven-malicious. - Signature-based injection detection.
INJ*rules match known 2026 attack phrasings (Unit 42 et al.). They are a tripwire, not a complete classifier — a novel paraphrase can evade them, and benign text can coincidentally match (findings are advisory HIGH/MEDIUM, not proof).PERC*structural checks (invisible/bidi/mixed-script) are far harder to evade and higher confidence. - Capture fidelity is assumed. The tool trusts that the capture faithfully records what the client received; it does not intercept traffic itself.
- Deprecation-aware, version-agnostic. Rules encode the 2026-07-28 contract
(SEP-2577 / SEP-2596) but audit the logical request shape common to recent
revisions.
includeContextgating assumes capabilities are recorded underclientCapabilities. - The
MAX_TOKENS_BOMB_THRESHOLD(16k) and the expensive-model heuristic are deliberately conservative constants; tune them inrules.pyfor your workload.
MIT — see LICENSE. See RESEARCH.md for the signals that inspired this experiment.
{ "clientCapabilities": { "sampling": { "tools": {}, "context": {} } }, "exchanges": [ { "id": "summarize", "server": "release-notes-mcp", "request": { "method": "sampling/createMessage", "params": { "messages": [ /* … */ ], "maxTokens": 512 } }, "result": { "role": "assistant", "content": { "type": "text", "text": "…" }, "model": "claude-3-haiku-20240307", "stopReason": "endTurn" }, "humanReview": { "promptApproved": true, "responseApproved": true } } ] }