Skip to content

About

contravene: variance-aware breaking-change classifier for MCP tool contracts

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 008 — contravene

Variance-aware breaking-change classifier for MCP tool contracts. Diff two MCP tools/list manifests, classify every change as MAJOR / MINOR / PATCH under a variance model, compute the required semver bump, and fail CI when the declared version bump under-states it. Pure Python 3.11+ standard library. No LLM, no network, no paid APIs.

contravene old_manifest.json new_manifest.json --fail-on major

Thesis

The 2026-07-28 MCP release candidate made tool schemas first-class JSON Schema 2020-12 contracts: every tool has an inputSchema and (increasingly) an outputSchema, and servers MUST return output conforming to the declared schema (SEP-2106). But MCP servers evolve, and when a tool's contract changes between releases, clients that compiled and cached the old schema break silently — there is no semantic-versioning discipline on tool contracts and no tool to enforce one.

The non-obvious insight — and the reason a correct checker is more than a JSON diff — is that the two halves of a tool contract have opposite variance:

  • inputSchema is contravariant. The caller supplies the arguments. Narrowing the set of accepted inputs (a new required field, a lowered maximum, a removed enum value, closing additionalProperties) breaks existing callers. Widening it is safe.
  • outputSchema is covariant. The consumer reads the result. Widening the set of possible outputs (a new enum value, a dropped required, a relaxed field) breaks existing consumers, because their code never anticipated the new shape. Narrowing it is safe.

Most people get the output direction backwards. contravene encodes the asymmetry directly, so "the domain got smaller" is flagged MAJOR on an input and MINOR on an output — and vice versa. The smallest thing that proves the idea is a deterministic CLI that reads two manifests and returns the correct required semver bump plus a precise, per-field explanation, with a non-zero exit code when the declared bump is too small to be a CI gate.

What it checks

  • Input contracts (contravariant): new required properties, optional→required transitions, narrowed domains (type restriction, enum shrink, tighter numeric / length / pattern bounds, additionalProperties: true→false), incompatible type swaps.
  • Output contracts (covariant): removed required properties, required→optional transitions, widened domains (enum growth, loosened bounds, relaxed additionalProperties), outputSchema added or removed.
  • Behavioral / safety annotations: readOnlyHint, idempotentHint, destructiveHint, openWorldHint moving away from their safe value (a previously auto-approvable tool becoming mutating) is MAJOR.
  • Structural: tools added (MINOR) or removed / renamed (MAJOR).
  • Forward-looking warnings: adding an outputSchema surfaces the documented error-result validation collision (IBM/mcp-context-forge#4202); JSON Schema keywords outside the analyzed subset are flagged as "review manually" rather than silently assumed safe.

How to run

Requires only Python 3.11+. No installation needed.

# Human-readable report on the bundled example (v1.2.0 -> v1.3.0):
python -m contravene examples/server_v1.json examples/server_v2.json

# Machine-readable JSON:
python -m contravene examples/server_v1.json examples/server_v2.json --json

# As a CI gate — fail the build on any breaking change, ignoring versions:
python -m contravene old.json new.json --fail-on major

# Stricter output policy (also flags additive output fields, for consumers
# that reject unknown fields):
python -m contravene old.json new.json --policy strict

# Read the "new" manifest from stdin (e.g. piped from a live server):
some-mcp-client tools/list | python -m contravene baseline.json -

Or via make: make run, make json, make strict, make demo.

Accepted manifest shapes (auto-detected): an MCP tools/list result ({"tools": [ ... ]}), a bare list of tool objects, or a name-keyed object. Versions are read from version or serverInfo.version, or overridden with --from-version / --to-version.

Exit codes: 0 pass · 1 gate failed · 2 usage / parse error.

Use as a CI gate (GitHub Actions)

- name: Enforce semver on MCP tool contracts
  run: |
    python -m contravene \
      manifests/${{ github.base_ref }}.json \
      manifests/current.json \
      --from-version "$(cat manifests/base_version)" \
      --to-version   "$(cat VERSION)"

The job fails if the maintainer bumped, say, the minor version while actually removing a required output field.

Run the tests

The suite is written against the standard-library unittest runner, so it passes with zero installs:

python -m unittest discover -s tests -p "test_*.py"
# 79 tests, OK

pytest also discovers and runs them (make test prefers it when installed).

Architecture

 old.json ─┐
           ├─▶ compare.load_manifest ─▶ normalized {tools, version}
 new.json ─┘                                  │
                                              ▼
                          compare.compare  (pairs tools by name)
                                              │
                 ┌────────────────────────────┼───────────────────────────┐
                 ▼                            ▼                            ▼
        schemadiff.diff_schema        classify.classify_tool_pair   semver.delta_level
   (position-AGNOSTIC facts:          (interprets each fact under    (declared bump
    domain narrowed/widened,           INPUT=contravariant /          from versions)
    property add/remove, ...)          OUTPUT=covariant + policy)
                 └────────────────────────────┼───────────────────────────┘
                                              ▼
                                         model.Report
                                              │
                         report.decide_gate + render_text / render_json
                                              ▼
                                   stdout + exit code (CI gate)

The key design decision is the two-stage split:

  1. schemadiff.py walks the two JSON Schemas and emits position-agnostic facts — e.g. "the accepted value domain narrowed at /properties/limit". It knows nothing about inputs vs outputs.
  2. classify.py interprets each fact under a Position (INPUT ⇒ contravariant, OUTPUT ⇒ covariant) and a policy, assigning the semver severity.

This makes the variance model — the intellectual core — a small, independently testable interpretation layer, and keeps the gnarly schema-walking logic free of compatibility semantics. Severities are an orderable IntEnum, so the required bump is simply max() over all gating findings.

Two approaches considered, and the trade-off

(A) Runtime response validation — spin up the two server versions, call every tool, and validate live responses against the declared outputSchema (what the official conformance suite does). Rejected: needs runnable servers, credentials, side-effecting tool calls, and non-deterministic coverage; it catches response bugs, not contract-evolution bugs, and can't run as a fast pre-merge gate. High CPU, high maintenance, flaky.

(B) Static schema-vs-schema diff with a variance model — chosen. Reads two JSON manifests only; fully deterministic; runs in milliseconds with no dependencies; catches the exact class of silent breakage (contract drift) that runtime testing misses because the maintainer never re-ran the client. The trade-off is that it reasons about declared schemas, not runtime behavior — a server whose implementation lies about its schema is out of scope (that is Experiment 007 overreach's and runtime conformance's job). Memory footprint is trivial (two parsed JSON docs); maintenance cost is a well-bounded set of JSON-Schema keyword rules.

The two are complementary: contravene gates the contract, conformance suites gate the implementation.

Assumptions & limitations

  • JSON Schema subset. contravene analyzes the keywords that carry input/output compatibility meaning: type, enum, const, properties, required, additionalProperties, items, numeric bounds (minimum, maximum, exclusive*, multipleOf), string/array bounds (minLength, maxLength, pattern, format, minItems, maxItems, uniqueItems). Combinators and references ($ref, allOf/anyOf/oneOf, if/then/else, patternProperties, prefixItems, dependentRequired, …) are not interpreted; when a tool uses them, contravene emits an explicit "review manually" warning rather than assuming safety. This is a deliberate soundness choice: never claim a change is safe from a schema we cannot fully read.
  • Regex/format subset relations are undecidable in general, so a changed pattern or format is conservatively treated as a narrowing (potential break) rather than proven-compatible.
  • Tool renames read as remove + add (both MAJOR/MINOR), since names are the identity key; contravene does not attempt fuzzy rename detection.
  • Semver 0.x nuance. contravene compares the declared bump level against the required level directly. Under the common 0.x convention a minor bump may carry breaking changes; if you follow that convention pre-1.0, use --fail-on major instead of relying on the version comparison.
  • Behavioral hints are advisory metadata. A safety-hint downgrade is flagged MAJOR from a trust/policy standpoint even though it is not a schema break.
  • Scope is a prototype: correctness of the variance rules is covered by 79 tests, but the keyword coverage is intentionally bounded to what a single run can implement soundly.

Sample run

python -m contravene examples/server_v1.json examples/server_v2.json (the example evolves acme-files from 1.2.0 to 1.3.0 — a declared MINOR that actually contains several MAJOR breaks):

contravene - MCP tool-contract compatibility report
=======================================================
versions:        1.2.0 -> 1.3.0
declared bump:   minor
required bump:   MAJOR  (policy: lenient)
suggested next:  2.0.0

12 finding(s):

  [MAJOR] delete_file
          tool removed: clients calling it will fail
  [MAJOR] read_file /annotations/readOnlyHint
          safety hint readOnlyHint moved away from its safe value (True -> False): agents/policies that auto-approved this tool may now trigger unsafe behavior
  [MAJOR] read_file /outputSchema/properties/encoding
          [output] output domain widened at /outputSchema/properties/encoding: consumers may receive values they do not handle (allowed values added: 'gzip')
  [MAJOR] search_files /inputSchema/properties/limit
          [input] input domain narrowed at /inputSchema/properties/limit: previously valid arguments will be rejected (upper bound tightened from 100 to 50)
  [MAJOR] search_files /inputSchema/properties/workspace_id
          [input] new required input property at /inputSchema/properties/workspace_id: existing callers that omit it will be rejected
  [MAJOR] search_files /outputSchema/properties/total
          [output] required output property removed at /outputSchema/properties/total: consumers depending on it will break
  [MINOR] list_dir /outputSchema
          added an outputSchema (server now promises structured output)
  [MINOR] move_file
          new tool added
  [MINOR] read_file /outputSchema/properties/size
          [output] new output property at /outputSchema/properties/size (additive)
  [MINOR] search_files /inputSchema/properties/sort
          [input] new optional input property at /inputSchema/properties/sort
  [MINOR] search_files /outputSchema/properties/facets
          [output] new output property at /outputSchema/properties/facets (additive)
  [note ] list_dir /outputSchema
          outputSchema added: standard MCP error results (isError:true with text content) do NOT conform to a success outputSchema. Clients must validate error and success results separately (cf. ibm/mcp-context-forge#4202).

gate: FAIL - declared bump 'minor' is smaller than required 'major' (1.2.0 -> 1.3.0)

Exit code: 1. Notice how the same structural move — a shrinking value set — is MAJOR on search_files.limit (an input) but the widening of read_file.encoding (an output, gaining gzip) is also MAJOR: the variance model catches both directions of breakage that a naive "added vs removed" diff would misclassify.

Project layout

contravene/
  model.py       data model: Severity, Position, SchemaChange, Finding, Report
  schemadiff.py  position-agnostic JSON Schema (2020-12 subset) differ
  classify.py    variance-aware interpretation of changes -> semver severity
  semver.py      dependency-free semver parse / delta / bump
  compare.py     manifest loading + top-level comparison engine
  report.py      text/JSON rendering + CI gate decision
  cli.py         argparse CLI, exit codes
examples/        server_v1.json, server_v2.json (a realistic breaking evolution)
tests/           79 unittest tests (schemadiff, classify, semver, CLI e2e)

License

MIT — see LICENSE.


Development Experiment 008 in an autonomous daily R&D series. Built LLM-free and dependency-free; verified with 79 passing tests and the smoke run shown above.

About

contravene: variance-aware breaking-change classifier for MCP tool contracts

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages