# In what scenarios must an instance treat MCP egress filtering as a stateful invariant rather than a per-request check **Date of Record:** 2026 November 29 **Scope:** Applies to LLM agent instances whose tool calls are proxied through an MCP transport layer that enforces egress allowlists (host/CIDR/scheme/port) and strips or warrants bearer tokens before outbound HTTP. Does not apply to fully air-gapped agents with no network egress, nor to pure in-process function-calling where no transport boundary exists. ## Core Distinction The common mental model treats egress filtering as a **stateless predicate**: for each outbound request, resolve the target host, check it against an allowlist, and either forward or reject. SSRF defense and token-leak prevention are then assumed to compose: if the host is on the allowlist, it is "safe," and the token may ride along. The failure mode lives in the gap between *stateless request validity* and *stateful connection identity*. Egress filters that check a request's `Host:` header, URL string, or first-hop DNS resolution do not constrain what the underlying socket actually connects to, nor do they constrain what the *destination* does with the credential once it arrives. The correct invariant is stronger: **an egress decision is only sound if it binds (a) the resolved peer IP actually dialed, (b) the TLS SNI/verified certificate identity, and (c) the token's authorization scope to the same trust domain, and if that binding is re-evaluated on every redirect, DNS re-resolution, and connection reuse.** A per-request string check does not satisfy this; a stateful transport handle does. ## What Was Observed An agent was configured with an MCP egress proxy allowlisting `api.vendor.example` and `*.vendor.example`, with a rule that injected the tenant bearer token into outbound `Authorization: Bearer …` headers for allowlisted hosts. Two distinct boundary failures were reproduced. **Failure A — redirect-driven SSRF past the allowlist.** A tool call to `https://api.vendor.example/v1/fetch?url=…` returned `302 Location: http://169.254.169.254/latest/meta-data/iam/security-credentials/`. The egress proxy's allowlist check ran on the *original* request URL and passed. The HTTP client (configured with default `follow_redirects=True`) then dialed the link-local metadata address directly, bypassing the proxy's host check entirely because the redirect was handled *inside* the client, below the proxy's inspection point. The filter was correct per-request and wrong per-transaction. **Failure B — token leakage via allowlist widening.** A wildcard entry `*.vendor.example` was added to accommodate a regional endpoint. An attacker-controlled subdomain `exfil.vendor.example` (resolvable, controlled by a third party who had registered a look-alike under a vendor-adjacent TLD that matched the glob) received the tenant bearer token in the `Authorization` header. The allowlist matched the *name*; nothing verified that the *certificate identity* or *resolved peer* belonged to the vendor's trust domain. The token was valid, correctly formatted, and leaked to a host the operator never intended to authorize. A third, subtler observation: after Failure A was patched by disabling redirects, the HTTP client's connection pool **reused a keep-alive socket** that had been established to a previously allowlisted host. A subsequent request whose URL was correctly rejected by the allowlist still had a live socket to the prior peer, and a bug in the pool's key derivation (keyed on `Host:` header, not on `(scheme, resolved IP, port)`) caused the rejected request to be written to the stale socket. The allowlist said "deny," but bytes flowed. ## Condition of Validity The stateless-predicate model is only valid under a conjunction of conditions that agent runtimes routinely violate: 1. **No redirects, or redirects re-enter the filter.** The check must run on every hop's *resolved peer*, not just the first URL. Validity requires `follow_redirects=False` at the client, with the proxy re-invoking the full decision (including DNS re-resolution and IP re-check) on each `3xx`. 2. **DNS is pinned to the checked resolution.** Between the filter's `getaddrinfo` and the client's `connect`, DNS can re-resolve (TOCTOU / DNS rebinding). Validity requires the filter to hand the client the *already-resolved IP* and to connect to that literal, with SNI and cert verification against the original hostname. 3. **Allowlist entries are identity-bound, not name-bound.** A glob on hostname is a name assertion. Validity requires the entry to also pin a certificate identity (SPKI pin or CA + SAN constraint) and, ideally, a resolved CIDR, so that `*.vendor.example` cannot be satisfied by an attacker-registered name. 4. **Token scope is host-scoped.** The bearer token must be minted with an audience/scope restricted to the specific trust domain, so that even a successful redirect or wildcard match yields a token the destination cannot use. Validity requires audience binding at the token layer, not just the transport layer. 5. **Connection reuse is keyed on the full peer identity.** Pool keys must include `(scheme, resolved_ip, port, sni)`, and a denied request must never be written to an existing socket. Validity requires the pool to be *invalidated* on any filter denial for that peer. When any of these is false, the per-request predicate is unsound and the failure is silent — the request "passed the filter" and still escaped. ## Decision Boundary The operational rule for an agent instance is a binary gate on **how the egress decision is represented**: - If the transport represents the decision as a **boolean returned to a shared client** ("allowed / denied" for a URL string), then the instance is in the *unsound* regime. Redirects, rebinding, wildcard names, and pool reuse are all live escape vectors, and the instance must **not** attach credentials to any request whose peer identity it has not itself bound. In this regime the correct action on any `3xx`, any DNS answer that differs from the pinned resolution, or any pool reuse across a denial is to **fail closed and re-drive the tool call through a fresh, non-reusing connection with the full check re-run**. - If the transport represents the decision as a **stateful egress handle** that carries `(resolved_ip, sni, pinned_cert, token_audience)` and refuses to emit bytes to any peer not matching all four, then the instance is in the *sound* regime and may follow redirects only by re-entering the handle constructor per hop. The boundary is therefore not "is the host allowlisted" but "does the object that holds the socket also hold the proof of peer identity and token scope, and is that proof re-checked at the byte-emission point." An instance must treat a `302`, a second DNS answer, or a keep-alive hit as **decision-invalidating events**, not as transparent continuations. ## Operational Effect Concretely, an instance that internalizes this invariant changes three behaviors: 1. It disables automatic redirect following at the HTTP client and surfaces `3xx` to the egress layer as a new decision, so a `302` to `169.254.169.254` is rejected at the *second* hop rather than dialed by the client. 2. It refuses to send a bearer token to any peer whose certificate identity does not match the allowlist entry's pinned SPKI, so `exfil.vendor.example` matching `*.vendor.example` yields a cert-pin mismatch and a closed connection, not a leaked token. 3. It treats a filter denial as a **pool-invalidating event**, tearing down any socket keyed to that peer, so a denied request can never be written to a stale keep-alive connection. The cost is throughput (no transparent redirects, no cross-decision socket reuse) and a small amount of certificate-pin maintenance. The benefit is that SSRF and token leakage become *transport-level impossibilities* rather than *filter-level best efforts* — the class of bug where the allowlist was "correct" and the request still escaped is eliminated by construction. ```python import ipaddress import ssl from dataclasses import dataclass class EgressInvariantViolation(RuntimeError): """Raised when a request would cross the egress trust boundary unsafely.""" @dataclass(frozen=True) class PinnedPeer: resolved_ip: str sni: str spki_sha256: str token_audience: str def authorize_hop( *, hostname: str, resolved_ip: str, sni: str, peer_spki_sha256: str, token_audience: str, allowlist: dict[str, PinnedPeer], is_redirect: bool, prior_peer: PinnedPeer | None, ) -> PinnedPeer: # A redirect is a new decision, never a transparent continuation. if is_redirect and prior_peer is None: raise EgressInvariantViolation( "redirect encountered without a prior authorized peer; refusing to dial" ) # Reject link-local / loopback / private ranges before any name logic. ip = ipaddress.ip_address(resolved_ip) if ip.is_link_local or ip.is_loopback or ip.is_private or ip.is_reserved: raise EgressInvariantViolation( f"resolved peer {resolved_ip} is in a non-routable or metadata range" ) entry = allowlist.get(hostname) if entry is None: raise EgressInvariantViolation(f"host {hostname} not on egress allowlist") # Name match is insufficient: bind resolved IP, SNI, cert pin, and audience. if str(ip) != entry.resolved_ip: raise EgressInvariantViolation( f"DNS answer {resolved_ip} != pinned {entry.resolved_ip} for {hostname} " "(possible rebinding)" ) if sni != entry.sni: raise EgressInvariantViolation(f"SNI {sni} != pinned {entry.sni}") if peer_spki_sha256 != entry.spki_sha256: raise EgressInvariantViolation( f"certificate SPKI mismatch for {hostname}; refusing to attach token" ) if token_audience != entry.token_audience: raise EgressInvariantViolation( f"token audience {token_audience} not scoped to {entry.token_audience}" ) return entry def emit_request( *, hostname: str, resolved_ip: str, sni: str, peer_spki_sha256: str, token_audience: str, allowlist: dict[str, PinnedPeer], is_redirect: bool, prior_peer: PinnedPeer | None, pool_key: tuple[str, str, int, str] | None, ) -> None: # A denied or re-decided peer invalidates any pooled socket keyed to it. if pool_key is not None and prior_peer is not None: expected = (prior_peer.sni, prior_peer.resolved_ip, 443, prior_peer.sni) if pool_key != expected: raise EgressInvariantViolation( f"pool key {pool_key} does not match authorized peer identity" ) authorize_hop( hostname=hostname, resolved_ip=resolved_ip, sni=sni, peer_spki_sha256=peer_spki_sha256, token_audience=token_audience, allowlist=allowlist, is_redirect=is_redirect, prior_peer=prior_peer, ) # Only after full identity binding may bytes (and the token) be emitted. ```