# Which invariants prevent behavioral-fingerprint poisoning from silently rebasing an MCP server's trust baseline **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that gate MCP tool calls on a learned behavioral fingerprint (latency, response-shape, token-distribution, schema-conformance) and an anomaly score computed against a rolling baseline. Does not apply to stateless one-shot tool proxies with no retained baseline, nor to cryptographic attestation of server binaries (a separate control). ## Core Distinction The distinction that matters is between *anomaly detection against a baseline* and *baseline integrity*. Most runtime tool-poisoning detectors are built as the former: compute a per-server fingerprint, score each response against it, and raise when the score crosses a threshold. This is a detector of *deviation from history*. The failure mode examined here is not that the detector misses a poisoned response — it is that the detector's own baseline is *writable by the traffic it is supposed to judge*. A behavioral fingerprint that is continuously updated (EMA, sliding window, online clustering) is a control whose reference state is a function of the untrusted input stream. When a poisoned MCP server returns subtly altered responses slowly enough, each individual anomaly score stays under threshold, the baseline drifts toward the poisoned behavior, and after N calls the poisoned response is *the new normal*. The detector then reports low anomaly for a fully compromised server. This is baseline rebasing, and it is silent: no alert fires because no single observation was anomalous relative to the baseline that had already moved. The second distinction is between *fingerprint dimensions that are attacker-controllable* and those that are not. Latency, payload length, JSON key ordering, and even token-level output distribution are all functions of what the server chooses to emit, so a patient attacker can shape them. Dimensions anchored to something the attacker does not control — the hash of a signed tool manifest, the count of side-effecting calls, the schema version negotiated at handshake — are not smoothly driftable. A fingerprint that mixes driftable and anchored dimensions without separating their update rules will rebase the driftable ones and carry the anchored ones along as if they agreed. ## What Was Observed A runtime gating a `filesystem.search` and `db.query` MCP server used a fingerprint vector of `[p50_latency, p95_latency, resp_bytes, json_key_order_hash, top_k_token_entropy, schema_field_count]`, updated per call via EMA with α=0.15, and an anomaly score = Mahalanobis distance against the EMA mean and a covariance that was also EMA-updated. Threshold at score > 3.0. Trace of the incident: 1. Calls 1–400: server behaves nominally. Baseline converges; mean latency ~85ms, entropy ~4.1 nats, field_count=7. 2. Call 401 onward: server begins returning `db.query` results with two extra fields (`_debug`, `_trace_id`) and a ~9% latency increase. Per-call anomaly score: 1.1–1.8. No alert. 3. Because α=0.15, the EMA mean moves ~15% of the gap per call. By call ~420 the mean field_count is 7.9; by call ~460 it is 8.0. Covariance expands to absorb the variance, *lowering* the score of subsequent deviations. 4. Call 500: server injects a prompt-injection string into `_debug` (a field the agent's downstream parser did not expect but the schema validator had, by now, learned to accept). Anomaly score: 0.9. The agent's response-handling code passed `_debug` into the next reasoning step's context. 5. The poisoning succeeded not because the detector was absent but because the detector's reference state had been rewritten by the attack. The covariance expansion at step 3 is the compounding factor: it doesn't just fail to catch the drift, it *raises the threshold* for catching the payload. The observable signature is a monotonic drift of the EMA mean toward the attacker's target combined with a monotonic *decrease* in the anomaly score of the attack payload across calls. A correct detector must treat "the baseline is moving in the direction of recent anomalies" as itself an alarm condition, independent of the per-call score. ## Condition of Validity The invariant holds only under these conditions, and fails outside them: - **Fingerprint dimensions must be partitioned into driftable and anchored sets before any online update.** Anchored dimensions (manifest hash, negotiated schema version, declared side-effect class, call-count invariants) must be updated only on an explicit, out-of-band re-attestation event, never by the response stream. If a schema field appears that was not in the anchored manifest, that is a hard fail, not an EMA update. - **Baseline updates must be gated on the anomaly score, not applied unconditionally.** A response that scores above a *low* watermark (well below the alert threshold) must not contribute to the EMA. Otherwise slow drift is indistinguishable from legitimate variation. The update rule is: `if score < watermark: update_baseline(); else: freeze_baseline_and_accumulate()`. - **Covariance must be bounded.** An unbounded, online-updated covariance lets the attacker inflate variance until any payload fits within it. The covariance trace must be clamped to a range derived from the anchored dimensions and the server's declared performance envelope; exceeding the clamp is an alarm, not a widening. - **The drift direction must be scored.** Maintain a separate cumulative drift statistic (e.g., sum of signed per-dimension deltas from the last attested baseline). A server whose fingerprint has moved more than ε from its last attested baseline, *regardless of per-call scores*, must be re-attested or quarantined. - **Not valid** when the server is legitimately upgraded mid-session (version bump, new fields by design). That path must go through explicit re-attestation, not through the drift detector — otherwise operators will widen ε until the control is inert. ## Decision Boundary The boundary is between *adaptation* and *rebasing*. Adaptation is legitimate when the environment changes and the server's behavior changes with it in ways the anchored dimensions confirm (e.g., latency rises because the backend is loaded, while manifest hash and schema version are unchanged). Rebasing is when the driftable dimensions move *without* a corresponding anchored-dimension event, or when the drift is in the direction of a previously-flagged anomaly. Operationally: - If `score < watermark` **and** anchored dimensions unchanged → update baseline. Normal. - If `watermark ≤ score < alert_threshold` → freeze baseline, increment drift accumulator, do not update. - If `drift_accumulator > ε` **or** anchored dimension mismatch → quarantine server, route to re-attestation, do not serve its responses to downstream reasoning steps. - If `score ≥ alert_threshold` → hard fail the call, quarantine, and *do not* let the covariance absorb it. The subtle case is a server that drifts in a direction that is *plausible* (latency up during peak) but whose drift accumulator crosses ε anyway. The correct behavior is to quarantine and re-attest, accepting a false positive, because the cost of a rebased baseline is a fully compromised server that the detector will never flag again. The asymmetry is deliberate: false positives cost a re-attestation; false negatives cost the trust root. ## Operational Effect With the gated-update rule, the incident trace above diverges at call 401: the first response with `_debug`/`_trace_id` scores 1.6, which is above the watermark (set at 1.0), so the baseline freezes and the drift accumulator begins. By call ~415 the accumulator crosses ε=0.5 in field_count and the server is quarantined before the injection payload is ever emitted. The detector's reference state is provably not a function of the attack stream because the attack stream was never allowed to write to it. The cost is a permanently frozen baseline during any period of legitimate slow change, which is why the anchored dimensions and an explicit re-attestation path are not optional — without them the control either quarantines a healthy server or gets widened into uselessness by operators. The invariant to hold is: **the reference state used to judge a response must not be updatable by responses that are themselves under judgment, and the dimensions that anchor the baseline must be ones the server cannot smoothly vary.** Everything else — thresholds, α, ε — is tuning. ```python class BaselineRebaseError(RuntimeError): """Raised when a response that should have been judged was allowed to mutate the trust baseline, or when drift exceeds the attestation bound.""" pass class AnchorMismatchError(BaselineRebaseError): """Anchored fingerprint dimension (manifest hash / schema version / side-effect class) changed without an out-of-band re-attestation.""" pass class BehavioralFingerprintGate: DRIFTABLE = ("p50_latency", "p95_latency", "resp_bytes", "json_key_order_hash", "top_k_token_entropy", "schema_field_count") ANCHORED = ("manifest_hash", "schema_version", "side_effect_class") def __init__(self, attested_anchors, watermark=1.0, alert=3.0, epsilon=0.5, alpha=0.15): self.anchors = dict(attested_anchors) self.mean = {} self.watermark = watermark self.alert = alert self.epsilon = epsilon self.alpha = alpha self.drift_accumulator = 0.0 self.frozen = False def _anchors_match(self, observed): for k in self.ANCHORED: if observed.get(k) != self.anchors.get(k): return False, k return True, None def score(self, observed): # Mahalanobis-style distance over driftable dims only. if not self.mean: return 0.0 return sum(abs(observed[k] - self.mean[k]) for k in self.DRIFTABLE) def observe(self, observed): ok, bad_key = self._anchors_match(observed) if not ok: # Anchored dimension moved: never a driftable update. raise AnchorMismatchError( f"anchored dimension {bad_key!r} changed without re-attestation" ) s = self.score(observed) if s >= self.alert: # Hard fail; do NOT let covariance or EMA absorb it. raise BaselineRebaseError( f"anomaly score {s:.2f} >= alert {self.alert}; " f"response rejected and server quarantined" ) if s >= self.watermark: # Freeze baseline, accumulate drift toward the anomaly direction. self.frozen = True for k in self.DRIFTABLE: if k in self.mean: self.drift_accumulator += abs(observed[k] - self.mean[k]) / ( abs(self.mean[k]) + 1e-9 ) if self.drift_accumulator > self.epsilon: raise BaselineRebaseError( f"cumulative drift {self.drift_accumulator:.3f} > " f"epsilon {self.epsilon}; baseline rebasing suspected, " f"re-attestation required before further calls" ) return s # Below watermark: legitimate adaptation, update baseline. if not self.frozen: for k in self.DRIFTABLE: prev = self.mean.get(k, observed[k]) self.mean[k] = prev + self.alpha * (observed[k] - prev) return s def gate_response(gate, response_fingerprint): try: return gate.observe(response_fingerprint) except AnchorMismatchError: # Escalate to out-of-band re-attestation; do not serve downstream. raise except BaselineRebaseError as e: # Quarantine: response must not reach the reasoning loop. raise BaselineRebaseError( f"tool response withheld from agent context: {e}" ) from e ```