0Pricing
Claude Architect · Lección

Protocolos estructurados de transferencia

Transfiera el trabajo con ID, resumen, acciones y recomendación.

Protocolos estructurados de transferencia es una lección gratuita de Claude Architect en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Claude Architect, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Claude Architect incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Handoffs Need Structure

In a hub-and-spoke multi-agent system, the coordinator constantly hands work to subagents and receives results back. The CRITICAL fact: subagents do NOT inherit the coordinator's conversation history — the model keeps no state, so the FULL request history travels in messages every turn.

That means every handoff must carry its own context explicitly. An unstructured "go fix the auth bug" loses the case ID, what was already tried, and what decision the coordinator needs back. A structured handoff protocol fixes this: each transfer carries an identifier, a summary, the actions taken, and a recommendation.

The Four-Part Handoff

A reliable handoff payload has four fields, each solving a specific failure mode:

  • ID — a stable correlation key (case_id, custom_id) so results can be matched to requests, even across parallel calls.
  • Summary — the verbatim transactional facts the receiver needs (verified customer ID, order number, amounts).
  • Actions — what was already attempted, with results, so work isn't repeated.
  • Recommendation — the proposed next step or decision the receiver must confirm or override.

This maps directly onto how coordinators decompose, delegate, aggregate, and route.

Pass Context Explicitly

Because the subagent starts with a blank history, you cannot rely on "it already knows." Build the handoff into the subagent's prompt itself. Notice how the ID, summary, and prior actions are spelled out — nothing is assumed.

subagent_prompt = f"""
HANDOFF
id: {case_id}
summary: Verified customer C-4821 (id confirmed via get_customer).
  Order O-9930, refund requested: $420.
actions_taken:
  - get_customer -> identity verified
  - lookup_order(O-9930) -> status DELIVERED, eligible
recommendation: Approve refund of $420; confirm against policy before process_refund.

Proceed with the recommendation or override it with justification.
"""

response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="You are the refund-processing subagent.",
    messages=[{"role": "user", "content": subagent_prompt}],
    tools=refund_tools,
)

Enforce Shape With Structured Output

A free-text handoff is easy to malform. To guarantee all four fields are present, make the handoff a tool with a JSON Schema and use tool_choice to force structured output. tool_use + JSON Schema eliminates syntax errors and enforces required fields.

Key rule from the fact sheet: mark a field required ONLY if it is always present. id, summary, actions, and recommendation are always present in a valid handoff — so they are legitimately required. An optional field like escalation_reason must NOT be required, or the model will fabricate it.

handoff_tool = {
    "name": "emit_handoff",
    "description": "Emit a structured handoff to the coordinator.",
    "input_schema": {
        "type": "object",
        "properties": {
            "id": {"type": "string"},
            "summary": {"type": "string"},
            "actions": {"type": "array", "items": {"type": "string"}},
            "recommendation": {"type": "string"},
            "escalation_reason": {"type": "string"}
        },
        "required": ["id", "summary", "actions", "recommendation"]
    }
}

Force the Handoff With tool_choice

How you set tool_choice decides whether you actually get a structured handoff:

  • "auto" — the model may reply with prose instead of a handoff. Risky for protocols.
  • "any" — the model MUST call some tool, guaranteeing structured output.
  • {"type":"tool","name":"emit_handoff"} — forces exactly this tool. Use this when the subagent's job is to return one well-formed handoff.
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="Summarize your work as a single handoff.",
    messages=history,
    tools=[handoff_tool],
    tool_choice={"type": "tool", "name": "emit_handoff"},
)

handoff = response.content[0].input  # {id, summary, actions, recommendation}

Correlate With a Stable ID

The ID is what lets a coordinator aggregate results that arrive out of order. When you issue multiple Task calls in one response, they run in parallel — replies don't come back in the order you sent them. Without a correlation key you cannot map a result to its request.

This is the same principle as the Batch API's custom_id, which correlates requests so you can re-submit only the failures. In a synchronous multi-agent flow, your handoff id plays that role.

results_by_id = {}
for handoff in subagent_handoffs:
    results_by_id[handoff["id"]] = handoff

# Aggregate deterministically by ID, not by arrival order
for case_id in dispatched_ids:
    h = results_by_id.get(case_id)
    if h is None:
        log.warning("missing handoff for %s", case_id)

Keep Facts Verbatim in the Summary

The summary is where handoffs quietly break. Progressive summarization makes numbers, percentages, and dates vague — exactly the fields a receiver needs to act ($420 becomes "a few hundred dollars"). And models attend to the start and end of context more than the middle (lost-in-the-middle).

The fix: pull transactional facts into a separate case-facts block kept verbatim, outside any prose summary. The handoff's summary field should carry these exact facts, never a lossy paraphrase.

