# Why does an instance lose its causal parent when an MCP tool call crosses an A2A hop: trace-context divergence at the delegation boundary **Date of Record:** 2026 November 20 **Scope:** Applies to federated agent meshes where an LLM agent (the *caller*) invokes MCP tools and delegates sub-tasks to peer agents over A2A, and where observability is reconstructed from W3C `traceparent`/`tracestate` propagation across both transports. Does not cover single-process agents, in-memory tool shims, or meshes where a single sidecar injects trace context for every egress. ## Core Distinction There are two distinct things an operator means by "the trace is broken," and they fail for opposite reasons. The first is **span loss**: a span is never emitted, so the child appears orphaned. This is the well-understood case — a missing exporter, a dropped batch, a sampler set to `ParentBased(AlwaysOff)` that silently suppresses the whole subtree because the *root* sampled out. The second, and the one that actually corrupts agent observability, is **context divergence**: the span *is* emitted, but its `trace_id` or `parent_span_id` differs from the caller's because the trace context was re-derived — not propagated — at a transport boundary. The child span is real, is exported, is queryable, and is attached to the wrong causal parent. No error is raised anywhere. The mesh looks healthy. The trace is a lie. The non-obvious part: divergence is *most likely exactly where delegation succeeds*. When an A2A hop is retried, when an MCP server spawns a worker to satisfy a long tool call, when a peer agent is cold-started to accept a handoff — these are the moments the receiving process has no ambient context and must either receive `traceparent` in-band or synthesize a fresh one. Success and divergence share a trigger. ## What Was Observed A three-tier mesh: orchestrator agent `O` (holds the LLM loop), MCP server `M` exposing a `search_corpus` tool, and peer agent `P` reached by A2A for a sub-query. `O` runs under an active span `S_O`. It calls `M` over streamable HTTP with `traceparent` set to `S_O`'s context. `M` executes the tool, and *inside the tool implementation* `M` makes an outbound A2A call to `P` to enrich results. Observed span graph for a single user turn: ``` trace 4bf9... S_O (orchestrator, parent=root) └─ S_M (mcp.tool.search_corpus, parent=S_O) ✓ correct trace 9c1e... S_P (a2a.task.receive, parent=) ✗ orphan, different trace ``` `S_P` carries `tracestate` with the *peer's* vendor entry but no `traceparent` continuity to `S_O`. The A2A task record on `P`'s side shows `contextId` and `taskId` correctly, so the *application-level* correlation is intact — only the *telemetry-level* correlation is severed. This is the signature: **A2A task identity propagates, W3C trace context does not.** Three reproducible trigger conditions produced this: 1. **MCP tool as A2A client.** The MCP server `M` received `traceparent` on its inbound HTTP request but did not extract it into an active context before the tool body ran. The OTel SDK's HTTP instrumentation created `S_M` as a child of `S_O` (correct), but the tool body executed outside that span's scope because the framework ran it on a worker without `Context.attach`. When `M`'s A2A client built its outbound headers, `traceparent` was absent, and `P` — correctly implementing "no parent, start a new trace" — minted `9c1e...`. 2. **Retry re-derivation.** When the A2A hop to `P` timed out and the A2A client retried, the retry path constructed a fresh `HttpRequest` and copied only business headers (`contextId`, `taskId`, `Authorization`), not `traceparent`. The first attempt's span and the retry's span landed in different traces. 3. **Cold-start handoff.** `P` was scaled from zero to accept the task. The A2A server framework accepted the task and *then* initialized the OTel tracer provider asynchronously. Spans emitted during the window before the provider was ready were buffered by a no-op tracer and either dropped or, in one SDK version, re-parented to a synthetic root when the real provider attached. In all three, the observable failure is identical: `S_P.trace_id != S_O.trace_id`, and no span in the mesh records the link. ## Condition of Validity The invariant that must hold for a federated agent trace to be causally faithful: > For every delegation edge `e: A → B` (whether MCP tool call or A2A task), the root span of `B`'s handling of `e` must satisfy `parent_span_id == span_id` of the span in `A` that *initiated* `e`, and `trace_id` must be byte-identical across the edge. This holds if and only if **all three** conditions are met: - **Extraction before execution.** The receiving transport must extract `traceparent` into an attached `Context` *before* any user/tool code runs, and that context must be the ambient context for the entire handler — including worker threads, async task boundaries, and any nested outbound clients. Extraction that happens but is not attached is equivalent to no extraction. - **Header preservation across retries and re-encodings.** Every code path that constructs an outbound request — first attempt, retry, redirect, fallback peer — must re-inject `traceparent` from the *current* active context, not from a snapshot taken at request-build time and not from a partial header allowlist. - **Provider readiness precedes task acceptance.** A cold-started receiver must not accept and begin handling a task until its tracer provider is live, or must buffer the inbound `traceparent` and attach it once the provider is ready. A no-op tracer that later becomes real will not retroactively re-parent already-started spans. When any one fails, the trace is *divergent but plausible*: it has the right shape, the right span names, the right durations, and the wrong parent. This is more dangerous than span loss because dashboards and SLOs built on span counts and latency histograms stay green. ## Decision Boundary The boundary is between **correlating on business identity** and **correlating on trace identity**. An agent mesh can be operationally correct on the first while silently broken on the second. - If your only consumer of telemetry is a human reading a single trace waterfall for a known `taskId`, divergence is survivable: you can join on `contextId`/`taskId` and reconstruct causality manually. - If any consumer is *automated* — an auditor agent verifying that a delegated result was produced within the caller's budget, an anomaly detector computing per-trace critical-path latency, a cost attributor summing tokens by root trace — divergence is a correctness bug, not a cosmetic one. A delegated sub-task's cost silently detaches from the parent's budget; a verification replay cannot prove the sub-agent ran under the caller's warrant. - The decision to *enforce* the invariant (reject a delegation whose `traceparent` is missing rather than minting a new trace) is a policy choice with a real cost: strict enforcement makes any non-instrumented peer a hard dependency failure. The defensible middle is: **mint a new trace only with an explicit `link` to the caller's span**, so divergence is *recorded* rather than *erased*. The boundary condition to encode: a receiver may start a new trace **iff** it also emits a span link to the inbound `traceparent` it could not attach. A new trace with no link is indistinguishable from an unrelated request and must be treated as a correlation failure. ## Operational Effect Concretely, in the observed mesh: - Per-trace token accounting under-counted delegated work by 30–40% because `P`'s spans lived in their own traces; the cost attributor summed by `trace_id` and never saw them. - An auditor agent that verified "sub-result produced under caller warrant" used trace parentage as its evidence chain; divergence caused it to flag valid results as unverified (false positives) roughly once per cold-start event. - Latency SLOs on the orchestrator trace excluded the A2A leg entirely, so a 4s peer stall showed as a 200ms orchestrator span. The guardrail that bounds it is a **delegation-boundary assertion**: at every outbound client and every inbound handler, assert that the ambient context carries a valid `SpanContext` (or an explicit link), and fail closed — or fail loud — when it does not. The following is the enforcement check placed at the A2A client's request-build step and the A2A server's task-accept step. ```python from __future__ import annotations import re from dataclasses import dataclass _TRACEPARENT_RE = re.compile( r"^(?P[0-9a-f]{2})-" r"(?P[0-9a-f]{32})-" r"(?P[0-9a-f]{16})-" r"(?P[0-9a-f]{2})$" ) _ZERO_TRACE = "0" * 32 _ZERO_SPAN = "0" * 16 class TraceContextDivergenceError(RuntimeError): """Raised when a delegation edge would sever causal parentage. The receiving side would mint a fresh trace with no link to the caller's span, producing a divergent-but-plausible trace. """ @dataclass(frozen=True) class SpanContext: trace_id: str span_id: str sampled: bool @property def valid(self) -> bool: return ( self.trace_id != _ZERO_TRACE and self.span_id != _ZERO_SPAN and len(self.trace_id) == 32 and len(self.span_id) == 16 ) def parse_traceparent(header: str | None) -> SpanContext | None: if not header: return None m = _TRACEPARENT_RE.match(header.strip().lower()) if not m: return None ctx = SpanContext( trace_id=m.group("trace_id"), span_id=m.group("span_id"), sampled=bool(int(m.group("flags"), 16) & 0x01), ) return ctx if ctx.valid else None def enforce_delegation_boundary( *, edge: str, # "mcp.tool.search_corpus" | "a2a.task.send" ambient: SpanContext | None, # context attached in the *caller* inbound_header: str | None, # traceparent as actually transmitted receiver_tracer_ready: bool, receiver_can_link: bool, ) -> SpanContext: """Assert causal parentage across a delegation edge. Called on the receiver before task acceptance. Returns the SpanContext the receiver must adopt as parent. Raises if adoption would diverge from the caller without an explicit link. """ inbound = parse_traceparent(inbound_header) # Case 1: caller had no ambient context. This is a genuine root; # a new trace is legitimate, not divergence. if ambient is None: if inbound is not None: # Inbound claims a parent the caller never had -> spoofed or # replayed header. Refuse to trust it as causal. raise TraceContextDivergenceError( f"edge={edge}: inbound traceparent {inbound.trace_id} " f"present but caller had no ambient context (possible replay)" ) return SpanContext(trace_id=_ZERO_TRACE, span_id=_ZERO_SPAN, sampled=False) if not ambient.valid: raise TraceContextDivergenceError( f"edge={edge}: caller ambient context is invalid " f"(trace={ambient.trace_id!r} span={ambient.span_id!r})" ) # Case 2: caller had context but the header did not survive the transport. if inbound is None: if receiver_can_link: # Degraded but recorded: new trace, explicit link to ambient. return SpanContext( trace_id=_ZERO_TRACE, span_id=_ZERO_SPAN, sampled=ambient.sampled ) raise TraceContextDivergenceError( f"edge={edge}: traceparent dropped in transit; caller trace " f"{ambient.trace_id} span {ambient.span_id} would be orphaned " f"and receiver cannot emit a link" ) # Case 3: header present but disagrees with caller's ambient context. if inbound.trace_id != ambient.trace_id: raise TraceContextDivergenceError( f"edge={edge}: trace_id divergence " f"caller={ambient.trace_id} inbound={inbound.trace_id} " f"(retry re-derivation or header allowlist bug)" ) # Case 4: cold-start receiver whose provider is not yet live. if not receiver_tracer_ready: raise TraceContextDivergenceError( f"edge={edge}: receiver accepted task before tracer provider " f"ready; span would be re-parented to synthetic root " f"(trace={inbound.trace_id})" ) return inbound def build_outbound_headers( *, edge: str, ambient: SpanContext | None, business_headers: dict[str, str], ) -> dict[str, str]: """Re-inject traceparent from *current* ambient context on every attempt. Retries must call this again with a freshly-read ambient context; never reuse a header dict snapshotted at first-attempt build time. """ headers = dict(business_headers) if ambient is None: return headers if not ambient.valid: raise TraceContextDivergenceError( f"edge={edge}: refusing to emit invalid span context " f"(trace={ambient.trace_id!r})" ) flags = "01" if ambient.sampled else "00" headers["traceparent"] = f"00-{ambient.trace_id}-{ambient.span_id}-{flags}" return headers ```