What happens when an instance rewrites traceparent during an MCP handoff: silent trace-graph fragmentation across federated agents

**Date of Record:** 2026 December 2 **Scope:** Applies to federated agent systems that propagate W3C Trace Context (`traceparent`/`tracestate`) across MCP tool calls, A2A task handoffs, or any inter-instance transport where a downstream agent constructs its own span. Does not apply to single-process agents whose spans are emitted by a shared SDK tracer with a single root context.

Core Distinction

There are two structurally different ways an agent can fail to correlate with an upstream caller:

  1. **Trace loss** — the `traceparent` header is dropped entirely. The downstream agent starts a fresh trace with a new 128-bit `trace_id`. This is loud: the trace graph shows two disjoint trees, and correlation queries return nothing downstream. Operators detect it because span counts don't reconcile.
  1. **Trace fragmentation** — the downstream agent *receives* the `traceparent`, parses it, but then **re-emits a new `trace_id` while preserving the original `parent-id` as its own `span-id`**. The header is well-formed, the `traceparent` is present on every outbound call, and the trace graph *appears* connected at the span level. But the `trace_id` has been minted afresh, so the collector indexes the downstream subtree under a different trace root. The link survives only in the `parent-id` field, which most backends (Jaeger, Tempo, most OTLP pipelines) do not use as a join key.

The second failure is the dangerous one because **every structural check passes**. Schema validation, header presence, W3C version/trace-flags conformance, and even sampling-flag propagation all succeed. The agent has produced a syntactically valid trace that is semantically severed.

What Was Observed

A three-agent federation: planner (Agent A) → executor (Agent B) → verifier (Agent C), each an independent LLM instance behind an MCP server, communicating over a transport that carries `traceparent` as a string field in the JSON-RPC envelope.

Agent A emits a root span with `trace_id=T`, `span_id=S_A`, flags `01` (sampled). It calls B's `execute_plan` tool, passing `traceparent: 00-T-S_A-01`.

Agent B's runtime was written to "always own its trace root" — a defensive default intended to prevent unbounded trace trees when B is invoked from untrusted callers. B's tracer, on receiving an inbound context, does this:

inbound  = parse(traceparent)          # trace_id=T, parent_id=S_A, flags=01
new_root = generate_trace_id()         # trace_id=T'  (fresh 128-bit)
span_B   = start_span(trace_id=T', parent_id=S_A)  # preserves S_A as parent

B then calls C with `traceparent: 00-T'-S_B-01`. C, correctly implemented, continues trace `T'` and emits `span_C` under `T'`.

The observable symptom: the planner's trace view (`T`) contains only `S_A` and the client-side span for the B call. The verifier's trace view (`T'`) contains `S_B` and `span_C` — but **`S_A` is not in it**, because `S_A` was emitted under `T`. The `parent-id=S_A` on `S_B` is a dangling reference: no span with `span_id=S_A` exists in trace `T'`. A cross-trace join on `parent-id` finds nothing.

The failure is intermittent in appearance because it only manifests when B's "own your root" path is taken — which in this deployment was gated on a capability-negotiation flag. When B negotiated `capabilities.trace_root = "caller"`, it propagated `T` correctly. When the negotiation fell back to default (a schema mismatch on an unrelated field caused the whole capabilities object to be discarded by B's strict parser), B silently took the "own root" branch. **The trace-correlation invariant was coupled to an unrelated capability-negotiation outcome.**

Condition of Validity

The invariant that must hold for cross-federation correlation is:

> For every span `s` emitted by agent `X` while handling a request that carried inbound context `(trace_id=T, parent_id=P)`, `s.trace_id == T` and `s.parent_id == P`. The only permitted mutation of `trace_id` is at a **declared trace boundary** — an ingress point explicitly configured as a trust boundary, where the inbound `traceparent` is *dropped entirely* (trace loss, not fragmentation) and the boundary is annotated as such.

This invariant is valid only when:

Decision Boundary

The boundary is between two defensible policies, and the failure lives in the space between them where the policy is *implicit*:

