Skip to content

About

undertow - offline, LLM-free, pure-stdlib auditor for the MCP cancellation/abort plane: residue windows, effect commit verdicts, and the duplication channel opened when a broken stream is a cancellation to the server and a mandated new-id re-issue to the client (MCP 2026-07-28 / SEP-2575)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 042 — undertow

An offline, LLM-free, dependency-free (pure-stdlib) auditor for the MCP cancellation / abort plane.

Experiments 001–041 audited what happens when an agent goes forward: what it may call, what it may read, what it may remember, what comes back. undertow is the first entry on the stop leg — the one users reach for when something is going wrong, and the one nobody instruments.


Thesis

A cancellation is not an undo, and MCP 2026-07-28 quietly made that much harder to reason about. Two changes landed in the same revision:

  1. Cancellation became implicit. On Streamable HTTP, "closing the SSE response stream is the cancellation signal. The server MUST treat a client disconnect as cancellation of that request." No notifications/cancelled is sent or expected.
  2. Resumability was removed (SEP-2575). "A broken response stream loses the in-flight request; clients MUST re-issue it as a new request with a new request ID."

Those two sentences describe one network event. The server is told to read it as stop. The client is told to read it as do it again, under a fresh identity. Nothing in the protocol synchronises the two readings, and nothing bounds how long the server takes to actually stop.

So a dropped connection means: the tool may still be running, its side effects may still be committing, and a second copy of the same work is already in flight — carrying a different requestId, which means server-side deduplication keyed on request identity is not merely unreliable, it is provably unable to match the two attempts.

undertow measures that gap. Given a captured session and a declaration of when each tool's effects become durable, it computes the residue window of every cancelled request (how long the server kept working after the stop), places each declared effect inside or outside that window, and pairs cancelled requests with their re-issues to decide whether the duplication was suppressed by a stable idempotency key or actually happened. It is the smallest thing that proves the point: you pressed stop, the money still moved, and then it moved again.


Quick start

undertow has zero runtime dependencies — Python 3.11+ and the standard library. pytest is needed only to run the tests.

# The flagship case: a wire transfer that ignores the stop, commits, and re-runs.
python -m undertow audit fixtures/defective-http/session.jsonl \
    --effects fixtures/defective-http/effects.json

# Or via make
make run        # the flagship defective fixture
make demo       # all four fixtures
make test       # 211 tests
make rules      # the rule catalogue
make ci         # gate the conformant fixtures (exits 0)

Useful flags:

flag meaning
--format json full structured report (schemaVersion: 1) for CI ingestion
--fail-on critical|high|medium|low|info|none lowest severity that exits 1 (default high)
--min-score N also fail below a score
--stop-latency-warn-ms / --stop-latency-high-ms residue-window thresholds for UT204
--cancel-race-grace-ms how long after a response a cancel is still a benign network race
--reissue-horizon-ms how long after a cancel a fresh request still counts as a re-issue
-o FILE write the report to a file

Exit codes: 0 clean, 1 findings met the gate, 2 the audit could not run (bad capture, bad profile, bad options).


Inputs

1. The session capture (JSON Lines)

Anything that can see the wire can produce one: an MCP proxy, a client's debug log, a test harness. Blank lines and # comments are allowed so captures stay readable.

{"kind":"event","ts":1788220800.000,"event":"session_meta","transport":"http","clientTimeoutMs":30000,"maxTimeoutMs":120000}
{"kind":"message","ts":1788220810.000,"dir":"c2s","msg":{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{...}}}
{"kind":"event","ts":1788220810.200,"event":"client_disconnect","requestId":"10","detail":"user pressed stop"}
{"kind":"message","ts":1788220810.900,"dir":"s2c","msg":{"jsonrpc":"2.0","method":"notifications/progress","params":{...}}}

ts is a float, seconds since the Unix epoch. Recognised events:

event meaning
session_meta transport, clientTimeoutMs, maxTimeoutMs, client, server
stream_broken the response stream for requestId died unexpectedly
client_disconnect the client deliberately closed the stream for requestId
request_released the client gave up waiting and resolved requestId locally
server_activity out-of-band evidence the server was still working on requestId

2. The effect profile (optional, but it is where the value is)

The one thing that cannot be read off the wire: when a tool's side effects become durable.

{
  "version": 1,
  "tools": {
    "wire_transfer": {
      "readOnlyHint": false,
      "idempotencyKeyArg": null,
      "volatileArgs": ["arguments.clientNonce"],
      "effects": [
        {"name": "audit_entry",         "commitAfterMs": 50,  "external": true, "compensator": "void_audit"},
        {"name": "notify_counterparty", "commitAfterMs": 120, "external": true, "compensator": null},
        {"name": "debit_account",       "commitAfterMs": 900, "external": true, "compensator": null}
      ]
    }
  }
}
  • commitAfterMs — offset from request dispatch at which the effect is durable.
  • idempotencyKeyArg — the argument a server could deduplicate on across a fresh requestId.
  • volatileArgs — arguments that legitimately differ between two attempts at the same work (nonces, timestamps, and the idempotency key itself when you want to detect it rotating). These are excluded from the fingerprint used to match a re-issue to its original.

Architecture

capture.jsonl ──► capture.py ──► timeline.py ──┬─► residue.py ─────┐
                  (strict          (per-request │   (effect         │
                   validation)      lifecycles) │    verdicts)      ├─► rules.py ─► scoring.py ─► report.py
effects.json ───► profile.py ──────────────────┴─► duplication.py ─┘   (26 rules)   (caps +       (text | json)
                  (schema)                         (fingerprint +                     clamps)
                                                    re-issue pairing)

Two models carry the analysis.

The residue model. For a request dispatched at t0 and cancelled at tc, the residue window is [tc, te], where te is the last moment the server was observed doing work on that request (progress, request-scoped notifications, a late response, or an explicit server_activity event). Each declared effect commits at t0 + commitAfterMs, and lands in one of three buckets:

verdict commit point meaning
COMMITTED ≤ tc already durable when the cancel arrived
RACING tc < commit ≤ te landed inside the window — the cancel lost the race
AVOIDED > te beyond all observed server work

An effect that is COMMITTED or RACING, external, and has no compensator is unrecoverable: the stop was requested and the world changed anyway.

The duplication model. Requests are fingerprinted by canonical JSON of their arguments with _meta and declared volatile paths stripped. A cancelled request is paired with the nearest later request sharing its method, tool and fingerprint within the re-issue horizon. If a declared idempotency key survived the transition, duplication is suppressed (UT303). If not — and the original's residue window is non-empty — the work provably ran twice under two different request IDs (UT301).

Two approaches considered

A. Dynamic prober (drive a live server, cancel it, look for damage) B. Passive analyzer (chosen)
Evidence Ground truth: you see the double charge Inferred from timestamps plus a declared effect model
Coverage Only what you can safely provoke Every cancellation that ever happened in production traffic
Side effects Requires a server you are allowed to break None; reads a file
CI fit Needs a live environment per run Runs on a recorded artifact, hermetic and instant
Cost High: a fault-injecting harness per transport Low: one parser, two models

Chosen: B. The interesting cancellations are the ones a prober cannot manufacture — a user hitting stop 900ms into a settlement, on a connection that dropped for real reasons. Those are already in everybody's logs; nothing reads them. A prober would also have to cause the damage it reports, which is a hard sell for the exact tools that matter most. The cost of B is the effect profile: someone must state when each tool commits. That is a real cost, and it is also the useful part — writing the profile is the first time most teams have written down when their tool becomes irreversible.

Memory/CPU: the analysis is O(n²) in cancelled × total requests for re-issue pairing and linear everywhere else, over a capture held fully in memory. For session captures (thousands of messages) this is microseconds. See Limitations for the scale ceiling.


Rule catalogue

26 rules, each traceable to a normative sentence or to one of the two models. python -m undertow rules prints the catalogue with its spec references; python -m undertow rules UT301 prints one.

UT1xx — cancellation-channel conformance

id severity what
UT101 medium a response was sent for a cancelled request (SHOULD not)
UT102 medium cancelled request never resolved: no response, no local release — the client's slot leaks
UT103 medium cancellation references a request that was never issued
UT104 info→medium cancellation of an already-completed request (INFO inside the race grace window)
UT105 low the same request cancelled more than once
UT106 high server sent notifications/cancelled outside subscriptions/listen (MUST NOT, 2026-07-28)
UT107 low notifications/cancelled used on Streamable HTTP, where the stream close is the signal
UT108 high client disconnect not treated as cancellation — the server kept working (MUST)
UT109 info cancellation carries no reason
UT110 medium server kept emitting after the cancel point
UT111 medium progress notification for a token bound to no active request (MUST)
UT112 medium progress notification after completion (MUST stop)
UT113 low stream-level cancellation event on a stdio session, which has no per-request stream

UT2xx — liveness and timeouts

id severity what
UT201 medium→high progress keepalive can defeat the client timeout — notifications spaced below the request timeout, sustained past the ceiling (HIGH when no ceiling is declared)
UT202 low no per-request timeout declared
UT203 medium no maximum timeout ceiling declared (SHOULD always enforce one)
UT204 medium→high excessive stop latency — the residue window is too wide

UT3xx — the duplication channel

id severity what
UT301 low→critical confirmed double dispatch: cancelled with an open residue window, then re-issued with identical arguments under a new request ID. CRITICAL when the tool has uncompensated external effects
UT302 medium→high tool is exposed to mandated re-issue duplication: write-capable, external effects, no idempotency key
UT303 info duplication suppressed — the re-issue carried the same idempotency key
UT304 high the idempotency key rotated across the re-issue, so deduplication cannot fire
UT305 medium the re-issue reused the original request ID (SEP-2575 requires a new one)

UT4xx — task lifecycle · UT5xx — effect residue · UT9xx — capture coverage

id severity what
UT401 high a task handle outlives the cancellation of the request that minted it — no tasks/cancel sent
UT402 medium tasks/cancel sent but the task never reached a terminal status (cancellation is cooperative)
UT501 high unrecoverable effect already committed when the cancel arrived
UT502 critical unrecoverable effect committed inside the residue window
UT503 low tool declares external effects and no compensator for any of them
UT504 medium cancelled write-capable calls audited without an effect profile
UT901/902/903 info/medium capture out of order, unknown events, or no declared transport

Scoring

Start at 100; deduct 25/12/5/2/0 by severity, with each rule's total deduction capped at twice its worst finding's weight so one chatty rule cannot dominate. Grades A≥95, B≥85, C≥70, D≥55, else F. Two categorical clamps then apply: any CRITICAL caps the grade at D, any HIGH caps it at B.


Sample run

Verbatim output of python -m undertow audit fixtures/defective-stdio/session.jsonl --effects fixtures/defective-stdio/effects.json:

==============================================================================
undertow - MCP cancellation / abort-plane audit
==============================================================================
capture       : fixtures\defective-stdio\session.jsonl
transport     : stdio
effect profile: fixtures\defective-stdio\effects.json
timeouts      : request=not declared  ceiling=not declared
volume        : 8 messages, 2 events, 2 requests, 2 cancelled, 0 task(s)

RESIDUE WINDOWS
------------------------------------------------------------------------------
  request 1      run_migration              cancel=notification   stop-latency=1400.0ms
      post-cancel activity: progress(+300.0ms), progress(+1100.0ms), response(+1400.0ms)
      !! effect alter_schema       commit=+700ms -> RACING    compensator=none
  request 2      noop_probe                 cancel=stream_broken  stop-latency=0.0ms
      (no effects declared for this tool)

DUPLICATION CHANNEL
------------------------------------------------------------------------------
  no re-issue of a cancelled request detected

FINDINGS
------------------------------------------------------------------------------
  [CRITICAL]
    UT502  (1)  unrecoverable effect committed inside the residue window
      effect 'alter_schema' of run_migration committed 200.0ms *after* the cancel point for request 1, inside a 1400.0ms residue window, and has no compensator: the stop was requested, ignored, and cannot be undone
  [MEDIUM]
    UT101  (1)  response sent for a cancelled request
      request 1 was cancelled at +500.0ms but the server still answered 1400.0ms after the cancel point
    UT102  (2)  cancelled request never released by the client
      request 2 was cancelled and never resolved: no response and no 'request_released' event, so the client's request slot stays occupied
    UT110  (1)  server kept emitting after the cancel point
      request 1 produced 2 server emission(s) up to 1100.0ms after the cancel point (progress)
    UT204  (1)  excessive stop latency
      request 1 kept the residue window open for 1400.0ms after the cancel point (warn above 1000.0ms)
  [LOW]
    UT105  (1)  duplicate cancellation for one request
      request 1 received 2 notifications/cancelled
    UT113  (2)  stream-level cancellation event on a stdio session
      request 2 carries a 'stream_broken' transport event on a stdio session, which has no per-request stream to close
    UT202  (-)  no per-request timeout declared
      the capture declares no per-request timeout (session_meta.clientTimeoutMs); a hung request can only be cancelled by a human
    UT503  (run_migration)  tool declares external effects with no compensator
      tool 'run_migration' declares 1 external effect(s) (alter_schema) and no compensator for any of them
  [INFO]
    UT109  (1)  cancellation carries no reason
      notifications/cancelled for request 1 carries no 'reason' string
    UT109  (1)  cancellation carries no reason
      notifications/cancelled for request 1 carries no 'reason' string

SCORE
------------------------------------------------------------------------------
  critical=1  high=0  medium=4  low=4  info=2
  top deductions: UT502:-25, UT101:-5, UT102:-5, UT110:-5, UT204:-5
  47/100  grade F
==============================================================================

And the flagship case from fixtures/defective-http/ — the whole thesis in one screen:

RESIDUE WINDOWS
------------------------------------------------------------------------------
  request 10     wire_transfer              cancel=disconnect     stop-latency=1200.0ms
      post-cancel activity: progress(+200.0ms), progress(+700.0ms), server_activity(+1200.0ms)
         effect audit_entry        commit=+50ms -> committed compensator=void_audit
      !! effect notify_counterparty commit=+120ms -> committed compensator=none
      !! effect debit_account      commit=+900ms -> RACING    compensator=none

DUPLICATION CHANNEL
------------------------------------------------------------------------------
  EXPOSED     10 -> 11  wire_transfer  fingerprint=be56c5fbf71a901b  gap=800.0ms
      no idempotency key declared; requestId-keyed dedup cannot match two distinct ids
  EXPOSED     12 -> 13  create_invoice  fingerprint=ae3bb29693160e21  gap=750.0ms
      arguments.idemKey: 'k-aaa' -> 'k-bbb'

  [CRITICAL]
    UT301  (10)  confirmed double dispatch across a cancel boundary
      request 10 was cancelled (disconnect) but the server kept working for 1200.0ms, and request 11
      re-issued identical arguments (fingerprint be56c5fbf71a901b) 800.0ms later. The two attempts
      carry different request IDs, so requestId-keyed deduplication is unsound; the tool has
      uncompensated external effect(s): notify_counterparty, debit_account
    UT502  (10)  unrecoverable effect committed inside the residue window
      effect 'debit_account' of wire_transfer committed 700.0ms *after* the cancel point for request
      10, inside a 1200.0ms residue window, and has no compensator: the stop was requested, ignored,
      and cannot be undone

Fixture ground truth

Four fixtures ship with the project, and tests/test_fixtures.py asserts the exact set of rules each one fires — no more, no less — so a regression that silences a rule or invents one fails.

fixture transport expected outcome
conformant-stdio stdio zero findings, 100/A. The user aborts a search; the client sends a reason, the server stops and sends no response, the client releases its own slot.
conformant-http http one INFO (UT303), 100/A. A stream breaks mid-charge; the server stops immediately, both effects are AVOIDED, and the mandated re-issue carries the same idempotency key, so duplication is suppressed.
defective-http http 23 rules, 2 critical / 9 high / 14 medium / 1 low / 3 info, 0/F.
defective-stdio stdio 10 rules, 1 critical / 4 medium / 4 low / 2 info, 47/F.

defective-http is built around eight distinct ground-truth defects:

  1. The money-moving case (requests 10→11) — a client_disconnect is ignored for 1200ms; notify_counterparty had already committed (UT501), debit_account commits inside the residue window with no compensator (UT502, CRITICAL), and the client re-issues the identical transfer 800ms later under a new request ID (UT301, CRITICAL) — plus UT108, UT110, UT204, UT302.
  2. The rotated key (requests 12→13) — same shape, but create_invoice does declare an idempotency key and the client regenerates it on retry (UT304), so the declared defence is inert. Its effect also races the cancel, but it has a compensator, so UT502 correctly stays silent.
  3. Server cancel misuse (request 14) — the server sends notifications/cancelled for a tools/call (UT106), and emits progress after the response (UT112).
  4. Bookkeeping drift — a cancel for request 999, which was never issued (UT103), and a progress notification for ghost-token (UT111).
  5. Timeout defeat (request 15) — progress every 20.5s under a 30s request timeout, sustained for 62s with no declared ceiling (UT201 + UT203).
  6. Task orphaning — task-9 outlives the disconnect of the request that minted it (UT401, plus UT104 because the cancel arrived after the handle came back); task-10 is sent tasks/cancel and is still working on the next tasks/get (UT402).
  7. Same-id re-issue (request 20) — retried under its original ID (UT305).
  8. Capture hygiene — a lagging-clock line (UT901) and an unknown proxy_note event (UT902).

Assumptions & limitations

Stated plainly, because the residue model is only as honest as its inputs.

  • Absence of evidence is treated as a stop. If a capture shows no server activity after the cancel point, undertow reports a zero-width residue window and effects beyond it as AVOIDED. A server that keeps working silently looks identical to one that stopped. Emit server_activity events from a proxy or an instrumented server if you need that closed; without them the tool is optimistic by construction, and it says so rather than guessing.
  • commitAfterMs is a declaration, not a measurement. The verdicts are exactly as good as the profile. A tool whose commit point varies with input size needs the pessimistic (earliest) value.
  • Without an effect profile the duplication channel goes partly blind. Fingerprint matching depends on volatileArgs to see past rotating nonces; the shipped defective-http fixture produces zero re-issue pairs when audited without its profile, and undertow reports that gap explicitly as UT504 rather than passing silently. This is a deliberate trade: no heuristic guessing about which arguments are semantically irrelevant.
  • Correlating request-scoped notifications requires a convention. notifications/progress binds through progressToken, which is normative. Everything else binds through _meta["io.modelcontextprotocol/relatedRequestId"], which is a capture convention this project defines, not a spec field. Captures without it simply contribute less evidence.
  • JSON-RPC ids are keyed by their string rendering, so the string "1" and the integer 1 are treated as the same request. A session that deliberately uses both is mis-analysed; no real client does this, and MCP gives no reason to.
  • Re-issue pairing is a heuristic, and it is O(cancelled × requests). Two genuinely distinct calls with identical arguments inside the horizon will pair. Tighten --reissue-horizon-ms for chatty sessions. For very large captures (10⁵+ requests) the pairing loop is the first thing that would need an index; it is deliberately not optimised for a prototype.
  • This is a passive analyzer. It never connects to a server, executes a tool, or sends a byte. Everything it knows comes from a file.
  • UT201 reasons about the declared timeouts, not the client's real behaviour. If session_meta misstates them, the finding is wrong in the same direction.
  • Only the cancellation plane is audited. Authorization, schema conformance, content safety and the rest are prior experiments' problems (001–041); undertow deliberately does not duplicate them.

Development

python -m pytest tests     # 211 tests, ~0.3s, no network, no fixtures beyond the repo

The package is pure standard library: json, hashlib, argparse, dataclasses, enum, logging, pathlib, copy, math. Every failure mode raises a typed exception (CaptureError, ProfileError, ConfigError) carrying a path:line or path: pointer location, and the CLI maps those to exit code 2 — nothing fails silently.

See RESEARCH.md for the signals this was built from.

MIT licensed.

About

undertow - offline, LLM-free, pure-stdlib auditor for the MCP cancellation/abort plane: residue windows, effect commit verdicts, and the duplication channel opened when a broken stream is a cancellation to the server and a mandated new-id re-issue to the client (MCP 2026-07-28 / SEP-2575)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages