All chapters
  1. Start hereOne agent asks. Another answers. The rest is the contract between them
  2. Foundations · 1One model, one tool, two agents: who is who, and who is responsible
  3. Foundations · 2Message passing: sender, recipient, payload, address and correlation
  4. Foundations · 3Topologies: central orchestrator, peer-to-peer and hierarchy
  5. Mechanics · 4Request and reply, or a task: synchronous versus asynchronous exchange
  6. Mechanics · 5Contracts: messages, artifacts, typed schemas, errors and versions
  7. Mechanics · 6The task lifecycle: submitted, working, input-required, completed, failed, canceled
  8. Mechanics · 7Discovery: Agent Cards, skills and how an agent says what it can do
  9. Protocol · 8A2A: the Agent2Agent protocol, part by part
  10. Protocol · 9A2A versus MCP: delegating to an agent versus calling a tool
  11. Protocol · 10Handoff, delegation or shared state: three ways to work together
  12. Production · 11How updates arrive: streaming, push notifications, callbacks, polling and queues
  13. Production · 12Security: identity, delegated scopes, trust across domains, authorization
  14. Production · 13Reliability: retries, idempotency, order, timeouts and compensation
  15. Production · 14Observability: one trace across three agents
  16. Reference · 15Frameworks: A2A SDKs, LangGraph, AutoGen, CrewAI and plain code
  17. Reference · 16Advanced: consensus claims, coordination failure, cost and isolation
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Mechanics · 5

Contracts: messages, artifacts, typed schemas, errors and versions

What two agents must agree on before the first message: the shape of the request, the artifact that comes back, the errors with names, and how the shape may change.

What you will understand
The agreement
A contract is what both agents agreed on before the first message: shapes, errors, states, versions.
Message or artifact
A message is talk about the work. An artifact is the work's result, with its own id and schema.
Changing safely
Which changes an old reader survives, which ones break it, and how to tell before you ship.

The evidence team improved its artifact. The list of facts had been called evidence; several team members found the name confusing next to the artifact's own name, so in the new release it became items. The change was small, the tests of the evidence team passed, and the release went out on a Tuesday.

The underwriting agent had not changed. It read the artifact as it always had, looked for evidence, found nothing, and wrote recommendations as if no evidence had been collected. Case UW-403, the conflicting roof age, came back as request_info instead of escalate. The roof was 22 years old and nobody was told.

Nothing crashed, and that is the problem. The two agents had an agreement about the artifact's shape, but it existed only in the code of each side. When one side changed, nothing compared the two. This page is about writing that agreement down.

What a contract is#

A contract is what two agents agreed on before the first message: the shape of each request, the shape of the result, the errors with their names, the states a task may pass through, and the versions of all of these. For example: "the assessment agent accepts evidence.request/v1 and answers with evidence.artifact/v1; when it cannot collect a fact, it names the gap; when a request is malformed, it answers FIELD_MISSING or TYPE_MISMATCH".

A schema is the written shape of one kind of payload: its fields, their types, which are required. For example, evidence.request/v1 requires submission_id (text), need (a list) and submission (an object). A schema id has a name and a version, separated by a slash, so a receiver can tell which shape it is reading.

Plain English. A contract is the order form both companies printed before the first order: which boxes exist, which must be filled, what the supplier sends back, and what each error code on the delivery slip means. The form has a version number in the corner.

Message and artifact#

Two kinds of thing travel between agents, and a good contract keeps them apart.

A message, as on Messages, is talk about the work: a request, a status update, a question, a cancel. It is short-lived; once acted on, it has done its job.

An artifact is the result a task produces: a structured, versioned output with its own id. For example, the assessment agent's evidence artifact art-a1. An artifact is kept: the underwriting agent reads it, the recommendation cites its evidence ids, an auditor may read it a year later. It is a document, not a conversation.