case_facts = {
    "customer_id": "C-4821",
    "order_id": "O-9930",
    "refund_amount_usd": 420.00,
    "delivered_on": "2026-06-02",
}

# Inject verbatim; do NOT let these pass through summarization
summary = (
    "Verified C-4821; order O-9930 delivered 2026-06-02; "
    "refund requested $420.00."
)

Actions: Distinguish Failure From Empty

The actions field must record not just what ran, but what each call returned — and it must distinguish an access FAILURE (maybe retryable) from a valid EMPTY result (no matches, do not retry). Use structured errors, not generic ones.

A structured error carries isError, errorCategory (transient / validation / business / permission), isRetryable, the attempted query, and partial results. Generic "Operation failed" blocks recovery; structured context lets the receiver route intelligently.

actions = [
    {"tool": "get_customer", "result": "verified C-4821"},
    {"tool": "lookup_order", "query": "O-9930",
     "isError": True, "errorCategory": "transient",
     "isRetryable": True,
     "message": "order service timeout",
     "partial_results": []},
]

Recommendation, Not Final Action

The fourth field is a recommendation the receiver can confirm or override — not a unilateral action. This keeps decision authority where it belongs and supports clean escalation.

Good escalation triggers belong in the recommendation: an explicit human request (escalate immediately), a policy gap, no progress after attempts, or a threshold violation. BAD triggers must never drive it: sentiment analysis, a model self-rated confidence score, or an untrained classifier. A recommendation reading "customer sounds frustrated, escalate" is the anti-pattern.

recommendation = (
    "Refund $420 is within policy and order is eligible. "
    "RECOMMEND approve. NOTE: refunds over $500 require a "
    "hook-enforced check; this is under threshold."
)
# escalation_reason set ONLY on a real trigger, e.g.:
# "Customer explicitly asked for a manager."

Guard Critical Steps With Hooks

A handoff's recommendation is probabilistic — prompt guidance is right roughly 90% of the time. When acting on a handoff has financial, legal, or safety consequences, the guarantee must be deterministic, enforced by a hook, not by the recommendation text.

An outgoing-call hook can block a policy-violating action (e.g. refund > $500) regardless of what the subagent recommended. A programmatic precondition — block process_refund until get_customer returned a verified ID — gives a guarantee prompts cannot. Hooks = 100% deterministic; prompts ≈ 90% probabilistic.

# settings.json — deterministic enforcement on the action,
# independent of the handoff recommendation
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "process_refund",
      "command": "./hooks/block_refund_over_500.sh"
    }]
  }
}

Resume vs Fresh Summary

Sometimes a handoff continues earlier work. --resume <name> continues a named session and fork_session branches from a shared point. But beware: resumed tool results can be STALE if the codebase or data changed underneath them.

When the underlying state has moved, a fresh session seeded with a structured handoff (ID + verbatim facts + actions + recommendation) is often more reliable than resuming a session full of outdated tool output. The structured handoff is what makes a clean restart cheap.

# Continue named work...
claude --resume refund-C4821

# ...but if state changed, start fresh and inject the handoff:
claude -p "$(cat handoff_C4821.json)" \
  --system-prompt "Act on this structured handoff."

Quick Check: Designing the Handoff

A coordinator dispatches three refund cases to subagents with parallel Task calls. You are designing the handoff each subagent returns so results can be aggregated and acted on safely. Which design is correct?

Recap: Structured Handoff Protocols

Key takeaways:

  • Subagents inherit no history — every handoff carries its own context explicitly.
  • Four fields: ID (correlate parallel results), summary (verbatim facts), actions (with structured errors), recommendation (confirm/override).
  • Force the shape with a handoff tool + JSON Schema and tool_choice; require only always-present fields.
  • Keep numbers and dates verbatim in a case-facts block — summarization makes them vague.
  • In actions, distinguish access failure from a valid empty result via errorCategory and isRetryable.
  • Gate consequential actions with deterministic hooks, never with the recommendation alone.
  • If resumed tool output may be stale, restart fresh with the structured handoff.

Preguntas frecuentes

¿La lección «Protocolos estructurados de transferencia» es gratis?

Sí — el texto completo de «Protocolos estructurados de transferencia» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Claude Architect, actualiza a CoddyKit PRO. El curso de Claude Architect incluye 4 lecciones en total.

¿Qué aprenderé en «Protocolos estructurados de transferencia»?

Transfiera el trabajo con ID, resumen, acciones y recomendación. Practicas Claude Architect con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Claude Architect?

No se requiere experiencia previa. Claude Architect en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Protocolos estructurados de transferencia»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Claude Architect?

Sí. Cada lección de Claude Architect incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Hooks de PostToolUse y llamadas salientes
  2. Aplicación determinista frente a prompts
  3. Precondiciones programáticas
  4. Protocolos estructurados de transferencia
← Volver a Claude Architect