Tasks & Messages

Tasks and messages are the core data model of the A2A protocol. Understanding their structure and lifecycle is essential for building agents.

Tasks

A Task represents a unit of work. A SendMessage that names no task starts one; one that names a live task continues it; and an agent may answer with a direct Message instead of returning a task.

Task Structure

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::types::task::{ContextId, TaskId, TaskStatus, TaskState};
use a2a_protocol_sdk::types::message::{Message, MessageId, MessageRole, Part};
use a2a_protocol_sdk::types::artifact::{Artifact, ArtifactId};
pub struct Task {
    pub id: TaskId,                          // Server-assigned unique ID
    pub context_id: ContextId,               // Conversation thread ID
    pub status: TaskStatus,                  // Current state + optional message
    pub history: Option<Vec<Message>>,       // The task's messages; omitted from a send response by default
    pub artifacts: Option<Vec<Artifact>>,    // Produced results
    pub metadata: Option<serde_json::Value>, // Arbitrary key-value data
}
// The real type has exactly these fields: this pattern names them all.
fn _fields(t: a2a_protocol_sdk::types::task::Task) {
    let a2a_protocol_sdk::types::task::Task { id: _, context_id: _, status: _, history: _, artifacts: _, metadata: _, .. } = t;
}
}

A SendMessage response omits history unless the request's configuration.historyLength asks for it (n keeps the newest n messages; 0 omits). GetTask returns the stored, size-capped history unless historyLength trims it.

Task States

Tasks follow a state machine with validated transitions; the proto's default, Unspecified, is not a state a task is ever in:

StateMeaningTerminal?
UnspecifiedThe proto default (TASK_STATE_UNSPECIFIED): no real state. Never send it as a status: a server refuses the event and a client refuses a task carrying itNo
SubmittedReceived, not yet startedNo
WorkingActively processingNo
InputRequiredNeeds more input from clientNo
AuthRequiredNeeds authenticationNo
CompletedFinished successfullyYes
FailedFinished with errorYes
CanceledCanceled before completion (by CancelTask)Yes
RejectedThe agent declined the task, at creation or laterYes

Valid Transitions

Not all state transitions are allowed. TaskState::can_transition_to encodes two rules, and the server applies them to every status update and task snapshot an executor writes:

  1. Terminal states (Completed, Failed, Canceled, Rejected) are final, including to themselves.
  2. Nothing transitions into Submitted or Unspecified.

Everything else is allowed, Submitted → Completed and Working → Working included.

State diagram: a new task starts in Submitted; from Submitted it may go to Working, to an interrupted state (InputRequired or AuthRequired) or straight to a terminal state; Working may repeat, go to an interrupted state or end; an interrupted task returns to Working on its next turn or ends; the terminal states Completed, Failed, Canceled and Rejected are final.
The usual paths. Any move is valid except out of a terminal state or into Submitted.

The server checks the rule when it processes an event, against the task as it holds it. Which error the client sees depends on the path that processed the event:

Flowchart: the executor writes a status update or task snapshot; if can_transition_to allows the move it is stored; if not, a blocking SendMessage fails with ServerError::InvalidStateTransition, which the client receives as InvalidParams, while on the streaming or returnImmediately path the task is marked Failed.
Where an invalid transition is caught.
  • Blocking SendMessage — the collector returns ServerError::InvalidStateTransition, which reaches the client as an InvalidParams error naming the task and both states.
  • Streaming and returnImmediately — the background processor has no caller to fail, so it marks the task Failed and stores that.

The same check applies to a task snapshot that changes the state. Checking transitions yourself:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::TaskState;

// Check if a transition is valid
assert!(TaskState::Submitted.can_transition_to(TaskState::Working));
assert!(TaskState::Working.can_transition_to(TaskState::Completed));

// Terminal states cannot transition
assert!(!TaskState::Completed.can_transition_to(TaskState::Working));
assert!(!TaskState::Failed.can_transition_to(TaskState::Working));

// Check if a state is terminal
assert!(TaskState::Completed.is_terminal());
assert!(!TaskState::Working.is_terminal());
}

Terminal State Constraints

Tasks in terminal states enforce strict invariants:

  • No new messages — SendMessage to a terminal task returns UnsupportedOperation. Start a new task instead.
  • No subscription — SubscribeToTask on a terminal task returns UnsupportedOperation since no new events will be emitted.
  • No cancellation — CancelTask on a terminal task returns TaskNotCancelable.
  • Unknown taskId — SendMessage with a taskId that doesn't reference an existing task returns TaskNotFound.

Two more rules apply to a SendMessage that names a task, whatever its state:

  • One run at a time — a SendMessage naming a task whose executor is still running returns UnsupportedOperation; wait for INPUT_REQUIRED, AUTH_REQUIRED or a terminal state.
  • Context must match — a message whose contextId differs from the named task's returns InvalidParams.

Task Status

The status combines a state with an optional message and timestamp:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::{TaskStatus, TaskState};

// Without timestamp
let status = TaskStatus::new(TaskState::Working);

// With automatic UTC timestamp
let status = TaskStatus::with_timestamp(TaskState::Completed);
}

Wire Format

On the wire, task states use SCREAMING_SNAKE_CASE with a TASK_STATE_ prefix:

{
  "id": "task-abc",
  "contextId": "ctx-123",
  "status": {
    "state": "TASK_STATE_COMPLETED",
    "timestamp": "2026-03-15T10:30:00Z"
  },
  "artifacts": [...]
}

Messages

A Message is a structured payload exchanged between client and agent:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::types::task::{ContextId, TaskId, TaskStatus, TaskState};
use a2a_protocol_sdk::types::message::{MessageId, MessageRole, Part};
use a2a_protocol_sdk::types::artifact::{Artifact, ArtifactId};
pub struct Message {
    pub id: MessageId,                           // Unique message ID (wire name: messageId)
    pub role: MessageRole,                       // User or Agent
    pub parts: Vec<Part>,                        // Content (≥1 part)
    pub task_id: Option<TaskId>,                 // Associated task
    pub context_id: Option<ContextId>,           // Conversation thread
    pub reference_task_ids: Option<Vec<TaskId>>, // Related tasks
    pub extensions: Option<Vec<String>>,         // Extension URIs
    pub metadata: Option<serde_json::Value>,
}
fn _fields(m: a2a_protocol_sdk::types::message::Message) {
    let a2a_protocol_sdk::types::message::Message { id: _, role: _, parts: _, task_id: _, context_id: _, reference_task_ids: _, extensions: _, metadata: _, .. } = m;
}
}

Roles

RoleWire ValueMeaning
User"ROLE_USER"From the client/human side
Agent"ROLE_AGENT"From the agent/server side
Unspecified"ROLE_UNSPECIFIED"The proto default; a server refuses a message that carries it (InvalidParams)

Creating Messages

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;

let message = Message::new(MessageId::new(uuid::Uuid::new_v4().to_string()), MessageRole::User, vec![Part::text("What is 2 + 2?")]);
}

Parts

Parts are the content units within messages and artifacts. Four types are supported:

Text

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;
let part = Part::text("Hello, agent!");
assert_eq!(serde_json::to_value(&part).unwrap(), serde_json::json!({"text": "Hello, agent!"}));
}

Wire format: {"text": "Hello, agent!"}

Raw (inline bytes)

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;
let base64_encoded_string = "aGVsbG8=";
// Inline bytes (base64-encoded)
let part = Part::raw(base64_encoded_string);
}

Wire format: {"raw": "aGVsbG8=", "filename": "doc.bin", "mediaType": "application/octet-stream"}

Part::raw does not check its argument. A server refuses a raw that is not base64 with InvalidParams naming the field; URL-safe and unpadded base64 are accepted and returned in standard padded form. The same check applies to the events an executor writes.

A raw part travels inside the task: it is kept in the task's row, in every event that carries it, and in every subscriber's buffer until it is sent. For anything large, an executor should store the bytes where its readers may fetch them and emit a url part instead; it is the one place that knows where the bytes may live and who may read them. The SDK does not rewrite raw to url (ADR 0047). with_max_event_size refuses an event that is too large, and HandlerLimits::with_max_buffered_event_bytes bounds the bytes all queues hold at once.

Url (URI reference)

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;
// URI reference
let part = Part::url("https://example.com/document.pdf");
assert_eq!(serde_json::to_value(&part).unwrap(), serde_json::json!({"url": "https://example.com/document.pdf"}));
}

Wire format: {"url": "https://example.com/document.pdf"}

Structured Data

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;
let part = Part::data(serde_json::json!({
    "table": [
        {"name": "Alice", "score": 95},
        {"name": "Bob", "score": 87}
    ]
}));
assert!(serde_json::to_value(&part).unwrap()["data"]["table"].is_array());
}

Wire format: {"data": {"table": [...]}}

Protobuf carries these numbers as doubles, so a server refuses an integer beyond ±2^53 in a data part or in metadata with InvalidParams, in a client's message and in an executor's events alike.

Part Metadata

Any part can carry optional metadata:

{
  "text": "Hello",
  "metadata": {"language": "en"}
}

Artifacts

Artifacts are results produced by an agent, delivered as part of a task:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::types::task::{ContextId, TaskId, TaskStatus, TaskState};
use a2a_protocol_sdk::types::message::{Message, MessageId, MessageRole, Part};
use a2a_protocol_sdk::types::artifact::ArtifactId;
pub struct Artifact {
    pub id: ArtifactId,                      // wire name: artifactId
    pub name: Option<String>,
    pub description: Option<String>,
    pub parts: Vec<Part>,                    // ≥1 part
    pub extensions: Option<Vec<String>>,
    pub metadata: Option<serde_json::Value>,
}
fn _fields(a: a2a_protocol_sdk::types::artifact::Artifact) {
    let a2a_protocol_sdk::types::artifact::Artifact { id: _, name: _, description: _, parts: _, extensions: _, metadata: _, .. } = a;
}
}

Create and validate an artifact:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;

let artifact = Artifact::new(
    "result-1",
    vec![Part::text("The answer is 42")],
);
// `Artifact::new` panics in debug builds on empty parts; `validate()` is the
// fallible check for an artifact built another way (a struct literal, or one
// you deserialized). A server refuses an artifact with no parts.
artifact.validate().expect("artifact should be valid");
}

Streaming Artifacts

Artifacts can be delivered incrementally during streaming:

#![allow(unused)]
fn main() {
use a2a_protocol_sdk::prelude::*;
async fn f(ctx: &RequestContext, queue: &dyn EventQueueWriter) -> A2aResult<()> {
// First chunk
queue.write(StreamResponse::ArtifactUpdate(
    TaskArtifactUpdateEvent::new(
        ctx.task_id.clone(),
        ctx.context_id.clone(),
        Artifact::new("doc", vec![Part::text("First paragraph...")]),
    )
    .with_last_chunk(false), // More chunks coming
)).await?;

// Final chunk — parts are appended, metadata is merged key by key
queue.write(StreamResponse::ArtifactUpdate(
    TaskArtifactUpdateEvent::new(
        ctx.task_id.clone(),
        ctx.context_id.clone(),
        Artifact::new("doc", vec![Part::text("Last paragraph.")]),
    )
    .with_append(true)      // Append parts to existing artifact by ID
    .with_last_chunk(true), // This is the last chunk
)).await?;
Ok(())
}
}

When append=true, the server finds the existing artifact by ID and:

  1. Appends the new parts to the existing parts list
  2. Merges metadata key by key at the top level (new keys override existing keys)

If no artifact with the ID exists, it is created as a new artifact.

A chunk without append (or with append: false) for an ID the task already holds replaces that artifact; it does not add a second one, so every chunk after the first needs append: Some(true). An append that would take the artifact past max_parts_per_artifact (a HandlerLimits field, default 10,000) is dropped.

ID Types

a2a-rust uses newtype wrappers for type safety:

TypeWrapsExample
TaskIdStringTaskId::new("task-abc")
ContextIdStringContextId::new("ctx-123")
MessageIdStringMessageId::new("msg-456")
ArtifactIdStringConstructed inside Artifact::new

These prevent accidentally passing a task ID where a context ID is expected.

Next Steps