The artifact in this example is the evidence artifact, evidence.artifact/v1: everything the assessment agent found about one submission, with an id and a source for every piece. Here it is for UW-403, from a real run of the example (only the guidance passages are shortened to the two that matter):

{
  "artifact_id": "art-a1",
  "submission_id": "SUB-1004",
  "run_id": "run-7f3a",
  "policy_version": "2026.2",
  "evidence": [
    {"evidence_id": "EV-APP-1004", "kind": "roof_age_application", "source": "application", "value": {"roof_age_years": 9}, "trusted": true},
    {"evidence_id": "EV-ROOF-0412", "kind": "roof_assessment", "source": "roof-data provider (stand-in)", "value": {"status": "ok", "roof_age_years": 22, "method": "aerial image, synthetic"}, "trusted": true},
    {"evidence_id": "EV-GUIDE-ROOF-03", "kind": "guidance", "source": "policy_fixture", "value": {"rule_id": "R-ROOF-03", "text": "Roof age on the application and from the provider differ by more than 5 years: escalate to a senior underwriter.", "similarity": 0.29}, "trusted": true, "policy_version": "2026.2"}
  ],
  "gaps": [],
  "produced_by": "assessment-agent",
  "attempt_number": 1
}

Three design choices make this artifact a good contract. Both roof ages are carried, each with its own evidence id, instead of one "best" value: the conflict is the finding, and the underwriting agent needs both to cite R-ROOF-03. Each piece carries trusted and, where it applies, the policy_version it belongs to, so the consumer can treat a passage from outside the policy fixture as data, not instruction (Security, case UW-405). And gaps names what could not be collected, so "nothing found" and "could not look" are different answers.

Diagram: The contract of one exchange · what both sides agree on

Read left to right. The caller sends a request in a named schema version; the receiver validates it on receipt and either answers with a typed error or accepts the work. The task's states are part of the contract. The result is an artifact in its own schema. A compatibility check in CI compares versions before a release.

  1. Request
    1. evidence.request/v1: The shape of the request: submission_id, need, submission.
    2. validate on receipt: The receiver checks the payload against the schema it claims before any work.
  2. Errors
    1. Typed error: An error a program can branch on.
  3. States
    1. Task states: Which states a task may pass through, and which moves are allowed. Covered on the task lifecycle page.
  4. Result
    1. evidence.artifact/v1: A kept, versioned result with an id, every fact with an evidence id and a source, and the gaps.
    2. is_compatible: Can a reader of the old version read the new one? Run in CI before a release.

The smallest primitive: validate on receipt#

The smallest mechanism that turns an agreement into a contract is a check on the receiving side: before acting on a payload, compare it with the schema it claims, and answer with a named error if it does not match. In the example every agent does this for every request (Agent._on_request calls validate), and the errors have names a program can test.

The schemas are plain dictionaries in examples/uw-agents/contracts.py. These are the two schemas of the evidence exchange, verbatim:

def _f(type: str, required: bool = True, nullable: bool = False) -> dict[str, Any]:
    return {"type": type, "required": required, "nullable": nullable}


_ARTIFACT_V1 = {"artifact_id": _f("str"), "submission_id": _f("str"), "run_id": _f("str"), "policy_version": _f("str"),
                "evidence": _f("list"), "gaps": _f("list"), "produced_by": _f("str"), "attempt_number": _f("int")}

and in SCHEMAS, "evidence.request/v1": {"submission_id": _f("str"), "need": _f("list"), "submission": _f("dict")}.

A typed error is an error answer with a fixed code a program can branch on, plus a sentence for a person. For example {"code": "TASK_NOT_CANCELABLE", "message": "...", "retryable": false}. The example names ten codes, from SCHEMA_UNKNOWN and VERSION_UNSUPPORTED to DEADLINE_EXCEEDED. A caller can retry on one code and stop on another; it cannot do that with a free-text "something went wrong".

An executable demonstration#

This script, run from the example folder, validates a good request, a broken one, and a request in a version the receiver does not accept; then it asks whether two artifact versions are compatible, and builds one typed error:

