Skip to content

About

penumbra - deterministic cache-coherence model checker for the MCP 2026-07-28 caching model (ttlMs/cacheScope/listChanged). Offline, LLM-free, pure stdlib.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 028 — penumbra

A deterministic cache-coherence model checker for the MCP 2026-07-28 caching model (ttlMs / cacheScope / listChanged).

Offline, LLM-free, dependency-free (pure stdlib). No network access anywhere in the package, no wall clock, no randomness.


Thesis

The MCP 2026-07-28 specification made client-side caching normative: tools/list, prompts/list, resources/list, resources/templates/list, resources/read and server/discover now carry ttlMs and cacheScope (SEP-2549). That solves a real scaling problem — vendors are actively advising teams to drop sticky sessions and let clients cache lists for as long as the server permits — and it opens a correctness one that nothing measures. The spec says the quiet part itself: "TTL is a freshness hint, not a guarantee. Servers MAY change the underlying data before the TTL expires."

Between two fetches, an agent plans and acts against a contract the server may have already replaced. Today's defence against tool redefinition — fingerprint the definition and compare on re-fetch, as the Vercel AI SDK's detectToolDrift does — is a comparison between two observations, so it is structurally blind to the interval in which no second observation happens. And ttlMs is exactly the knob that decides how long that interval lasts. A server may legally publish ttlMs: 3600000 and never advertise listChanged; nothing in the protocol can then invalidate the cache early, so every definition change is guaranteed to go unseen for up to an hour. That is not a bug in anyone's implementation. It is a spec-legal configuration, and it converts a rug pull from an opportunistic attack into a scheduled one.

penumbra is the smallest thing that proves the point: give it a server policy, a timeline of server-side changes, a model of one client's cache behaviour, and the actions an agent takes, and it simulates the interval on a virtual clock and emits counterexample traces naming the exact instants at which belief and truth diverged — and what the agent did while they were apart.

It is not a scanner. Nothing here reads a manifest and pattern-matches it. It is a discrete-event simulator with a rule catalog over its output, which is the only shape that can answer a question about time.

What it finds

33 rules in 7 families. python main.py rules prints the catalog.

Family What it means
PHANTOM The client acts on a primitive the server already removed.
ECLIPSE The client is blind to a primitive that already exists.
DRIFT The contract moved underneath a stable name.
TRUST Stale belief about a tool's authority — the security core.
SCOPE cacheScope and authorization-context violations.
CONF Conformance of the declared hints and the client's cache behaviour.
PAGE Pagination incoherence across a multi-page fetch.

The three findings that motivated the build:

  • TRUST01 (CRITICAL) — the client auto-approved a call because its cached annotations said readOnlyHint: true; the live tool says otherwise. Cache staleness converted directly into unreviewed write authority.
  • TRUST04 (HIGH) — a long ttlMs with no invalidation path. Reported from the declared policy alone, before any mutation happens, because the window is guaranteed by configuration rather than by luck.
  • SCOPE02 (CRITICAL) — a cache entry produced under one authorization context served to another, where the two ground truths differ. The spec's own security section warns that a "public" result "may be shared outside of the initial request's authorization context."

Run it

Python 3.11+. No dependencies to install for the tool itself.

python main.py check fixtures/hostile.json     # grade a scenario
python main.py check fixtures/clean.json       # the false-positive gate
python main.py check fixtures/hostile.json --trace --json
python main.py matrix fixtures/hostile.json    # every client profile, side by side
python main.py rules                           # the catalog
python main.py profiles                        # bundled client models

Or with make:

make run        # check the hostile fixture
make clean-run  # check the clean fixture
make matrix
make test       # pytest in an isolated venv

Exit codes: 0 clean, 1 findings at or above --fail-on (default LOW), 2 usage or scenario error. That makes penumbra check a CI gate.

Tests

python -m pytest tests/ -q

160 tests. Every rule in the catalog has a test that makes it fire and, where a false positive is plausible, a test that keeps it quiet.

Sample run

$ python main.py check fixtures/hostile.json
========================================================================================
penumbra  scenario: hostile/long-ttl-no-invalidation
          client:   hostile-gateway
========================================================================================

Declared caching policy
----------------------------------------------------------------------------------------
  method                  ttlMs  scope    listChanged  invalidation
  resources/list             -5  private  no           NONE
  tools/list            3600000  public   no           NONE