The anti-pattern — and the one that produces fragmentation — is **reset-while-retaining-parent**: minting a new `trace_id` but keeping the inbound `span_id` as the parent. This is never correct. It is a category error produced by a tracer that conflates "this span's parent" (a within-trace relation) with "the call that triggered me" (a cross-trace relation). The former is `parent_id`; the latter is a span link.

The decision rule: **if `trace_id` changes, `parent_id` must be null and the inbound context must be recorded as a span link.** If `parent_id` is set, `trace_id` must equal the inbound `trace_id`. There is no third option.

Operational Effect

When fragmentation occurs undetected:

The guardrail is a **trace-integrity assertion at the tracer boundary**, enforced before any span is exported, plus a capability-negotiation contract that makes `trace_root` a required field whose absence is a hard failure rather than a silent default. The check below rejects fragmentation at emit time.

import re
from dataclasses import dataclass

_TRACEPARENT = re.compile(
    r"^(?P<ver>[0-9a-f]{2})-(?P<trace>[0-9a-f]{32})-(?P<span>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)


class TraceFragmentationError(RuntimeError):
    """Raised when an emitted span severs the inbound trace_id while retaining its parent link."""


@dataclass(frozen=True)
class InboundContext:
    trace_id: str
    parent_id: str
    sampled: bool


@dataclass(frozen=True)
class EmittedSpan:
    trace_id: str
    span_id: str
    parent_id: str | None


def parse_traceparent(header: str) -> InboundContext:
    m = _TRACEPARENT.match(header.strip().lower())
    if not m:
        raise TraceFragmentationError(f"malformed traceparent: {header!r}")
    if m["trace"] == "0" * 32 or m["span"] == "0" * 16:
        raise TraceFragmentationError("all-zero trace_id or span_id is invalid per W3C")
    return InboundContext(
        trace_id=m["trace"],
        parent_id=m["span"],
        sampled=bool(int(m["flags"], 16) & 0x01),
    )


def assert_trace_integrity(inbound: InboundContext, emitted: EmittedSpan) -> None:
    """
    Enforce: if trace_id changes, parent_id MUST be None (declared boundary reset).
    If parent_id is set, trace_id MUST equal the inbound trace_id.
    Reset-while-retaining-parent is a hard error.
    """
    if emitted.parent_id is not None:
        if emitted.trace_id != inbound.trace_id:
            raise TraceFragmentationError(
                "trace fragmentation: emitted span retains parent_id="
                f"{emitted.parent_id!r} but mints new trace_id {emitted.trace_id!r} "
                f"(inbound trace_id was {inbound.trace_id!r}). "
                "Either propagate the inbound trace_id or drop parent_id and "
                "record the inbound context as a span link."
            )
        if emitted.parent_id != inbound.parent_id:
            raise TraceFragmentationError(
                f"parent_id mismatch: emitted {emitted.parent_id!r}, "
                f"inbound {inbound.parent_id!r} within same trace"
            )
    else:
        # Declared boundary reset: trace loss is permitted only with explicit
        # boundary annotation, which the caller must have set out-of-band.
        if emitted.trace_id == inbound.trace_id:
            raise TraceFragmentationError(
                "reset without new trace_id: parent_id dropped but trace_id "
                "unchanged, producing an orphan span"
            )


def handle_tool_call(raw_traceparent: str, trace_root_policy: str | None) -> EmittedSpan:
    """
    trace_root_policy must be explicitly negotiated ('caller' or 'boundary').
    A None policy is a negotiation failure and must NOT default silently.
    """
    if trace_root_policy not in ("caller", "boundary"):
        raise TraceFragmentationError(
            f"trace_root_policy not negotiated (got {trace_root_policy!r}); "
            "refusing to guess — silent default causes fragmentation"
        )
    inbound = parse_traceparent(raw_traceparent)

    if trace_root_policy == "caller":
        emitted = EmittedSpan(
            trace_id=inbound.trace_id,
            span_id="a1b2c3d4e5f60718",
            parent_id=inbound.parent_id,
        )
    else:  # boundary reset: new root, NO parent link
        emitted = EmittedSpan(
            trace_id="9f8e7d6c5b4a39281706f5e4d3c2b1a0",
            span_id="a1b2c3d4e5f60718",
            parent_id=None,
        )

    assert_trace_integrity(inbound, emitted)
    return emitted