import json
from contracts import validate, is_compatible, error

ok = {"submission_id": "SUB-1004", "need": ["roof_assessment"], "submission": {"submission_id": "SUB-1004"}}
print(validate("evidence.request/v1", ok))
print(validate("evidence.request/v1", {"submission_id": 1004, "need": ["roof_assessment"]}))
print(validate("evidence.request/v2", ok, accepts=("evidence.request/v1",)))
print(json.dumps(is_compatible("evidence.artifact/v1", "evidence.artifact/v2")))
print(json.dumps(is_compatible("evidence.artifact/v1", "evidence.artifact/v3")))
print(error("TASK_NOT_CANCELABLE", "task-c1 is canceled; a terminal state never moves"))
[]
[{'code': 'TYPE_MISMATCH', 'field': 'submission_id', 'message': '`submission_id` must be str, got int'}, {'code': 'FIELD_MISSING', 'field': 'submission', 'message': 'evidence.request/v1 requires `submission`'}]
[{'code': 'VERSION_UNSUPPORTED', 'field': 'schema', 'message': 'evidence.request/v2: The schema name is known, but the receiver does not accept this version.'}]
{"old": "evidence.artifact/v1", "new": "evidence.artifact/v2", "compatible": true, "problems": [], "added": ["collected_at_ms"]}
{"old": "evidence.artifact/v1", "new": "evidence.artifact/v3", "compatible": false, "problems": ["`evidence` was removed or renamed"], "added": ["items"]}
{'code': 'TASK_NOT_CANCELABLE', 'message': 'task-c1 is canceled; a terminal state never moves', 'retryable': False}

Every failure has a name and a field. The version check distinguishes "I do not know this schema" from "I know it, but not this version", which tells the sender whether to downgrade or give up. The last two lines are the opening story, caught before release: v2 adds an optional field and is safe for a v1 reader; v3 renames evidence to items and is not.

Versions and compatible change#

Versioning means giving each shape a version and changing the version when the shape changes, so that both sides can say which one they speak. In the example the version is part of the schema id: evidence.artifact/v1.

A change is backward-compatible when a consumer written for the old version can still read what the producer sends under the new one. The rule is_compatible applies is the common one: every field the old reader requires must still be there, with the same type, still required. Adding an optional field is compatible, because an old reader ignores fields it does not know. Removing, renaming or retyping a required field breaks the old reader.

Change to evidence.artifactExampleOld reader still works?
Add an optional fieldv2 adds collected_at_msYes
Rename a required fieldv3 renames evidence to itemsNo: evidence was removed or renamed
Change a field's typeattempt_number from int to textNo
Make a required field optionalgaps may be absentNo: no longer guaranteed
Add a new value to an enum the reader branches ona new recommendation valueThe schema check passes, but the reader's logic may not know it: test it

The last row is the one schema checks miss. A new evidence kind or a fifth recommendation value passes every type check, and an old consumer may still mishandle it. Compatibility is about behavior, not only shape.

Before AI. Teams that run Avro or Protobuf behind a schema registry know these rules as backward and forward compatibility, enforced at publish time. OpenAPI teams know them as "do not remove a field from a response". The agent version of the problem is the same, with one extra source of drift: an agent's output is partly generated, so a shape that "always" had a field may omit it when the model is unsure. Validate what you receive, even from your own agents.

A failure mode: the silent mismatch#

Return to the Tuesday release. Without validation on receipt, the underwriting agent reads artifact.get("evidence", []), gets an empty list, and goes on. Its recommendation for UW-403 cites no roof evidence and asks for information that was already collected. With the contract in place, three things would have stopped it. The producer would have published evidence.artifact/v3, not changed v1 in place. The consumer, which accepts only v1, would have answered VERSION_UNSUPPORTED, a loud and named failure. And a compatibility check in the producer's CI, the equivalent of is_compatible("evidence.artifact/v1", "evidence.artifact/v3"), would have reported "evidence was removed or renamed" before the release.

Production pitfall. Lenient parsing ("ignore what you do not understand") is right for added fields and wrong for missing required ones. A consumer that silently defaults a missing field to empty turns every breaking change into a wrong answer instead of an error.

How the A2A protocol carries contracts#

The A2A protocol, an open standard for messages between agents, does not prescribe your payload schemas. It defines the frame around them: a message carries its content as parts (text, structured data, files), a task produces artifacts with their own ids, and the protocol has named errors of its own. Which parts and error names exist, read from the specification, is on A2A. Agents also advertise the input and output types they accept in their Agent Card (Discovery). Typed models in libraries (Pydantic in Python, Zod in TypeScript, records in Java) are a common way to write the schemas themselves; Frameworks says which libraries document which.

What this is not. This page covers only what two agents must agree on. Typed output in depth, how to get a model to produce valid structure, repair it when it does not, and evolve schemas over time, belongs to schema.sammuthu.com. Designing the schema of a tool belongs to tools.sammuthu.com.

Checklist: a contract review#

The same idea for a coding agent. A review agent returns its review to a planning agent. If the review is free text, the planning agent must guess which comments block the merge. If it is an artifact, say review/v1 with a list of findings, each with a file, a line, a severity and an id, the planning agent can act on blocking findings and the CI system can count them. When the review team adds a suggested_fix field, the old planning agent keeps working; when it renames findings, the contract check fails before the release.

Tolerant reader, strict writerWhere to be lenient, and where never

The robust pattern is asymmetric: produce exactly the schema you claim, and when reading, ignore unknown fields but reject missing required ones. The example's validator does precisely this: it reads only the fields the schema names, so extra fields pass, and a missing required field fails with FIELD_MISSING.

Two refinements matter at scale. A consumer should accept a range of versions, not one, during a migration: the example's accepts tuple is that list. And a producer should be able to emit the old version for old consumers, which turns a breaking change into a period of dual writing rather than a coordinated release. The cost is real: two shapes in production, and tests for both. The alternative is a release in which every agent changes at once, which is the coupling the split was meant to remove.

Semantic driftSame fields, different meaning

The hardest breaking change keeps every field and changes what one means. Suppose roof_age_years in the artifact switches from "years since the roof was replaced" to "years since the building was built". Every schema check passes. Every recommendation for a re-roofed building is now wrong.

Defenses are partly social and partly technical. Name units and definitions in the schema description, not only types. Version on meaning, not only on shape: a changed definition is a new version even if no field moved. And keep golden cases whose expected outputs depend on the meaning: UW-403 would fail at once if the provider's age were reinterpreted. Measuring behavior on fixed cases is the subject of eval.sammuthu.com.

Designing the error vocabularyFew codes, each with one action

A good error code tells the caller what to do. VERSION_UNSUPPORTED: send an older version or stop. UNAUTHORIZED: do not retry with the same token. DEADLINE_EXCEEDED: the work may have happened; check before retrying. If two codes lead to the same action, merge them; if one code leads to two actions depending on context, split it.

The retryable flag in the example's error payload is a hint, not a guarantee. The caller still owns the decision, and a retry is only safe if the operation is idempotent (Reliability). A protocol's own error names (A2A has several, listed on A2A) cover the protocol layer; your contract still needs codes for your domain, such as EVIDENCE_UNAVAILABLE.

In one breath#

A contract is what two agents agree on before the first message: the request schema, the artifact, named errors, task states and versions. The receiver validates on receipt and answers with a named error, so a mismatch is loud. Adding an optional field is a compatible change; renaming, retyping or dropping a required one breaks the old reader, and a compatibility check in CI should say so before the release.

Next: the contract says what the result looks like. It does not yet say what the work goes through on the way. Task lifecycle defines the states of a task, the moves between them, and what cancel can and cannot undo.