Score: 0/100   Grade: F   Findings: 29
  critical=3  high=10  medium=13  low=3  info=0
  families: PHANTOM=4  ECLIPSE=5  DRIFT=6  TRUST=4  SCOPE=4  CONF=3  PAGE=3

Findings
----------------------------------------------------------------------------------------
[ 1] CRITICAL SCOPE01  t=0ms
     public cacheScope on a context-varying result
     tools/list is declared cacheScope=public, but its membership demonstrably differs
     between authorization contexts in this scenario; a shared cache may serve one
     tenant's view to another

[ 2] CRITICAL SCOPE02  t=100000ms
     cached entry served across authorization contexts
     a cache entry produced under authorization context 'tenant-a' was served to
     'tenant-b'; the two ground truths differ, exposing 'billing_export',
     'delete_project'
     witness: #17, #1

[ 3] CRITICAL TRUST01  t=500000ms
     auto-approval granted on a stale readOnly annotation
     the client auto-approved 'config_read' because its cached annotations said
     readOnlyHint=true; the live tool declares readOnlyHint=False. A 490000ms-old cache
     entry was converted directly into unreviewed write authority
     witness: #32, #1

[ 5] HIGH     TRUST04  t=0ms  window=3600000ms (1.0h)
     spec-legal invalidation-free rug-pull window
     tools/list publishes ttlMs=3600000 and listChanged is not advertised. Nothing in
     the protocol can invalidate the cache early, so any definition change is guaranteed
     to go unseen for up to 3600000ms

[ 8] HIGH     PHANTOM01  t=150000ms
     call to a tool the server has removed
     agent invoked tool 'delete_project' from a cache entry 140000ms old; the server had
     already removed it, so the call cannot succeed
     witness: #23, #1

[11] HIGH     DRIFT02  t=400000ms
     required argument missing under the live schema
     call to 'billing_export' omits 'confirm', which the live inputSchema requires but
     the cached one did not
     witness: #29, #1

... 23 more findings ...

And the false-positive gate — a server that caches for five minutes, paginates, serves two tenants and mutates its tool surface three times mid-session:

$ python main.py check fixtures/clean.json
Score: 100/100   Grade: A   Findings: 0
  No coherence defects. The client's belief tracked the server's
  ground truth at every point an action was taken.

The profile matrix

The same hostile server graded against every bundled client model. This is the output that makes the thesis concrete: exposure is a property of the pair, and even a perfectly conformant client cannot escape a server that publishes a long TTL with no invalidation path.

$ python main.py matrix fixtures/hostile.json
  client profile        score  grade  findings   families
  --------------------------------------------------------------------------------------
  eager-approver            0      F        24   PHANTOM:2 ECLIPSE:5 DRIFT:6 TRUST:4 SCOPE:2 CONF:2 PAGE:3
  immortal-cache            0      F        26   PHANTOM:3 ECLIPSE:5 DRIFT:6 TRUST:4 SCOPE:2 CONF:3 PAGE:3
  notification-deaf         0      F        18   PHANTOM:2 ECLIPSE:4 DRIFT:1 TRUST:4 SCOPE:2 CONF:2 PAGE:3
  shared-gateway            0      F        14   PHANTOM:3 ECLIPSE:1 TRUST:1 SCOPE:4 CONF:2 PAGE:3
  spec-conformant           0      F        18   PHANTOM:2 ECLIPSE:4 DRIFT:1 TRUST:4 SCOPE:2 CONF:2 PAGE:3
  ttl-only                  0      F        18   PHANTOM:2 ECLIPSE:4 DRIFT:1 TRUST:4 SCOPE:2 CONF:2 PAGE:3
  ttl-poller                0      F        20   PHANTOM:2 ECLIPSE:4 DRIFT:1 TRUST:4 SCOPE:4 CONF:4 PAGE:3

immortal-cache picks up the rules the others cannot reach — PHANTOM05 and ECLIPSE03, the unbounded windows, where the divergence can never heal because the cache neither expires nor accepts an invalidation signal. That profile is modelled directly on claude-code #38324.

Architecture

scenario.json
     │
     ▼
scenario.py ── the only module that touches the filesystem
     │         strict validation; refuses rather than guesses
     ▼
  Scenario (frozen dataclasses)
     │
     ├──────────────► server.py    GroundTruth: what was true at instant t,
     │                             per authorization context
     │
     ├──────────────► client.py    ClientCache: storage + freshness under one
     │                             ClientProfile. Dumb on purpose.
     ▼
