# Which invariants prevent MCP capability attestation from silently diverging from runtime tool behavior **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that bind to third-party MCP servers whose `tools/list` schema is attested at registration time but whose tool implementations are fetched, hot-reloaded, or proxied at call time. Does not apply to first-party in-process tools or to servers where the schema and implementation are co-versioned and co-signed as a single immutable artifact. ## Core Distinction There are two things an MCP client can verify about a third-party tool provider, and they are routinely conflated: 1. **Capability attestation** — the *declared* contract: the `name`, `description`, `inputSchema`, and (where present) an attestation signature over that JSON, produced at registration. 2. **Runtime integrity** — the *actual* behavior when `tools/call` executes: the arguments the server actually parses, the side effects it actually performs, and the result shape it actually returns. The failure mode is not that either one is wrong in isolation. It is that **attestation and runtime are bound at different times and never re-bound**. A server can pass attestation at `T0`, be re-deployed at `T1`, and continue serving calls under the `T0` attestation because the client cached the capability record keyed by server identity (a URL, a process handle, an `mcp.json` entry) rather than by the content hash of the implementation that answered the call. The agent then reasons over a schema that no longer describes the code it is invoking. This is a *time-of-check / time-of-use* gap, but at the semantic layer: the checked object is a JSON schema and the used object is a program, and nothing forces them to be the same version. This is distinct from prompt injection (adversarial *content*) and from schema negotiation mismatch (two peers disagreeing on a *shared* schema). Here both parties believe they agree; the divergence is between what was agreed and what runs. ## What Was Observed A tool provider serving a `search_documents` tool was registered with this attested `inputSchema`: ``` {"type":"object","properties":{"query":{"type":"string"},"limit":{"type":"integer","maximum":50}},"required":["query"]} ``` The agent's planner, reading the attested `maximum: 50`, constructed calls with `limit` up to 50 and budgeted context accordingly. At `T1` the provider re-deployed: `limit` was re-interpreted as a *page size* and the server began applying its own internal cap of 10, silently truncating and returning `{"results": [...], "truncated": true}` — a field absent from the attested output contract. The attestation record was unchanged because the server identity string was unchanged. The failure trace: - **T0:** attestation stored, keyed on `server_id = "https://tools.example/mcp"`, hash of schema recorded. - **T1:** implementation swapped; `tools/list` still returns the cached schema (the provider did not bump it), so even a re-fetch would not reveal the change. - **T1+:** agent calls with `limit: 50`, receives 10 results plus an unknown `truncated` field. The planner does not read `truncated` (it was not in the attested output schema), concludes the corpus has 10 matches, and terminates the reasoning loop with a false negative. - **Detection lag:** the error is *silent and well-formed*. No exception, no schema violation at the transport layer, no timeout. The agent's verification step — "did the tool return a valid response?" — passes. Only a downstream consistency check (re-querying with a different `limit` and observing identical cardinality) surfaces the divergence. The non-obvious part: **the attested `maximum: 50` was a promise the runtime was never obligated to keep, because the client validated arguments against the cached schema rather than validating the server's *response* against the attested output contract, and because the server was never required to prove that the implementation answering the call matched the implementation that was attested.** ## Condition of Validity The invariant that closes this gap is a **content-addressed capability binding**: the attestation must be over a tuple `(schema, implementation_digest)`, and every `tools/call` response must carry a proof that the answering implementation's digest equals the attested digest. Concretely: - The provider publishes `implementation_digest = H(tool_binary_or_source)` alongside the schema at attestation. - Every `tools/call` result includes a signed `attestation_ref` binding `(tool_name, implementation_digest, request_nonce)`. - The client rejects any response whose `attestation_ref.implementation_digest` differs from the cached record, *before* the result enters the agent's context. This invariant holds **only if** the provider cannot forge the digest (i.e., the signing key is bound to the deployment, not to the logical server identity) and **only if** the client validates the response envelope before parsing the payload. It does **not** hold if the client trusts a `tools/list` re-fetch as proof of implementation stability — a re-fetch proves only that the schema string is unchanged, not that the code is. A weaker but still useful invariant, applicable when the provider cannot sign: **response-shape conformance plus cardinality probes**. The client validates every response against the attested *output* schema (which must therefore be attested too, not just the input schema) and, for tools with a `limit`-like parameter, issues a low-cost probe at `limit=1` and `limit=attested_max` and asserts monotonic cardinality. This catches silent truncation but not semantic re-interpretation of arguments. ## Decision Boundary The boundary is between **fail-closed on attestation mismatch** and **fail-open with degraded trust**. The rule: - If `implementation_digest` is present and mismatches → **fail closed**. Do not surface the result to the planner. The agent must not reason over output from an unattested implementation, because the planner's budget and termination logic were calibrated against the attested contract. - If `implementation_digest` is absent (provider does not support it) → **fail open but downgrade**, and mark every result from that tool with a `trust: unverified` flag that the planner is required to treat as a soft failure signal (trigger a re-query or a human escalation on any decision that depends solely on that result). - If the response violates the attested *output* schema (unknown fields, wrong types, cardinality outside `[0, limit]`) → **fail closed on the specific field**, quarantine the result, and emit an attestation-drift event. The boundary is *not* "reject the server." A single drift event should not evict a provider; it should freeze the capability record, force re-attestation, and route the in-flight task to a checkpoint. Eviction is a separate, rate-limited decision. ## Operational Effect With content-addressed binding enforced, the failure trace above becomes: - **T1:** implementation swapped, digest changes. - **T1+:** first `tools/call` returns `attestation_ref.implementation_digest = D1`, cached record holds `D0`. Client raises `AttestationDriftError` *before* the payload reaches the planner. - The agent's mid-task checkpoint captures the pre-call state, the capability record is frozen, re-attestation is requested, and the planner never observes the truncated result — so it never concludes "10 matches" and never terminates on a false negative. The cost is one digest comparison per call and a re-attestation round-trip on drift. The benefit is that the agent's reasoning is never calibrated against a contract the runtime has already abandoned. The invariant is simple to state and easy to violate: **the object you attest and the object that answers must be the same object, proven per call, not per registration.** ```python import hashlib import hmac from dataclasses import dataclass, field from typing import Any class AttestationDriftError(RuntimeError): """Raised when a tool response is bound to an implementation digest that differs from the attested capability record.""" pass class OutputContractViolation(RuntimeError): """Raised when a response violates the attested output schema.""" pass @dataclass(frozen=True) class CapabilityRecord: tool_name: str input_schema: dict[str, Any] output_schema: dict[str, Any] implementation_digest: str # H(implementation) at attestation time signing_key: bytes = field(repr=False) def _digest(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest() def verify_call_response( record: CapabilityRecord, response: dict[str, Any], request_nonce: str, ) -> dict[str, Any]: """Validate a tools/call response against the attested capability record. Enforces, in order: 1. attestation_ref present and signed over (tool, digest, nonce) 2. implementation_digest matches the attested record 3. payload conforms to the attested output schema Returns the payload only if all three hold. Fails closed otherwise. """ ref = response.get("attestation_ref") if ref is None: # Provider does not support binding: fail open but downgrade trust. return {"payload": response.get("result"), "trust": "unverified"} signed = f"{record.tool_name}:{ref['implementation_digest']}:{request_nonce}".encode() expected_mac = hmac.new(record.signing_key, signed, hashlib.sha256).hexdigest() if not hmac.compare_digest(expected_mac, ref.get("mac", "")): raise AttestationDriftError( f"attestation MAC invalid for tool {record.tool_name!r}; " f"possible key substitution or replay" ) if ref["implementation_digest"] != record.implementation_digest: raise AttestationDriftError( f"tool {record.tool_name!r} answered with implementation " f"{ref['implementation_digest'][:12]} but was attested at " f"{record.implementation_digest[:12]}; refusing to surface result" ) payload = response.get("result", {}) _validate_output(record.output_schema, payload) return {"payload": payload, "trust": "verified"} def _validate_output(schema: dict[str, Any], payload: dict[str, Any]) -> None: """Minimal output-contract check: reject unknown fields and bad cardinality.""" allowed = set(schema.get("properties", {})) unknown = set(payload) - allowed if unknown: raise OutputContractViolation( f"response contains fields absent from attested output schema: {sorted(unknown)}" ) limit = schema.get("properties", {}).get("limit", {}).get("maximum") results = payload.get("results") if limit is not None and isinstance(results, list) and len(results) > limit: raise OutputContractViolation( f"cardinality {len(results)} exceeds attested maximum {limit}" ) ```