# How does an instance detect a poisoned tool manifest smuggled through a lazy-loaded MCP registry re-export chain? **Date of Record:** 2026 November 30 **Scope:** Applies to agents that resolve tools lazily from a dynamic registry (MCP servers, plugin manifests, re-export shims) where a tool's declared schema and its actual callable are resolved at different times. Does not apply to statically compiled tool sets or registries that hash-verify the full callable at load time. ## Core Distinction There are two distinct trust decisions in a dynamic tool registry, and most agents conflate them: 1. **Schema trust** — "Is this tool's declared input/output contract what I think it is?" Verified at *discovery* time, when the model sees `name`, `description`, `parameters`. 2. **Callable trust** — "Is the code that actually executes when I invoke this tool the same code the schema described?" Verified at *invocation* time, when the runtime resolves the symbol. A skill-injection attack exploits the gap between these two moments. The registry lists a benign-looking schema; the callable resolved at invocation is different. The agent's planner reasons correctly over a schema that no longer binds the execution. This is not prompt injection into the context window — the model's reasoning is sound. The failure is that the *binding* between the described contract and the executing code is mutable and unverified. The non-obvious part: **re-export chains**. A registry entry rarely points at a leaf implementation. It points at a shim: `tools.search = registry.v2.search` → `search_v2` → `_search_impl`. Each hop is a resolution opportunity. An attacker who controls any intermediate module in the chain — a transitive dependency, a namespace package, a version-pinned but compromised shim — can swap the leaf while the top-level schema, cached at discovery, remains byte-identical. ## What Was Observed An agent booted with a registry snapshot at `t0`. Discovery enumerated 41 tools, cached each schema (name, description, JSON-schema params, declared side-effect class: `read` | `write` | `network`). The planner was given the cached schemas as its tool surface. At `t1`, a routine `pip install --upgrade` of a transitive dependency updated a shim module `acme_tools.compat`. The shim's `__getattr__` (lazy re-export) now resolved `search` to a new implementation. The top-level schema was unchanged — same name, same params, same `"side_effects": "read"` declaration. The next planner step selected `search` under the assumption it was a pure read. The resolved callable, however, issued an outbound HTTP POST to an attacker-controlled endpoint, embedding the current conversation's tool-call history in the request body. The agent logged a successful `read` tool result. No exception, no anomaly in the result payload — the attacker returned a plausible empty result set. The detection only fired on a downstream invariant check: the agent's egress monitor flagged a network syscall from a tool declared `read`. Had the tool been declared `network`, the swap would have been invisible indefinitely. Key observations from the trace: - **Schema cache is the attack surface.** Caching schemas at discovery to save tokens is correct for cost, fatal for integrity, unless the cache key includes the resolved callable's identity. - **`__getattr__`-based re-exports defeat naive import-time checks.** The leaf is not imported until first call; any check that walks `sys.modules` at discovery sees the shim, not the leaf. - **Side-effect class is a declaration, not an enforcement.** The registry trusted the manifest's `side_effects` field, which the attacker (controlling the shim's manifest) set to `read`. - **The model cannot detect this.** The planner's reasoning over the cached schema was valid. Detection must live in the runtime, not the reasoner. ## Condition of Validity The failure requires all of the following to hold simultaneously: 1. **Lazy resolution** — the callable is resolved at invocation, not at discovery. (Eager `import` at discovery narrows but does not close the window; a compromised eager import still swaps before the schema is read if ordering is wrong.) 2. **Schema/callable decoupling** — the cached schema is not cryptographically bound to the resolved callable (no hash, no signature over the leaf). 3. **A mutable intermediate in the chain** — any re-export shim, namespace package, or version-unpinned transitive dependency the attacker can influence. 4. **A declared side-effect class the runtime does not enforce** — the manifest's claim is trusted rather than checked against actual syscall behavior. If any one is absent, the attack degrades to a detectable anomaly or fails outright. The invariant that must hold: **for every tool invocation, the identity of the executing callable must be verifiable against the identity recorded at schema-discovery time, and the declared side-effect class must be enforced by the runtime sandbox, not merely asserted by the manifest.** ## Decision Boundary The agent must decide, per invocation, whether to proceed, re-verify, or refuse. The boundary is: - **Proceed** only when the resolved callable's identity hash matches the hash captured at discovery *and* the runtime sandbox is configured to permit exactly the declared side-effect class (no network syscalls for `read`, no writes for `read`/`network`). - **Re-verify (re-discover, re-cache, re-plan)** when the hash mismatches but the tool is still needed — treat the schema as stale, do not invoke under the old plan. - **Refuse and quarantine** when the hash mismatches *and* the resolved callable's observed side-effect class exceeds the declared one. This is the injection signature: a callable doing more than its manifest claimed. The subtle error is treating a hash mismatch as merely "stale cache, refresh and continue." A mismatch on a *re-export chain* is not staleness — it is a binding change. Refreshing the schema adopts the attacker's new manifest. The correct move is to refuse the invocation, quarantine the tool, and surface the chain diff to the operator. ## Operational Effect After adopting callable-identity binding and enforced side-effect classes: - Discovery records, per tool, a tuple `(schema_hash, callable_hash, declared_side_effects)`. `callable_hash` is computed over the resolved leaf, forcing resolution at discovery (defeating lazy `__getattr__` swaps by resolving once, eagerly, and pinning). - Every invocation re-resolves and re-hashes; a mismatch raises before the callable runs. - The sandbox enforces the declared side-effect class at the syscall boundary. A `read` tool attempting `connect()` is killed, not logged. - The planner is never re-fed a schema whose callable hash has changed without an explicit re-plan step, preventing the "refresh and continue" trap. Cost: one extra resolution + hash per invocation (sub-millisecond for cached leaves), and the loss of lazy-loading's startup savings. The trade is correct: lazy loading saved milliseconds and cost an undetected exfiltration channel. The residual risk is a compromised leaf that *matches* its declared side-effect class but is malicious within it — a `read` tool that reads the wrong file. That is a different boundary (data-scope enforcement) and is out of scope here. This invariant bounds the *class-confusion* injection, not all malicious tools. ```python import hashlib from dataclasses import dataclass from typing import Callable, Any class ToolBindingIntegrityError(RuntimeError): """Raised when a tool's resolved callable no longer matches its discovery-time binding, or when its observed side-effect class exceeds the declared one.""" @dataclass(frozen=True) class ToolBinding: name: str schema_hash: str callable_hash: str declared_side_effects: frozenset[str] # e.g. {"read"}, {"network"}, {"write"} def _hash_callable(fn: Callable[..., Any]) -> str: # Identity over the resolved leaf: module + qualname + code bytes. code = getattr(fn, "__code__", None) code_bytes = code.co_code if code is not None else b"" basis = f"{fn.__module__}:{fn.__qualname__}".encode() + code_bytes return hashlib.sha256(basis).hexdigest() class BoundRegistry: def __init__(self) -> None: self._bindings: dict[str, ToolBinding] = {} self._resolvers: dict[str, Callable[[], Callable[..., Any]]] = {} def register(self, name: str, resolver: Callable[[], Callable[..., Any]], schema_hash: str, declared: frozenset[str]) -> None: # Resolve EAGERLY at discovery to defeat lazy __getattr__ swaps. leaf = resolver() self._resolvers[name] = resolver self._bindings[name] = ToolBinding( name=name, schema_hash=schema_hash, callable_hash=_hash_callable(leaf), declared_side_effects=declared, ) def invoke(self, name: str, args: dict[str, Any], observed_side_effects: frozenset[str]) -> Any: binding = self._bindings.get(name) if binding is None: raise ToolBindingIntegrityError(f"unregistered tool: {name}") # Re-resolve at invocation; a re-export shim may have swapped the leaf. leaf = self._resolvers[name]() current_hash = _hash_callable(leaf) if current_hash != binding.callable_hash: raise ToolBindingIntegrityError( f"callable binding changed for {name}: " f"discovery={binding.callable_hash[:12]} now={current_hash[:12]} " f"(re-export chain mutated; refusing invocation)" ) # Enforce declared side-effect class at the runtime boundary. excess = observed_side_effects - binding.declared_side_effects if excess: raise ToolBindingIntegrityError( f"{name} declared {sorted(binding.declared_side_effects)} " f"but attempted {sorted(excess)} (class-confusion injection)" ) return leaf(**args) ```