engine.py ── discrete-event simulator on a virtual integer-ms clock
     │        merges mutations / notifications / polls / agent actions into
     │        one totally-ordered log. RECORDS, never judges.
     ▼
  Timeline(events, observations, policy_facts)
     │        observations pair BELIEF against TRUTH at the instant of an action
     ▼
analyzer.py ── pure Timeline -> [Finding]. No I/O, no clock, no RNG.
     │
     ▼
report.py ── score, grade, exit code, text / JSON / matrix rendering

Two design decisions worth naming

Observation is split from judgement. The engine emits belief-vs-truth pairs; the analyzer decides which are defects. This is the same split #023 rampart used for probe-vs-audit, and it buys the same things: every rule is unit-testable against a synthetic timeline, a committed fixture and a freshly built scenario grade through identical code, and adding a rule cannot change what the simulator records.

Point evidence and interval evidence are both first-class. An action observation proves a defect occurred. A divergence window proves how long the client was wrong and whether it could ever heal on its own. Reporting only the first would miss TRUST04 — a guaranteed blind window that this particular scenario happened not to step on — and reporting only the second would miss the concrete failed call. The catalog uses whichever shape fits the claim, and window findings are deduplicated across overlapping cache entries so one defect observed twice stays one finding.

The alternative considered, and why it lost

Approach A (chosen): a domain-specific discrete-event simulator. ~1,600 lines of stdlib Python, a virtual integer-millisecond clock, deterministic tie-breaking by event class. Cheap to run (the full 160-test suite is 0.3s), trivially embeddable in CI, and every finding carries the sequence numbers that prove it.

Approach B (rejected): encode the caching model in TLA+ / Alloy and exhaustively model-check it. Genuinely attractive — cache coherence is the canonical TLA+ example, and exhaustive exploration would find windows a hand-written scenario misses rather than only confirming the ones you thought to write down.

Rejected on three grounds. Maintenance: it makes a model checker a hard dependency and puts the rule catalog in a language most MCP implementers cannot read, when the deliverable is meant to run in their CI. State-space: the interesting dimensions here are continuous-ish (TTL values, mutation instants, page-fetch gaps), so an honest exhaustive model needs aggressive discretisation and the abstraction becomes the thing you have to trust. Output shape: a TLA+ counterexample is a state sequence over the abstraction; what an engineer needs is "at t=150000ms your agent called a tool deleted 140 seconds earlier, here are the two event numbers." The simulator produces that natively.

The honest cost of choosing A: penumbra only finds defects in the scenarios you give it. It confirms, it does not search. Mitigations shipped: the matrix command sweeps every client profile against one server policy for free, and the policy-level rules (TRUST04, SCOPE01, CONF01–CONF03, SCOPE05) fire from the declared configuration alone and so do not depend on the scenario stepping on the right instant. A scenario generator that searches the timeline space is the obvious next step, and it is not in this prototype.

Scenario format

A scenario is one JSON document with five parts. See fixtures/clean.json for a commented-by-example version.

{
  "name": "my-deployment",
  "contexts": ["tenant-a", "tenant-b"],   // authorization contexts
  "maxStalenessMs": 60000,                // optional budget -> ECLIPSE02

  "server": {
    "policies": {
      "tools/list": { "ttlMs": 300000, "cacheScope": "private",
                      "pageScopeOverrides": { "1": "public" } }
    },
    "listChanged": ["tool"],              // kinds that emit list_changed
    "droppedNotifications": [],           // advertised but never delivered
    "notificationLatencyMs": 0,
    "pageSize": 2,                        // 0 = no pagination
    "pageFetchGapMs": 0,
    "nonCacheableMarkedCacheable": []     // -> CONF03
  },

  "client": "spec-conformant",            // a name, or an inline override object

  "initial":   [ { "kind": "tool", "name": "search", "spec": { ... },
                   "contexts": ["tenant-a"] } ],
  "mutations": [ { "at": 100, "op": "add|remove|update", "kind": "tool",
                   "name": "search", "spec": { ... }, "note": "why" } ],
  "actions":   [ { "at": 500, "op": "use_list|call_tool|read_resource|get_prompt",
                   "kind": "tool", "target": "search", "args": { ... },
                   "authContext": "tenant-a", "params": { "cursor": "p2" } } ]
}

spec is the definition body the server would return — description, inputSchema, annotations. It is compared structurally, so any JSON shape works.

Bundled client profiles

Profile Models
spec-conformant Everything the spec requires. The baseline.
notification-deaf Ignores listChanged — claude-code #13646, codex #33266.
immortal-cache Never expires, never invalidates — claude-code #38324.
shared-gateway One cache entry across authorization contexts.
ttl-only No listChanged support at all.
eager-approver Auto-approves anything its cached annotations call read-only.
ttl-poller Background-polls on the TTL, without jitter.

Any profile can be overridden inline per scenario:

"client": { "profile": "spec-conformant", "honors_ttl": false, "name": "hybrid" }

Assumptions & limitations

Stated plainly, because a simulator that overstates its fidelity is worse than no simulator.

  1. It confirms, it does not search. penumbra grades the scenarios you write. It does not explore the space of possible timelines. Policy-level rules are the exception — they fire from the declared configuration alone.
  2. Request parameters are cache-key material only. penumbra does not simulate server-side filtering or real cursor semantics. params exists to check the spec's "MUST NOT serve a cached response for a request whose method or parameters differ" rule, and nothing more.
  3. Pagination is modelled as offset-style. Real servers may use opaque cursors with snapshot semantics, which would not exhibit PAGE01/PAGE02. The spec explicitly disclaims cross-page consistency, so offset behaviour is the worst legal case rather than the only one — read PAGE findings as "this is possible under the spec", not "your server does this".
  4. Schema validation is deliberately shallow. DRIFT02/DRIFT03 check required, top-level type and enum. It is not a JSON Schema validator; a call it calls valid may still be rejected by a real server for a reason penumbra does not model.
  5. resources/read and server/discover are not simulated as cacheable operations. Only the four list methods are. resources/read appears only through nonCacheableMarkedCacheable (CONF03). Extending the model to per-URI read caching is a natural next step.
  6. Annotation semantics are taken at face value. penumbra reasons about the declared readOnlyHint / destructiveHint / openWorldHint, not what a tool actually does. Experiment #007 (overreach) is the entry that questions whether the declaration is honest; this one assumes it is and asks whether the client's copy of it is current.
  7. The TRUST04 threshold is a judgement call. 60s by default, adjustable with --rugpull-ttl-threshold-ms. There is no principled value; below some TTL "the client notices almost immediately" stops being a fair description, and one minute is where this catalog draws it.
  8. The score is a comparison aid, not a measurement. Severity weights (CRITICAL 40 / HIGH 15 / MEDIUM 6 / LOW 2 / INFO 0) are subtracted from 100 and floored at zero. Two scenarios both scoring 0/F are not equally bad. The counterexample traces are the product; the grade exists so CI can fail on a number.
  9. No network, no clock, no randomness. Every time value is a virtual integer millisecond supplied by the scenario. This is what makes a committed counterexample mean the same thing next month, and it is why penumbra can never observe a live server — it grades a description of one.

Novelty against the rest of the series

Experiments 001–027 are static manifest analysers (001–010), single-channel message auditors (011–022), a transport prober (#023), a terminal-rendering auditor (#024), two A2A auditors (#025, #026) and a client-side UI-bundle auditor (#027). Every one of them answers a question about an artifact: is this document, message or bundle safe?

penumbra is the series' first entry that answers a question about time. Its input is not an artifact but a timeline, and its output is not a verdict on a document but a set of intervals with counterexamples inside them. It is also the first entry whose core is a simulator rather than a parser or a prober.

The nearest neighbours, and the honest distinction from each:

  • #008 contravene classifies whether a change to a tool contract is breaking, by diffing two manifests. penumbra takes breakingness as given and asks the orthogonal question: for how long will clients keep using the old one, and what will they do with it? contravene grades the change; penumbra grades the window the change lives in.
  • #010 capsule content-hashes capabilities into a lockfile to detect mutation. Same relationship: detection at re-fetch time, silent about the interval between fetches.
  • #005 forkpoint is also temporal, but observational — it localises where real agent runs diverged from each other, from recorded traces. penumbra is generative: it derives divergence between a client and a server from a declared policy, with no runs required.

License

MIT — see LICENSE.

About

penumbra - deterministic cache-coherence model checker for the MCP 2026-07-28 caching model (ttlMs/cacheScope/listChanged). Offline, LLM-free, pure stdlib.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages