Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

a2a-cpp C++20 Agent2Agent (A2A) SDK Documentation

This book is the canonical public SDK documentation. Shell commands run from the repository root unless a guide explicitly changes directory. Source-folder READMEs provide navigation to these guides.

Repository-wide contribution and maintenance policies remain in the root CONTRIBUTING.md, AGENTS.md, cpp_conventions.md, SUPPORT.md, and SECURITY.md.

a2a-cpp is a C++20 SDK for building Agent2Agent (A2A) protocol clients and servers. The current documented release focuses on production-oriented protocol coverage: REST, JSON-RPC, and gRPC transports; Agent Card discovery; task lifecycle APIs; streaming; push notification configuration APIs; authentication metadata propagation; interceptors; CMake package exports; and vcpkg-oriented packaging.

What is included

  • Client API: SendMessage, GetTask, ListTasks, CancelTask, streaming send/subscribe, and task push-notification config lifecycle calls.
  • Server API: executor-driven dispatch for REST, JSON-RPC, and gRPC transports.
  • Discovery: public and extended Agent Card fetch plus preferred-interface resolution.
  • Streaming: client observers, cancellable stream handles, and server stream sessions.
  • Authentication hooks: client credential providers and server request metadata extraction.
  • Operational extensions: client/server interceptors, required-extension validation, task stores, task history ordering, UUIDv7 task IDs, and optional PostgreSQL stores.
  • Build integration: CMake 3.25+, C++20, installable CMake package exports, generated protobuf headers, and vcpkg overlay/public-registry preparation.
  1. Installation and Build for toolchain requirements and CMake options.
  2. Quickstart for a copy/paste example flow.
  3. Client Overview or Server Overview, depending on your integration role.
  4. Transports, Streaming, and Authentication for runtime design decisions.
  5. API Reference when you need generated public-header details.

Version and support notes

  • See Releases and Versions for current release details and versioning guidance.
  • The SDK is C++20-only and exports CMake targets under the a2a:: namespace.
  • Package documentation describes vcpkg workflows only.
  • Examples are deterministic and run without external services unless their guide says otherwise.

Installation and Build

This page describes the current development build toward v0.6.0. In stable v0.5.2, simdjson is required only when signing is enabled.

Choose an integration method

Use the workflow that matches your application:

  • Build the SDK directly from source as described below.
  • Use CMake FetchContent and pin a release tag or reviewed commit.
  • Install the SDK as a CMake package and consume it with find_package.
  • Consume the repository-local vcpkg overlay port.

Prerequisites

Install these tools before configuring the repository:

  • CMake 3.25 or newer.
  • A C++20 compiler: GCC, Clang, AppleClang, or Visual Studio 2022.
  • Protobuf with protoc.
  • simdjson 3.0 or newer (required even with signing disabled).
  • gRPC C++ with grpc_cpp_plugin.
  • libcurl when using the built-in HTTP, JSON-RPC, or SSE clients.
  • clang-format and clang-tidy for contributor validation.
  • Optional: Doxygen for API reference generation.
  • Optional: PostgreSQL client libraries when building PostgreSQL-backed stores.

Debian or Ubuntu

./scripts/install_build_deps.sh
cmake --version

The automatic installer supports Debian 12+ and Ubuntu 24.04+, whose packages provide simdjson 3.0+ and CMake 3.25+. It rejects older releases before installing packages.

On older releases or other distributions, install the prerequisites above manually. Ubuntu 22.04 and Debian 11 package simdjson versions below 3.0; build a compatible version into a local prefix instead:

git clone --depth 1 --branch v3.12.3 https://github.com/simdjson/simdjson.git
cmake -S simdjson -B simdjson/build \
  -DCMAKE_BUILD_TYPE=Release \
  -DSIMDJSON_DEVELOPER_MODE=OFF \
  -DCMAKE_INSTALL_PREFIX="$PWD/simdjson/install"
cmake --build simdjson/build --parallel
cmake --install simdjson/build
cmake -S . -B build -DCMAKE_PREFIX_PATH="$PWD/simdjson/install"

Install CMake 3.25+ separately if the distribution’s CMake is older.

The same script also supports Windows when run from Git Bash.

macOS

brew install cmake ninja protobuf grpc re2 abseil curl simdjson

When enabling PostgreSQL-backed stores, also install the PostgreSQL client package:

brew install libpq

Windows Git Bash

Install Visual Studio 2022 with the Desktop development with C++ workload and Git for Windows. Open Git Bash in the repository root and run:

./scripts/install_build_deps.sh

The script first checks VCPKG_ROOT, then searches for vcpkg.exe or vcpkg on PATH, and then checks $HOME/vcpkg. It clones and bootstraps vcpkg under ${VCPKG_ROOT:-$HOME/vcpkg} only when an existing installation is not found. It installs the dependencies declared by the root vcpkg.json and prints the resolved VCPKG_ROOT, target triplet, and host triplet when it finishes.

Override VCPKG_ROOT, VCPKG_TARGET_TRIPLET, or VCPKG_HOST_TRIPLET before running the script when needed. Keep the resolved VCPKG_ROOT value for the CMake configuration step below; do not reset it to $HOME/vcpkg when the script found vcpkg elsewhere.

The root manifest does not install PostgreSQL client libraries. For PostgreSQL-enabled Windows builds, use a vcpkg manifest that includes libpq, or consume the SDK through the repository overlay port with its postgres-store feature. See Build with vcpkg.

Configure from source

On Linux:

cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

On macOS, use the same Homebrew prefixes validated by CI:

cmake -S . -B build -G Ninja \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DCMAKE_PREFIX_PATH="$(brew --prefix);$(brew --prefix curl)"

When A2A_ENABLE_POSTGRES_STORE=ON, append $(brew --prefix libpq) to CMAKE_PREFIX_PATH.

On Windows Git Bash, set VCPKG_ROOT to the value printed by install_build_deps.sh or to an existing vcpkg checkout:

export VCPKG_ROOT="/path/to/vcpkg"
export VCPKG_TARGET_TRIPLET="${VCPKG_TARGET_TRIPLET:-x64-windows}"
export VCPKG_HOST_TRIPLET="${VCPKG_HOST_TRIPLET:-$VCPKG_TARGET_TRIPLET}"
cmake -S . -B build -G "Visual Studio 17 2022" -A x64 \
  -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
  -DVCPKG_TARGET_TRIPLET="$VCPKG_TARGET_TRIPLET" \
  -DVCPKG_HOST_TRIPLET="$VCPKG_HOST_TRIPLET"

If a build directory was first configured without the vcpkg toolchain, delete it before reconfiguring. CMake caches the toolchain during the first configure.

Useful options:

OptionDefaultPurpose
A2A_ENABLE_TESTINGONBuilds unit and integration tests.
A2A_BUILD_EXAMPLESONKeeps the root project compatible with example-related CI messaging; curated examples are built as standalone consumers.
A2A_BUILD_BENCHMARKSOFFBuilds the optional Google Benchmark suite.
A2A_ENABLE_LIBCURLONEnables default outbound HTTP and SSE support when CURL::libcurl is found.
A2A_ENABLE_POSTGRES_STOREOFFBuilds PostgreSQL task and push-notification stores.

Build and test

Linux or macOS:

cmake --build build --parallel
ctest --test-dir build --output-on-failure

Windows Visual Studio generators are multi-configuration; run these commands from Git Bash:

cmake --build build --config RelWithDebInfo --parallel
ctest --test-dir build -C RelWithDebInfo --output-on-failure

Generate only protobuf outputs when needed:

cmake --build build --target a2a_proto_codegen

Generated A2A headers are written under build/generated/a2a/v1/. Generated Google API annotation headers are written under build/generated/google/api/. Both sets are installed with the SDK.

Install CMake package artifacts

cmake --install build --prefix /tmp/a2a-cpp-install

On a Visual Studio build, also pass --config RelWithDebInfo.

The install tree includes public headers, generated protobuf headers, libraries, and CMake package files under ${CMAKE_INSTALL_LIBDIR}/cmake/a2a_cpp, commonly lib/cmake/a2a_cpp.

Contributor validation

For code changes in a Linux CI-compatible environment, run the canonical validation script before opening or updating a PR:

./scripts/verify_changes.sh

The script runs the same main validation categories as CI: formatting, configure/build, tests, and clang-tidy. It runs clang-format -i first and can modify tracked C and C++ files, so review git diff after it completes.

The current script assumes a Unix environment with nproc and a single-configuration build. On macOS or Windows, use the platform-specific configure, build, and test commands above and run the required formatting and clang-tidy checks separately.

For documentation-only mdBook changes, build the book:

mdbook build book

Quickstart: Build and Run Examples

The curated examples build app sources the same way downstream applications consume the SDK.

1. Install dependencies

Follow the platform instructions in Installation and Build. On Windows, run the repository helper from Git Bash before the example runner:

./scripts/install_build_deps.sh

2. Run the smallest end-to-end example

Linux or macOS:

./scripts/run_examples.sh build-example hello_agent

Windows Git Bash cleanup and rebuild:

rm -rf build-example-hello_agent
./scripts/run_examples.sh build-example hello_agent

The executable is written to build-example-hello_agent/a2a_example on single-configuration generators and to build-example-hello_agent/RelWithDebInfo/a2a_example.exe with Visual Studio.

hello_agent creates a minimal in-process client/server flow and exits deterministically.

3. Try transport-specific examples

./scripts/run_examples.sh build-example rest_server json_rpc_server grpc_server

These examples cover server transport setup and deterministic request handling across REST, JSON-RPC, and gRPC.

4. Try streaming, push, and auth examples

./scripts/run_examples.sh build-example streaming_client streaming_server push_notifications auth_policy_server

Use these when validating event streams, webhook configuration flows, or server-side auth metadata policy shapes. On Windows, the runner automatically forwards the vcpkg toolchain and locates the Visual Studio configuration output when VCPKG_ROOT is set.

5. Consume an installed SDK package

After installing the SDK into a prefix, build the same app source with find_package(a2a_cpp CONFIG REQUIRED):

cmake -S examples/installed_package_consumer -B build-installed-example \
  -DCMAKE_PREFIX_PATH=/tmp/a2a-cpp-install \
  -DA2A_EXAMPLE_APP=hello_agent
cmake --build build-installed-example --parallel
./build-installed-example/a2a_example

For Visual Studio, add --config RelWithDebInfo to the build and run build-installed-example/RelWithDebInfo/a2a_example.exe.

6. Validate your local checkout

./scripts/verify_changes.sh

For documentation-only edits, use mdbook build book instead of the full code validation flow.

Continue with a production tutorial

The programs under examples/apps/ are focused deterministic capability examples. The standalone projects under examples/tutorials/ are realistic multi-process applications: a CLI discovers a coordinator, which discovers and delegates to a specialist over HTTP+JSON. After hello_agent, run either job_application_assistant or customer_support_copilot with ./scripts/run_tutorials.sh; a streaming production tutorial is the planned next step.

Client Overview

Use a2a::client::A2AClient with a concrete ClientTransport to call A2A servers.

Client capabilities

  • SendMessage
  • GetTask
  • ListTasks
  • CancelTask
  • SendStreamingMessage
  • SubscribeTask
  • CreateTaskPushNotificationConfig
  • GetTaskPushNotificationConfig
  • ListTaskPushNotificationConfigs
  • DeleteTaskPushNotificationConfig
  • Client interceptors via ClientInterceptor
  • Per-call settings through CallOptions

Typical flow

  1. Fetch an Agent Card with DiscoveryClient.
  2. Select an endpoint with AgentCardResolver::SelectPreferredInterface.
  3. Construct HttpJsonTransport, JsonRpcTransport, or GrpcTransport.
  4. Create A2AClient with the transport.
  5. Invoke task, streaming, or push-notification APIs.
  6. Call Destroy() during shutdown when you need transport cleanup.

Default outbound HTTP

When libcurl is available and A2A_ENABLE_LIBCURL=ON, default constructors/factories can perform buffered outbound REST, JSON-RPC, and discovery calls. For tests, custom TLS policy, mTLS, retries, or embedded runtimes, inject your own requester/fetcher callbacks.

Runnable examples

  • examples/apps/hello_agent/main.cpp
  • examples/apps/simple_client/main.cpp
  • examples/apps/streaming_client/main.cpp
  • examples/apps/push_notifications/main.cpp

When libcurl support is enabled at configure time, the SDK provides a shared libcurl-backed outbound HTTP implementation for buffered REST, JSON-RPC, and Agent Card discovery calls. Use a2a::client::MakeDefaultHttpRequester(), a2a::client::MakeDefaultHttpFetcher(), HttpJsonTransport::CreateDefault(...), JsonRpcTransport::CreateDefault(...), or DiscoveryClient::CreateDefault(...) when you do not need to provide custom HTTP plumbing.

The callback-based constructors remain available for tests, embedded runtimes, custom TLS/mTLS policy, observability, retry logic, and other environments that need to control outbound HTTP execution. The default requester captures response headers, including A2A-Version, so client-side protocol-version validation continues to apply.

SSE streaming uses the same default libcurl outbound HTTP infrastructure as buffered calls. HttpJsonTransport::CreateDefault(...) and JsonRpcTransport::CreateDefault(...) configure production SSE requesters for SendStreamingMessage and SubscribeTask; injected requesters are still available for tests or custom HTTP stacks. With -DA2A_ENABLE_LIBCURL=OFF, injected requesters/fetchers continue to work while default outbound HTTP and SSE calls return a clear runtime error. gRPC and Protobuf remain mandatory build dependencies. On Windows, run ./scripts/install_build_deps.sh from Git Bash; the example runner then configures CMake through the vcpkg toolchain.

See task history and retries for duplicate handling and telemetry.

Sending Messages

A2AClient::SendMessage starts or continues a task by sending a protobuf lf::a2a::v1::SendMessageRequest through the configured transport.

Request construction guidance

  • Set a stable message.message_id for idempotency and diagnostics.
  • Let the server generate a task ID for new work unless you are intentionally continuing an existing task.
  • Attach push-notification config only when the target Agent Card advertises support and your server policy allows it.
  • Use CallOptions for per-call deadlines, metadata, or auth settings where supported by the transport.

Response handling

The response can contain immediate task state and output data. Persist task identifiers in logs/telemetry so later GetTask, CancelTask, streaming subscription, or push-notification calls can be correlated.

Failure paths to test

  • Network or HTTP/gRPC transport failure.
  • Serialization or protocol validation failure.
  • Auth policy rejection.
  • Unsupported operation or required extension mismatch.
  • Duplicate/retry behavior for repeated message IDs.

Discovery and Agent Cards

Discovery resolves server capabilities before constructing a client transport.

Public and extended cards

DiscoveryClient supports:

  • Fetch(base_url) for the standard Agent Card.
  • FetchExtendedAgentCard(base_url) for the extended Agent Card endpoint.

Fetched cards are cached for kDefaultDiscoveryCacheTtl (300 seconds) unless a different TTL is supplied.

Interface resolution

AgentCardResolver::SelectPreferredInterface(card, preferred) selects a ResolvedInterface for one of:

  • PreferredTransport::kRest
  • PreferredTransport::kJsonRpc
  • PreferredTransport::kGrpc

The result includes the transport, URL, security requirements, and security schemes needed to configure a client.

Operational guidance

  • Validate and log the selected endpoint during startup.
  • Prefer an explicit fallback order when cards advertise multiple transports.
  • Treat discovery metadata as untrusted input until validated.
  • Refresh cached cards after deployment or capability changes.
  • include/a2a/client/discovery.h
  • include/a2a/core/agent_card/agent_card_provider.h
  • include/a2a/server/agent_card/agent_card_serializer.h

Get Task and List Tasks

GetTask retrieves a single task by ID. ListTasks returns a paginated list of tasks through the client abstraction and supported transports.

GetTask flow

  1. Store the task ID from SendMessage or a stream event.
  2. Build lf::a2a::v1::GetTaskRequest.
  3. Call A2AClient::GetTask.
  4. Interpret task status, artifacts, and history according to your application policy.

ListTasks flow

a2a::client::ListTasksRequest contains:

  • page_size
  • page_token

In v0.6.0 development, the response includes task values plus an opaque, versioned next_page_token. Tasks are ordered by last storage update, newest first, with task ID as the tie-breaker. History/artifact changes also affect this order. Start with an empty token; legacy numeric offsets are rejected. Concurrent changes can move tasks ahead of the cursor, so restart a traversal to see the latest changes. See the ListTasks cursor contract for consistency, permissions, exact-count costs and PostgreSQL migration details.

An omitted page size requests the protocol default of at most 50 tasks. Explicit page sizes must be between 1 and 100. Continue until next_page_token is empty:

a2a::client::ListTasksRequest request{.page_size = 50};
do {
  const auto page = client.ListTasks(request);
  if (!page.ok()) {
    return page.error();
  }
  for (const auto& task : page.value().tasks) {
    ProcessTask(task);
  }
  request.page_token = page.value().next_page_token;
} while (!request.page_token.empty());

Keep pages bounded (normally no more than 100 tasks) and request a small history_length, often 0 or 1, unless deeper history is required. CPU cost grows with both the returned task count and retained history. Oversized results also increase protobuf allocations and copies, response memory, serialized payload size, transport latency, and timeout risk. In-memory stores hold their shared read lock longer while materializing a result, so writes may wait longer. Full history projection can dominate the list operation.

Operational guidance

  • Use bounded polling with backoff when not using streaming.
  • Enforce authorization checks on server-side task visibility.
  • Avoid exposing full task history to clients that do not need it.

Cancel Task

A2AClient::CancelTask asks the server to cancel in-flight work.

When to use cancellation

  • A user aborts an operation.
  • A deadline expires upstream.
  • Supervising logic needs to reclaim compute or queue capacity.

Semantics

Cancellation is best-effort. A task can complete before the cancellation request is processed, and servers can reject cancellation for completed, unknown, or policy-protected tasks.

  • Make higher-level cancellation idempotent.
  • Return or display the latest task state after cancellation attempts.
  • Preserve enough audit data to explain whether the task was canceled, completed, or rejected.

Server Overview

Server integrations implement a2a::server::AgentExecutor and route protocol requests through Dispatcher plus one or more transports.

Server capabilities

  • REST server transport.
  • JSON-RPC server transport.
  • gRPC service transport.
  • Public and extended Agent Card dispatch when a provider is installed.
  • Required extension validation.
  • Server interceptors.
  • Streaming through ServerStreamSession.
  • Task lifecycle helpers, in-memory task store, and optional PostgreSQL stores.
  • Push-notification config CRUD and delivery service abstractions.

Core flow

  1. Implement an executor for task and message behavior.
  2. Create a Dispatcher with the executor and optional Agent Card provider/interceptors.
  3. Attach REST, JSON-RPC, or gRPC transport adapters.
  4. Convert inbound framework requests into transport calls.
  5. Return structured protocol errors instead of transport-specific ad hoc errors.

Task IDs

When an incoming message does not carry message.task_id, the SDK service layer can generate server-side task IDs using UUIDv7. UUIDv7 is sortable and operationally useful, but it leaks approximate creation time. Inject a custom task ID generator if your deployment needs opaque identifiers.

Custom Executors

Implement a2a::server::AgentExecutor to define application behavior.

Required methods

Executors implement task/message operations including:

  • SendMessage
  • SendStreamingMessage
  • GetTask
  • ListTasks
  • CancelTask

Push-notification config methods have default PushNotificationNotSupported behavior and should be overridden only when the server actually supports them.

Request context

Every executor method receives RequestContext. Use it for auth metadata, transport metadata, and request-scoped policy decisions. Treat metadata as untrusted until validated.

Design guidance

  • Keep executor methods small and deterministic.
  • Validate inputs at the boundary.
  • Return a2a::core::Result<T> with structured errors.
  • Avoid shared mutable state unless synchronized and documented.
  • Unit-test executor behavior separately from transport mapping.

REST Server Transport

RestServerTransport maps HTTP+JSON requests onto dispatcher operations.

Responsibilities

  • Validate HTTP method, path, and content type.
  • Parse JSON request bodies into protobuf messages.
  • Populate RequestContext, including auth metadata.
  • Serialize protocol responses and errors back to HTTP responses.

Supported operation shape

REST transport covers core task lifecycle operations, streaming-compatible endpoints where wired by the hosting environment, Agent Card routes, and push-notification config APIs exposed by the dispatcher/executor.

Hosting guidance

The SDK provides protocol mapping, not a full production web server framework. In production, place it behind an HTTP runtime that owns TLS, connection limits, request-size limits, access logs, and graceful shutdown.

Example

See examples/apps/rest_server/main.cpp.

JSON-RPC Server Transport

JsonRpcServerTransport maps JSON-RPC 2.0 method calls to dispatcher operations.

Responsibilities

  • Validate the jsonrpc, id, method, and params envelope fields.
  • Route supported A2A methods to the dispatcher.
  • Return JSON-RPC error objects for invalid requests, unknown methods, and executor failures.
  • Preserve request metadata for auth and audit policy.

Use cases

Use JSON-RPC when method-based routing is easier to integrate than resource-oriented REST paths or when another system already standardizes on JSON-RPC 2.0.

Example

See examples/apps/json_rpc_server/main.cpp.

Storage backends

The SDK storage layer is pluggable. TaskLifecycleService uses the TaskStore interface and PushNotificationService uses the PushNotificationStore interface, so applications can provide in-memory stores for development or PostgreSQL-backed stores for local production-style testing.

In-memory stores

Use InMemoryStoreFactory for examples, tests, and single-process development:

a2a::server::stores::InMemoryStoreFactory factory;
auto stores = factory.CreateStoreBundle();
a2a::examples::ExampleExecutor executor({
    .task_store = stores.value().task_store.get(),
    .push_store = stores.value().push_store.get(),
});

In-memory stores do not persist data, do not coordinate across processes, and should not be used as durable production storage.

PostgreSQL build flag

PostgreSQL support is optional and is disabled by default. A default build does not require PostgreSQL, libpq, or libpqxx:

cmake -S . -B build
cmake --build build

Enable the PostgreSQL store target with:

cmake -S . -B build-postgres -DA2A_ENABLE_POSTGRES_STORE=ON -DA2A_ENABLE_TESTING=ON
cmake --build build-postgres

When enabled, CMake builds a2a::store_postgres. Applications that instantiate PostgreSQL stores should link this target in addition to the normal server target.

Local Docker PostgreSQL

Start a local PostgreSQL 16 database:

docker compose -f dev/local/docker-compose.postgres.yml up -d

Equivalent helper script:

./dev/local/postgres_up.sh

Run a PostgreSQL-enabled build and test suite:

cmake -S . -B build-postgres -DA2A_ENABLE_POSTGRES_STORE=ON -DA2A_ENABLE_TESTING=ON
cmake --build build-postgres
A2A_TEST_POSTGRES_DSN="postgresql://a2a:a2a@127.0.0.1:5432/a2a" ctest --test-dir build-postgres --output-on-failure

Stop the database when done:

docker compose -f dev/local/docker-compose.postgres.yml down

Equivalent helper script:

./dev/local/postgres_down.sh

See guide for all local SDK development helper commands.

Example executor injection

The ExampleExecutor below is repository example/test support, not an installed SDK executor. Applications inject these stores into their own AgentExecutor. Keep the store bundle alive while executors, dispatchers or streams use it.

ExampleExecutor owns default in-memory stores when no options are supplied, preserving the existing examples. External callers can inject any implementation of the store interfaces:

a2a::server::stores::PostgresStoreFactory factory({
    .connection_string = "postgresql://a2a:a2a@127.0.0.1:5432/a2a",
    .schema = "public",
    .auto_create_schema = true,
    .connection_pool_size = 8,
});
auto stores = factory.CreateStoreBundle();

a2a::examples::ExampleExecutor executor({
    .task_store = stores.value().task_store.get(),
    .push_store = stores.value().push_store.get(),
});

connection_pool_size controls the number of synchronous libpq connections available to PostgreSQL store operations. It defaults to 4 for backward compatibility and must be greater than zero. Size it for the expected number of concurrent database operations while staying within PostgreSQL’s connection limit (including connections used by other application instances and tools). Task and push-notification stores returned by CreateStoreBundle() share this single configured pool; separately created stores each own a separate pool. Storage matching uses libpq’s active connection target (selected host, resolved server address, active port, and database) plus the configured target_session_attrs value and schema. Passwords and raw connection strings are not part of storage identity. Exact coordinate equality confirms local authority; a different database or schema confirms external authority. Other endpoint differences are uncertain because aliases, DNS, port changes, and multi-host failover can make textual differences insufficient evidence of external ownership. For separately constructed stores, PostgresStoreOptions::storage_authority_id can make that relationship explicit: matching non-empty IDs prove local authority, different non-empty IDs prove external authority, and a one-sided ID remains uncertain. Database or schema differences still override the ID and remain external. Treat the ID as a stable, non-secret deployment identifier rather than a connection credential. It is an authority assertion: incorrect IDs can change provenance and cleanup semantics. Equivalent URI and keyword DSNs continue to take the local path when they resolve to the same active server target.

The effective PostgreSQL role is tracked as part of each pool’s connection identity. This identity is used to keep connections inside a pool consistent; it is not used to prove that two independently constructed pools have equivalent session-policy context. PostgreSQL row-security policies can consult arbitrary session settings supplied through connection options or changed at runtime, so matching endpoint/schema/role metadata is insufficient for that proof. Consequently, the one-command task-aware list shortcut is used only when the task and push stores share the exact PostgresConnectionPool and resolve to the same local storage authority, as they do when created by PostgresStoreFactory::CreateStoreBundle(). Separately constructed stores perform the authoritative task-store lookup first even when their DSNs and roles otherwise appear equivalent. Applications must not leave pooled connections with out-of-band session state such as SET ROLE or custom policy GUCs.

Task-aware PostgreSQL behavior

PostgresPushNotificationStore implements the optional task-aware store capability used by PushNotificationService for create and list operations. The final PostgreSQL paths are:

  • Same storage, create/update: one push-store pool acquisition and one PQexecParams command. The statement invokes the schema-qualified SECURITY DEFINER task-lock helper, takes a shared transaction-scoped advisory lock derived from the schema-qualified task table and complete task ID, validates task existence, and performs INSERT ... ON CONFLICT DO UPDATE ... RETURNING 1 in the same statement. Task deletion takes the matching exclusive advisory lock in a BEFORE DELETE trigger. There is no preliminary task_get, explicit multi-command transaction, revalidation, or compensating cleanup. A missing task returns TaskNotFound; a concurrent delete cannot leave a locally owned orphan. The local task-aware path rejects repeatable-read and serializable transaction isolation before locking because their transaction-scoped snapshots can remain stale after a concurrent delete commits. Under PostgreSQL read-committed semantics, the VOLATILE helper rechecks task existence with a fresh snapshot after any advisory-lock wait. Equal task IDs in different schemas use different advisory keys. Hash collisions can still serialize unrelated task IDs; all task and push data access continues to use the original task ID.
  • External authority, create/update: the supplied TaskStore remains authoritative. The service performs its task lookup first and then writes an externally owned push row (local_postgres_task=FALSE). A different database or schema proves external authority. An uncertain PostgreSQL identity is never treated as external and is rejected before the push write. Direct PushNotificationStore::CreateOrUpdate calls have no authoritative TaskStore, so PostgreSQL keeps them on this external-provenance path.
  • Get: GetConfig remains push-store-only. PostgreSQL uses one statement and one push-store acquisition to distinguish a missing config from an absent push-config collection without consulting the authoritative TaskStore.
  • List: task and push stores that share one connection pool and local storage authority use one combined PostgreSQL statement for task existence, count, and page rows. With separate pools, the authoritative task lookup runs first and the push store then executes one combined count/page statement. This fallback is intentional even when endpoint and role metadata match, because independent sessions may carry different RLS policy context.

For the normal PostgresStoreFactory::CreateStoreBundle() layout, create, get, and list therefore use one PostgreSQL command and one pool acquisition per successful public operation. PushConfig_CreateMany with fan-out eight performs eight independent create commands, not sixteen; the task existence check is part of each atomic create statement. Separately constructed stores that resolve to the same storage coordinates retain the same one-command create path. Their list calls use the task-first fallback unless they explicitly share one pool and local storage authority.

When auto_create_schema=true, schema initialization creates or upgrades the task/push tables, provenance column, shared push-lock helper, exclusive task-delete lock helper and BEFORE DELETE trigger, cleanup helper and AFTER DELETE/AFTER TRUNCATE triggers, sequences, and task indexes, and removes the legacy push-to-task foreign key. During the issue #206 write-saturation experiment, initialization also drops both push secondary indexes: idx_a2a_push_configs_task and idx_a2a_push_configs_created_sequence. The primary key (task_id, config_id) remains available for task-prefix filtering; list queries explicitly sort by created_sequence ASC to preserve deterministic creation order and pagination semantics. The migration objects are installed transactionally and the task-aware-push-config-v4 markers are written last.

Externally managed PostgreSQL schemas

When auto_create_schema=false, the push-notification store always validates the push table’s provenance column and rejects a legacy push-to-task foreign key. The local task-aware objects are an optional capability: if the push-lock helper, task-delete lock helper and trigger, cleanup helper, and cleanup trigger are all absent, construction succeeds for a push-only store paired with an external authoritative TaskStore. Attempting to pair that store with a local PostgreSQL task store fails before the push write with an actionable task-aware-push-config-v4 migration error. Capability detection happens during store construction; request paths do not query the catalogs.

If any task-aware helper or trigger is present, construction requires the whole task-aware-push-config-v4 migration and rejects partial or stale installations. Validation covers all SECURITY DEFINER helper implementations and migration markers, their owners’ required privileges, absence of PUBLIC EXECUTE, exact BEFORE DELETE advisory-lock and AFTER DELETE/AFTER TRUNCATE cleanup trigger wiring without a WHEN clause, and the cleanup owner’s ability to bypass any row-level security enabled on the push-config table. Function-body checks preserve the exact case of quoted schema/table identifiers so a similarly named object in another case-sensitive schema cannot satisfy validation.

Apply the following migration before using local PostgreSQL task-aware create/update. This example uses the public schema and an SDK database role named a2a_sdk; replace both names for your deployment. Grant the lock helper only to SDK roles authorized to create push notification configurations. The invoking push-store role needs task-table SELECT plus lock-helper EXECUTE, but it does not need task-table UPDATE; the helper’s owner needs schema USAGE and task-table SELECT. Push-only roles paired with an external authoritative TaskStore do not need task-table access or lock-helper execution. The push store validates the invoking role’s lock-helper EXECUTE privilege only when CreateOrUpdateForTask selects the local PostgreSQL atomic path. PostgreSQL row-level security on the task table is allowed for external-authority/push-only use, but the local task-aware create path rejects it explicitly because a SECURITY DEFINER lock must not bypass caller row policies. If row-level security is enabled on the push-config table, managed-schema validation also requires the cleanup helper owner to bypass it: a table owner is sufficient when FORCE ROW LEVEL SECURITY is not enabled, while BYPASSRLS and superuser roles always bypass it. This prevents task deletion from silently leaving locally owned callback configurations behind.

BEGIN;

ALTER TABLE public.a2a_push_notification_configs
  ADD COLUMN IF NOT EXISTS local_postgres_task BOOLEAN NOT NULL DEFAULT FALSE;

ALTER TABLE public.a2a_push_notification_configs
  DROP CONSTRAINT IF EXISTS a2a_push_configs_task_fk;

DROP INDEX IF EXISTS public.idx_a2a_push_configs_task;
DROP INDEX IF EXISTS public.idx_a2a_push_configs_created_sequence;

CREATE OR REPLACE FUNCTION public.a2a_lock_task_for_push_config(requested_task_id TEXT)
RETURNS BOOLEAN
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog
AS $a2a$
DECLARE
  caller_role NAME;
  lock_key BIGINT;
BEGIN
  IF pg_catalog.current_setting('transaction_isolation') IN ('repeatable read', 'serializable') THEN
    RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE =
      'PostgreSQL task-aware push configuration requires read-committed transaction isolation';
  END IF;
  lock_key := pg_catalog.hashtextextended(
    requested_task_id,
    pg_catalog.hashtextextended('public.a2a_tasks', 0));
  IF NOT pg_catalog.pg_try_advisory_xact_lock_shared(lock_key) THEN
    PERFORM pg_catalog.pg_advisory_xact_lock_shared(lock_key);
  END IF;
  caller_role := NULLIF(pg_catalog.current_setting('role', true), 'none');
  IF caller_role IS NULL THEN
    caller_role := session_user;
  END IF;
  IF EXISTS (
    SELECT 1 FROM pg_catalog.pg_class
    WHERE oid = pg_catalog.to_regclass('public.a2a_tasks') AND relrowsecurity
  ) THEN
    RAISE EXCEPTION USING ERRCODE = '0A000', MESSAGE =
      'PostgreSQL task-aware push configuration does not support row-level security on a2a_tasks';
  END IF;
  IF NOT pg_catalog.has_table_privilege(caller_role, 'public.a2a_tasks', 'SELECT') THEN
    RAISE EXCEPTION USING ERRCODE = '42501', MESSAGE =
      'PostgreSQL push store role requires SELECT on a2a_tasks for task-aware creation';
  END IF;
  PERFORM 1
  FROM public.a2a_tasks
  WHERE id = requested_task_id;
  RETURN FOUND;
END
$a2a$;

REVOKE ALL ON FUNCTION public.a2a_lock_task_for_push_config(TEXT) FROM PUBLIC;
GRANT SELECT ON public.a2a_tasks TO a2a_sdk;
GRANT EXECUTE ON FUNCTION public.a2a_lock_task_for_push_config(TEXT) TO a2a_sdk;

CREATE OR REPLACE FUNCTION public.a2a_lock_task_for_delete()
RETURNS TRIGGER
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog
AS $a2a$
BEGIN
  PERFORM pg_catalog.pg_advisory_xact_lock(
    pg_catalog.hashtextextended(
      OLD.id,
      pg_catalog.hashtextextended('public.a2a_tasks', 0)));
  RETURN OLD;
END
$a2a$;

REVOKE ALL ON FUNCTION public.a2a_lock_task_for_delete() FROM PUBLIC;

DROP TRIGGER IF EXISTS a2a_lock_task_for_delete_trigger ON public.a2a_tasks;
CREATE TRIGGER a2a_lock_task_for_delete_trigger
BEFORE DELETE ON public.a2a_tasks
FOR EACH ROW
EXECUTE FUNCTION public.a2a_lock_task_for_delete();

CREATE OR REPLACE FUNCTION public.a2a_delete_task_push_configs()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog
AS $a2a$
BEGIN
  IF TG_OP = 'TRUNCATE' THEN
    IF pg_catalog.current_setting('transaction_isolation') IN
        ('repeatable read', 'serializable') THEN
      RAISE EXCEPTION USING
        ERRCODE = '0A000',
        MESSAGE = 'PostgreSQL task truncation cleanup requires read-committed transaction isolation';
    END IF;
    DELETE FROM public.a2a_push_notification_configs
    WHERE local_postgres_task;
    RETURN NULL;
  END IF;
  DELETE FROM public.a2a_push_notification_configs
  WHERE task_id = OLD.id AND local_postgres_task;
  RETURN OLD;
END
$a2a$;

REVOKE ALL ON FUNCTION public.a2a_delete_task_push_configs() FROM PUBLIC;

DROP TRIGGER IF EXISTS a2a_delete_task_push_configs_trigger ON public.a2a_tasks;
CREATE TRIGGER a2a_delete_task_push_configs_trigger
AFTER DELETE ON public.a2a_tasks
FOR EACH ROW
EXECUTE FUNCTION public.a2a_delete_task_push_configs();

DROP TRIGGER IF EXISTS a2a_truncate_task_push_configs_trigger ON public.a2a_tasks;
CREATE TRIGGER a2a_truncate_task_push_configs_trigger
AFTER TRUNCATE ON public.a2a_tasks
FOR EACH STATEMENT
EXECUTE FUNCTION public.a2a_delete_task_push_configs();

COMMENT ON FUNCTION public.a2a_lock_task_for_delete()
  IS 'task-aware-push-config-v4';

COMMENT ON FUNCTION public.a2a_delete_task_push_configs()
  IS 'task-aware-push-config-v4';

COMMENT ON FUNCTION public.a2a_lock_task_for_push_config(TEXT)
  IS 'task-aware-push-config-v4';

COMMIT;

The statement-level truncate trigger deletes every locally owned push configuration in the same transaction as a direct TRUNCATE public.a2a_tasks. It rejects repeatable-read and serializable transactions because cleanup under a stale transaction snapshot could miss a concurrently committed local push configuration. Externally owned rows (local_postgres_task=FALSE) remain available because their authoritative task storage is outside this table. TRUNCATE ... CASCADE must include the push-config table only when the operator intentionally wants to remove those externally owned rows too.

The migration markers are written last inside the transaction, so a partial migration is never accepted. Existing push configurations are marked as externally owned by the new column’s FALSE default. The owner of a2a_lock_task_for_push_config(TEXT) must have schema USAGE plus SELECT on a2a_tasks. The owner of a2a_lock_task_for_delete() needs schema USAGE; it locks only the advisory key derived from OLD.id. The owner of a2a_delete_task_push_configs() must have schema USAGE plus SELECT and DELETE on the push-config table. These are SECURITY DEFINER owner requirements, not privileges that every push-store role must receive.

Sensitive push notification data

Push notification configs can include delivery URLs, tokens, and authentication metadata. Treat stored TaskPushNotificationConfig payloads as sensitive operational data. This SDK stores protobuf payloads in PostgreSQL but does not implement encryption at rest; use database-level encryption, access control, backups, and audit logging appropriate for your environment.

Task listing

See ListTasks cursor pagination for the v0.6.0 development contract: last-update ordering, legacy-token compatibility, concurrency behavior, count costs and PostgreSQL migration SQL.

ListTasks cursor pagination

This contract targets v0.6.0 development. Released v0.5.2 retains numeric continuation tokens and creation-order listing; see the release notes.

The SDK stores list tasks by storage last-update time, descending, then task ID in descending byte order. The time is independent of TaskStatus.timestamp. Every successful create, unconditional/conditional replacement (including metadata, status, history or artifacts), cancellation, and history append advances it. Rejected writes, revision conflicts, rejected cancellations and deduplicated history appends do not change it. Each task’s time advances by at least one microsecond, even if the wall clock moves backward. Equal times across tasks use the ID tie-breaker. If a custom in-memory clock reaches the maximum signed 64-bit timestamp, further mutations of that task return an internal error without changing its contents, revision or cursor position. Deduplicated history appends remain successful because they do not mutate the task.

Start with an empty page_token. Copy the returned next_page_token unchanged into the next request; stop when it is empty. Tokens are opaque, versioned v1 boundaries, portable between JSON-RPC, HTTP+JSON and gRPC for the same store. They are neither credentials nor encrypted data. They never require resolving the boundary task or reveal whether that task currently exists or is accessible. Only a returned, authorized task supplies a response token. Cursor encoding preserves every byte of nonempty task IDs accepted by the store, including embedded NUL bytes in the in-memory store.

Compatibility

Numeric offset tokens (including 0) are rejected as invalid arguments. Restart an old pagination sequence with an empty token. Ordering intentionally changes from creation order. The public client loop in Get Task and List Tasks already follows returned tokens and requires no arithmetic. Do not manufacture, increment, decode, persist as an application identifier, or depend on a token’s representation. Unsupported versions, invalid encodings, empty IDs and out-of-range times use the same generic validation error regardless of the store contents or caller scope.

Keep the same caller and filters for a traversal. Changing them applies the existing boundary to the new visible result set; it does not grant access to the previous caller’s tasks. An empty page is valid after updates or permission changes. It has an empty continuation token, even when the current total is nonzero.

Consistency and permissions

Pagination is a live traversal, not a snapshot spanning requests. Inserts and updates ahead of the boundary are seen on a fresh traversal. A task updated or canceled between pages can move ahead of the boundary and be omitted from the rest of that traversal; already traversed tasks do not move backward and repeat. Equal-time inserts after the ID boundary can appear in subsequent pages.

An in-memory store call holds one shared lock. A PostgreSQL store call reads its count and page in one repeatable-read, read-only transaction. The authorization dispatcher narrows store queries with ScopeTaskList, checks CanAccessTask before counting and page selection, then re-reads and rechecks selected tasks before projecting them. A revocation during that final read returns the same not-found error as an inaccessible task. Applications own policy synchronization. Authorization scans use bounded batches and can observe changes between batches; their counts represent authorized observations during that scan, not a global snapshot of a changing application policy. Totals exclude inaccessible tasks and are independent of the cursor boundary.

Costs and custom stores

In-memory writes maintain an ordered index in O(log n). An unfiltered page seeks in O(log n) and visits only page-size plus one entries. Filtered exact counts still inspect all stored tasks. PostgreSQL uses (updated_at DESC, id COLLATE "C" DESC) and context-prefixed ordering indexes; SQL applies filters before its cursor predicate and bounded LIMIT. Both keys descend so a composite row comparison can seek directly through equal timestamps. Exact counts still scan matching rows/index entries. These indexes add write and storage cost.

Application-defined authorization can require inspecting every matching task. The dispatcher retains one batch (at most 100 tasks) and one page of IDs, disables redundant store counts, and loads full response projections only for selected IDs. Policies may request lightweight projections only when those fields suffice for authorization. Complex policies may therefore decode all matching task blobs.

Custom TaskStore implementations used with dispatcher security must return ListTasksResponse.task_cursors aligned with tasks, containing storage update times and IDs, and honor the same order/continuation contract. Missing boundaries fail closed. The boundaries and ListTasksRequest.include_total_size flag are internal store/dispatcher fields and are never transmitted on the wire. Set include_total_size=false to skip redundant counts during bounded internal scans.

SDK-managed PostgreSQL schemas install the default and ordering indexes on startup. Externally managed schemas must apply the equivalent migration before deploying:

ALTER TABLE public.a2a_tasks ALTER COLUMN updated_at SET DEFAULT clock_timestamp();
CREATE INDEX IF NOT EXISTS idx_a2a_tasks_updated
  ON public.a2a_tasks (updated_at DESC, id COLLATE "C" DESC);
CREATE INDEX IF NOT EXISTS idx_a2a_tasks_context_updated
  ON public.a2a_tasks (context_id, updated_at DESC, id COLLATE "C" DESC);

Existing rows retain their persisted updated_at; no creation timestamps are invented. All writers must update updated_at monotonically with task mutations. Push-notification configuration pagination is independent and retains its contract.

SDK idempotency and task-history deduplication specification

Duplicate definition

A task-history append is considered a duplicate when it matches an existing history entry according to the selected HistoryAppendPolicy:

  • kNoDedup: no duplicate detection; every request is appended.
  • kDedupByMessageId: duplicate only when both message_id and the message fingerprint match.
  • kDedupByIdOrFingerprint: with a message_id, same behavior as kDedupByMessageId; without a message_id, duplicate is determined by fingerprint only.

Fingerprint equality is evaluated on task_id, context_id, role, parts_size, and serialized parts content.

Ignored vs appended behavior

  • Ignored (dropped): only when duplicate conditions above are met for the active policy.
  • Appended:
    • always for kNoDedup;
    • for kDedupByMessageId when message_id is missing, or when payload differs;
    • for kDedupByIdOrFingerprint when neither id+fingerprint nor fingerprint-only duplicate match exists.

History order is strict append order for accepted entries. Retries that are accepted are appended at the end (no backfilling/reordering).

Missing message_id

For idempotent retry behavior across transports, clients should set message_id consistently per logical message.

When message_id is missing:

  • kDedupByMessageId cannot dedupe and the request is appended.
  • kDedupByIdOrFingerprint attempts fingerprint-based dedupe.

Structured telemetry for dedupe drops

InMemoryTaskStore maintains counters via GetHistoryTelemetrySnapshot():

  • dedupe_dropped_total
  • dedupe_dropped_by_message_id_and_fingerprint
  • dedupe_dropped_by_fingerprint_without_message_id

Operators can also provide InMemoryTaskStore::HistoryTelemetrySink to consume structured HistoryDedupeEvent records (task_id, message_id, policy, reason) for retry debugging.

Push Notifications

The SDK includes task push-notification configuration APIs and server-side delivery abstractions.

Client API surface

A2AClient exposes:

  • CreateTaskPushNotificationConfig
  • GetTaskPushNotificationConfig
  • ListTaskPushNotificationConfigs
  • DeleteTaskPushNotificationConfig

Use these only when the target Agent Card and server policy indicate push-notification support.

Server components

  • PushNotificationService coordinates stored configs and delivery.
  • PushNotificationStore persists webhook configs.
  • PushNotificationDeliveryClient abstracts outbound delivery.
  • HttpPushNotificationDeliveryClient provides a simple libcurl-backed synchronous delivery path when libcurl support is enabled.
  1. Persist task state in your TaskStore or TaskLifecycleService.
  2. Register inline configs from SendMessageRequest when present.
  3. Call NotifyTaskUpdated(task) after status changes.
  4. Propagate delivery failures instead of silently dropping them.
  5. Override push-config CRUD executor methods only when push support is fully configured.

Production guidance

For production, prefer a durable queued delivery client with retries, backoff, webhook URL validation, SSRF controls, credential protection, and delivery telemetry. Keep TLS policy at least as strong as the built-in delivery client, which requires TLS 1.2 or newer for HTTPS URLs.

Example

See examples/apps/push_notifications/main.cpp.

Use a2a::server::PushNotificationService when an executor supports task push-notification configs. Wire it with the same TaskStore that owns task state, a PushNotificationStore for webhook configs, and a PushNotificationDeliveryClient for outbound delivery.

Recommended executor flow:

  1. Persist the task state with TaskLifecycleService or your TaskStore.
  2. Call RegisterInlineConfigIfPresent(request, resolved_task_id) for SendMessageRequest values that include an inline push config.
  3. Call NotifyTaskUpdated(task) after each task status update and propagate the returned Result<void> to the caller. The service now fails the request path when delivery returns an error, reports an error message in PushDeliveryResult, or reports a non-2xx HTTP status.
  4. Forward create/get/list/delete push-config RPCs to CreateConfig, GetConfig, ListConfigs, and DeleteConfig.
  5. Advertise push support in the Agent Card only after the store and delivery client are configured.

The built-in HttpPushNotificationDeliveryClient is synchronous and intended for local examples, tests, and simple deployments. Production servers should usually inject a durable queued sender with retries, backoff, webhook URL validation, credential protection, SSRF controls, and delivery telemetry. See examples/apps/push_notifications/main.cpp for a focused service-level example and tests/support/example_support/example_support.h for executor wiring.

Built-in HTTP delivery requirements

When libcurl support is enabled, HttpPushNotificationDeliveryClient uses the SDK shared libcurl-backed outbound HTTP client for webhook delivery. SDK users that enable the built-in client must provide a libcurl build with HTTPS support and a platform trust store (or equivalent libcurl TLS backend configuration) so production https:// webhook URLs can be verified.

For security and interoperability, the built-in client:

  • accepts http:// and https:// webhook URLs, with TLS used for https:// URLs;
  • sets libcurl’s minimum TLS version to TLS 1.2, allowing TLS 1.2 or newer only;
  • supports HTTP/1.1, HTTP/2.0, and HTTP/3.0 request configuration; and
  • rejects HTTP/1.0 configuration instead of downgrading to it.

The default push-delivery preference is HTTP/2.0 with HTTP/1.1 fallback. Keep custom delivery clients at the same or stronger TLS baseline.

The shared outbound HTTP implementation lives outside the server namespace and is reused by client REST, JSON-RPC, discovery, and push-notification delivery paths. Custom PushNotificationDeliveryClient implementations can still be injected for queues, retries, policy enforcement, or alternate HTTP stacks.

Builds configured with -DA2A_ENABLE_LIBCURL=OFF keep server transports and custom delivery clients available, but the built-in HttpPushNotificationDeliveryClient cannot perform outbound webhook calls and reports that libcurl support is disabled.

Client and server interceptor hooks

This repository exposes transport-agnostic interceptors at two layers:

  • a2a::client::A2AClient interceptors in include/a2a/client/client.h
  • a2a::server::Dispatcher interceptors in include/a2a/server/server_interceptor.h

Client hook contract

Use ClientInterceptor to observe calls made through A2AClient.

  • BeforeCall runs in registration order.
  • AfterCall runs in reverse registration order.
  • Hooks execute on the caller thread of each A2AClient method.
  • Hooks must be non-blocking and should not throw exceptions.
  • Interceptors observe call metadata through ClientCallContext:
    • operation name (for example GetTask or ListTasks)
    • the CallOptions object used for the invocation
  • Result state is provided through ClientCallResult:
    • ok == true for success
    • ok == false and error populated for failures

A2AClient::Destroy() provides explicit lifecycle shutdown. It invokes transport shutdown and clears the transport pointer to prevent further calls.

Server hook contract

Use ServerInterceptor to observe dispatcher request handling.

  • BeforeDispatch runs in registration order before invoking AgentExecutor.
  • AfterDispatch runs in reverse registration order after request completion.
  • If a BeforeDispatch hook returns an error, executor dispatch is skipped and AfterDispatch hooks are still invoked with the failure result.
  • Hooks execute on the thread that calls Dispatcher::Dispatch.
  • Hooks may read and mutate RequestContext; changes are visible to downstream interceptors and executor logic.

Thread-safety guarantees

  • Interceptor registration is synchronized:
    • client: internal mutex in A2AClient
    • server: shared mutex in Dispatcher
  • Dispatch/call execution reads a stable interceptor snapshot order within a call.
  • No global mutable state is used in interceptor plumbing.

Design guidance

  • Keep interceptors deterministic and low-latency.
  • Avoid logging secrets or raw credential values.
  • Use structured errors so transports can map failures consistently.
  • Prefer composition: keep business behavior in AgentExecutor and cross-cutting behavior in interceptors.

Transports Overview

The SDK separates protocol operations from transport adapters. Applications choose the transport that best matches their deployment boundary and interoperability needs.

Available transports

  • REST: HTTP+JSON resource-oriented integration for clients and servers.
  • JSON-RPC: JSON-RPC 2.0 method dispatch over HTTP-style request handling.
  • gRPC: protobuf/gRPC service integration with unary and streaming RPCs.

Choosing a transport

  • Choose REST when your platform already standardizes on HTTP routing, gateways, or resource-style APIs.
  • Choose JSON-RPC when method-style dispatch is easier to interoperate with or proxy.
  • Choose gRPC when you want protobuf-native contracts, gRPC streaming, or a service mesh that already supports gRPC well.

Shared operational concerns

Regardless of transport, define these policies explicitly:

  • Authentication and authorization boundaries.
  • Protocol version and required-extension handling.
  • Request deadlines and payload limits.
  • Retry and idempotency behavior.
  • Telemetry, audit logs, and stable task/request identifiers.

REST Transport

REST is the HTTP+JSON transport path for clients and servers.

Client side

Use HttpJsonTransport with A2AClient. When libcurl is enabled and found, default outbound buffered HTTP can be used. Otherwise inject an HttpRequester implementation.

Server side

Use RestServerTransport to translate inbound framework requests into dispatcher calls.

Operational considerations

  • Enforce TLS and auth policy at your edge or hosting layer.
  • Set explicit request deadlines and payload limits.
  • Log stable task IDs and request IDs.
  • Validate protocol version headers where required.
  • Prefer injected requesters for custom retry, proxy, mTLS, or observability policy.

JSON-RPC Transport

JSON-RPC transport supports A2A method dispatch over JSON-RPC 2.0 envelopes.

Client side

Use JsonRpcTransport with A2AClient. Default buffered outbound HTTP is available when libcurl is enabled and found; otherwise inject a requester.

Server side

Use JsonRpcServerTransport to decode envelopes, dispatch operations, and encode JSON-RPC responses.

Operational considerations

  • Validate envelope fields strictly.
  • Preserve client-provided request IDs in responses.
  • Map structured SDK errors to consistent JSON-RPC error responses.
  • Include auth metadata in RequestContext only after policy validation.

gRPC Transport

gRPC support is first-class for client and server integrations.

Client side

Use a2a::client::GrpcTransport with a resolved interface and either:

  • a std::shared_ptr<grpc::Channel> for real gRPC calls, or
  • a custom GrpcTransport::RpcClient for tests and embedded adapters.

The transport supports unary task operations, streaming send, task subscription, and push-notification config lifecycle calls.

Server side

a2a::server::GrpcServerTransport implements lf::a2a::v1::A2AService::Service and routes RPCs to the dispatcher.

It supports:

  • SendMessage
  • SendStreamingMessage
  • GetTask
  • ListTasks
  • CancelTask
  • SubscribeToTask
  • Push-notification config RPCs
  • GetExtendedAgentCard

Metadata and extensions

The server transport recognizes A2A metadata such as a2a-version and can validate required extensions through GrpcServerTransportOptions::required_extensions.

Example

See examples/apps/grpc_server/main.cpp.

Streaming usage

Streaming is exposed through A2AClient::SendStreamingMessage and A2AClient::SubscribeTask for all production client transports:

  • gRPC uses native server streaming;
  • HTTP+JSON uses text/event-stream responses from the REST streaming and task-subscription endpoints;
  • JSON-RPC over HTTP posts a JSON-RPC request envelope and receives JSON-RPC response envelopes inside SSE data: fields.

Servers are expected to advertise capabilities.streaming: true in their Agent Card. Transport instances validate the server response shape (HTTP 2xx, Content-Type: text/event-stream, valid SSE frames, valid protocol payloads), while capability discovery and policy decisions remain the caller or client-factory responsibility.

Operations

SendStreamingMessage starts work and subscribes to updates in a single call. SubscribeTask reconnects to an existing active task and is the preferred recovery path after a broken stream. Servers close successful streams after a terminal or interrupted task state.

Implement a2a::client::StreamObserver:

  • OnEvent is called for each decoded StreamResponse, including Task, TaskStatusUpdateEvent, and TaskArtifactUpdateEvent variants.
  • OnError is called once for transport, HTTP, SSE, JSON/protobuf, or JSON-RPC envelope failures.
  • OnCompleted is called once after a clean server close. It is mutually exclusive with OnError.

For the default HTTP+JSON and JSON-RPC transports, observer callbacks are serialized per stream on a shared callback-dispatch executor. They never run on the shared libcurl reactor thread, and an idle stream does not reserve a dispatch worker. A slow callback can occupy one shared worker, so keep callbacks bounded and hand expensive processing to an application executor. Custom synchronous stream requesters retain a per-stream StreamHandle-owned worker compatibility path.

Each stream’s dispatch backlog is limited to 256 pending callbacks or 4 MiB of pending body data. The reactor never waits for callback capacity: exceeding a limit fails and cancels only that stream. There is no fixed SDK limit on the number of active streams; network, server, and process resource limits still apply.

Callback execution is marked only for the duration of each callback. Calling Cancel() from any stream callback requests cancellation without waiting for an already-running callback on the target stream. This avoids self-deadlocks and cross-stream cancellation cycles. An external thread calling Cancel() waits until the target stream can no longer call its observer. Code that cancels a stream from another stream’s callback must therefore keep the target observer’s state alive until that already-running callback returns. Per-stream serialization preserves event order even when successive callbacks run on different shared workers.

Default HTTP network reactor pool

Default libcurl-backed HTTP clients use a bounded, process-wide pool of at most four reactors. Each reactor owns a CURLM multi handle and thread and is the only thread that adds or removes easy handles from that multi handle. Start, cancellation, and shutdown operations are serialized through its synchronized command queue.

Both unary and streaming HTTP transfers acquire reactor infrastructure. The pool creates a reactor lazily when either kind of transfer first selects an uninitialized pool slot; initialization is not specific to streaming requests. Acquired unary-request and stream slots retain their reactor affinity when they are reused, preserving access to that reactor’s libcurl connection cache. A process can therefore have up to four live reactor threads, depending on which pool slots active clients and transfers acquire.

On Linux, libcurl socket and timer callbacks maintain an epoll readiness set and a timerfd. An eventfd wakes the reactor immediately for queued commands, including cancellation and shutdown, with no fixed polling interval. Socket and timer readiness is forwarded to curl_multi_socket_action(). Other platforms use libcurl’s event-driven multi wakeup fallback without a fixed wake interval.

A2AClient::Destroy() explicitly shuts down a default HTTP transport. It rejects new streams, wakes and drains the reactor, and cancels and detaches active transfers. It prevents further network stream activity, but it does not forcibly terminate or join application callback code: an observer callback that was already executing may finish naturally after Destroy() returns. Callers must therefore synchronize callback completion separately before destroying observer-owned state that another thread may still be using. No new callback for a stream begins after its shutdown has taken effect. Injected custom synchronous requesters are not owned by transport shutdown; their compatibility workers stay attached to the returned StreamHandle and are cancelled and joined when that handle is cancelled or destroyed.

The synchronous a2a::http::Client::StreamRequest() API waits for its transfer while network I/O progresses on the transfer’s reactor. Injected custom stream requesters retain their existing synchronous compatibility path.

Handles, cancellation, and timeouts

The returned StreamHandle remains active while the request is running. Cancel() is idempotent and requests prompt cancellation; destroying the handle also cancels and joins the worker before returning. Cancellation is not reported as normal completion. Configure bounded operation timeouts with CallOptions::timeout or the transport default timeout.

HTTP transport examples

auto rest = a2a::client::HttpJsonTransport::CreateDefault(resolved_rest_interface);
a2a::client::A2AClient rest_client(std::move(rest));
auto rest_stream = rest_client.SendStreamingMessage(send_request, observer, call_options);
auto jsonrpc = a2a::client::JsonRpcTransport::CreateDefault(resolved_jsonrpc_interface);
a2a::client::A2AClient jsonrpc_client(std::move(jsonrpc));
auto subscription = jsonrpc_client.SubscribeTask(get_task_request, observer, call_options);

Both default HTTP transports use the shared libcurl-backed SSE requester. Custom HttpStreamRequester injection remains available for tests and custom HTTP stacks.

See examples/apps/streaming_client/main.cpp and tests/functional/examples_functional_test.cpp.

Build and run the paired HTTP+JSON examples

The SDK build requires gRPC and Protobuf even when the examples use an HTTP transport. The default HTTP streaming client additionally requires libcurl.

On Debian, Ubuntu, or macOS, build both examples with:

./scripts/install_build_deps.sh
./scripts/run_examples.sh build-example streaming_server streaming_client

On macOS, brew install cmake ninja protobuf grpc re2 abseil curl simdjson may be used instead of the dependency script.

On Windows, install Visual Studio 2022 with the C++ workload and use Git Bash:

./scripts/install_build_deps.sh
rm -rf build-example-streaming_server build-example-streaming_client
./scripts/run_examples.sh build-example streaming_server streaming_client

The runner only invokes --help for these long-running/network-dependent examples. Start the server manually in the first terminal.

Linux or macOS, terminal 1:

./build-example-streaming_server/a2a_example

Linux or macOS, terminal 2:

./build-example-streaming_client/a2a_example \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

Windows Git Bash, terminal 1:

./build-example-streaming_server/RelWithDebInfo/a2a_example.exe

Windows Git Bash, terminal 2:

./build-example-streaming_client/RelWithDebInfo/a2a_example.exe \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

Stop the server with Ctrl+C. The client prints the terminal status update and exits after the server closes the SSE stream.

Other servers and operations

Point the generated client at any server whose Agent Card advertises capabilities.streaming: true:

./build-example-streaming_client/a2a_example --transport jsonrpc --endpoint http://127.0.0.1:8080/rpc --operation send --timeout-ms 10000
./build-example-streaming_client/a2a_example --transport http_json --endpoint http://127.0.0.1:8080/a2a --operation subscribe --task-id task-123 --timeout-ms 10000

The repository’s streaming_server example exposes HTTP+JSON SSE. Use a JSON-RPC-capable server for the JSON-RPC command. Add --cancel-after-first-event to request cancellation after the first event.

Server sessions

Executors return std::unique_ptr<ServerStreamSession> from SendStreamingMessage and, optionally, SubscribeTask. A session publishes StreamResponse values until it returns an empty optional or an error.

Observer signatures and ownership are defined by a2a::client::StreamObserver: OnEvent(const StreamResponse&), OnError(const core::Error&), and OnCompleted(). Keep observer-owned state alive until callbacks have finished.

Authentication and Authorization Hooks

The SDK provides hooks for carrying credentials and auth metadata. Your application remains responsible for credential storage, verification, authorization decisions, and audit policy.

Client credential providers

include/a2a/client/auth.h includes providers for:

  • API key headers.
  • Bearer token headers.
  • Custom header credentials.
  • OAuth2 bearer token extension points.

Use these with transport call options or request construction paths that support metadata injection.

Server metadata

REST, JSON-RPC, and gRPC server paths populate RequestContext with transport metadata. Executor or interceptor code can read this metadata to make authorization decisions.

Policy guidance

  • Never hardcode secrets in source, examples, or tests.
  • Validate credentials before trusting request metadata.
  • Normalize auth failures so callers receive consistent protocol errors.
  • Avoid logging raw credentials.
  • Prefer short-lived tokens and managed secret storage.
  • Document how TLS or mTLS identity is terminated and propagated into the SDK boundary.

Example

See examples/apps/auth_policy_server/main.cpp for an auth-policy shape.

Credential provider APIs

The public providers are ApiKeyCredentialProvider, BearerTokenCredentialProvider, CustomHeaderCredentialProvider and OAuth2BearerCredentialProvider. OAuth2 token acquisition and refresh remain application responsibilities.

See security integration, including task authorization, TLS and signed Agent Cards.

Security integration

Configure authentication, permissions, task authorization and TLS through public SDK APIs. Applications supply identity validation, credential lifetime, trusted keys and authorization policy; test fixtures are not a production identity system.

Signing is optional and disabled by default. Permissions and task authorization also work without it. Ordinary builds need neither nginx nor the OpenSSL CLI.

Caller permissions

Configure the dispatcher with its executor’s authoritative store:

dispatcher.SetSecurityPolicy(policy, stores.task_store.get());

Authenticate returns an identity or SDK error, AuthorizeOperation controls operations, and CanAccessTask evaluates authoritative tasks. The SDK clears and reauthenticates RequestContext::principal each call, preserving it across interceptors and executor callbacks. Applications own token validation, identity lifetime, ownership and scope rules. Synchronize mutable policy data: callbacks can run concurrently. Client-supplied context IDs are not identities.

Checks cover reads, cancellation, continuation, subscriptions and all push configuration operations. Hidden and missing tasks return the same canonical TaskNotFoundError, including message text. Missing/invalid credentials map to HTTP 401 or gRPC UNAUTHENTICATED; operation denials to HTTP 403 or PERMISSION_DENIED. Public card discovery stays public; extended cards use authenticated dispatch. Returned tasks from sends, reads and cancellation are checked before release; tasks without IDs are rejected before calling the policy. Returned push configurations, including every list entry, and associated messages are checked against the store; taskless messages are supported. Denials reach AfterDispatch in reverse order. Secured GetTask and unary SendMessage calls request the full executor response for authorization, then apply the caller’s history limit before returning it or invoking audit hooks.

Listing checks permissions before counting/pagination. ScopeTaskList can narrow store filters/projections or return nullopt for an empty scope. Retain fields needed by CanAccessTask; defaults preserve full tasks. The dispatcher retains one bounded batch and one page of IDs. Exact counts still inspect all matching tasks and may decode protobuf blobs before projection; bounded internal scans skip redundant backend counts. In v0.6.0 development, listings use versioned cursors and descending update-time ordering. See the ListTasks contract for live traversal consistency, legacy-token compatibility and migration requirements.

Streams check current task permissions before reading and releasing events, reject task-bearing events without IDs, and allow taskless messages. On a stream associated with a task, even taskless messages recheck that task after reading, so revocation during a blocking read is enforced. Streams preserve timed reads, live semantics and cancellation. Keep policies/stores alive until sessions finish. Credentials are authenticated on connection; include revocation/expiry in CanAccessTask for subsequent events.

Task authorization

TaskAuthorizationService combines storage, lifecycle, history and subscriptions:

a2a::server::TaskAuthorizationService authorization(
    stores.task_store.get(), validate_credential);
auto pending = authorization.RequestAuthorization(request, context, explanation);
auto resumed = authorization.Authorize(task_id, out_of_band_credential);
auto completed = authorization.Complete(task_id);

RequestAuthorization requires an agent explanation with a message ID and part; it persists TASK_STATE_AUTH_REQUIRED and TaskStatus::message. ReceiveMessage validates task/context association and deduplicates history by message ID without granting authorization. Invalid credentials leave state unchanged. Authorize validates credentials and moves to WORKING; Complete rejects pending tasks. Cancellation remains available while pending. Transitions reject tasks without the service’s authorization marker, so cancellation cannot mutate an unrelated ordinary task.

Route mutations/subscriptions through this service and keep its store alive. Send streams and subscriptions remain live during auth_required and receive working/completed events afterward. A mutex serializes mutations; SendStreamingMessage registers its stream before continuation can run. Separate creation/subscription calls can miss completion between them.

Both stores support the required conditional writes. Each transition clears the previous explanation and commits the complete task in one revision-checked write; only success publishes events. Failures preserve prior state; conflicts report errors instead of overwriting cancellation/history. Validation is not retried automatically, so validators should be safe to repeat. All writers must respect revisions: unconditional writes can replace committed state afterward.

TLS and server identity

HTTP bindings accept CallOptions::tls, the shared client Request::tls, and discovery MakeDefaultHttpFetcher TLS options, for unary and streaming requests:

a2a::client::CallOptions options;
options.tls = a2a::http::TlsOptions{.ca_bundle_path = ca_bundle_path,
                                     .require_tls13 = true};
auto task = client.GetTask(request, options);

libcurl verifies certificates/hostnames. Absent options or empty CA paths preserve compiled default trust even after pooled custom-CA use; transfer errors retain detailed diagnostics. Ordinary defaults require TLS 1.2+, explicit options default to TLS 1.3; set require_tls13=false for TLS 1.2. HTTP supports local fixtures; applications must enforce HTTPS ingress in production.

gRPC uses native grpc::SslCredentials/grpc::SslServerCredentials: supply PEM roots on channels and certificate/key pairs on the server builder. Avoid production target-name overrides. HTTP adapters use application-owned byte transports; a reverse proxy can terminate TLS and forward to loopback upstreams with SSE buffering disabled. Protect proxy-to-adapter traffic with same-host loopback or another secured connection.

Signed Agent Cards

Enable A2A_ENABLE_SIGNING=ON and link a2a::signing for OpenSSL 3.0+ Ed25519. OpenSSL is optional; simdjson 3.0+ (Apache-2.0/MIT) is a core SDK dependency, including signing-disabled builds. With vcpkg select VCPKG_MANIFEST_FEATURES=signing; installed packages expose A2A_CPP_HAS_AGENT_CARD_SIGNING and the enabled target. A pinned vcpkg registry selects maintained OpenSSL and CMake helpers, with simdjson pinned to 3.12.3; other packages retain the existing baseline. Canonicalization is private to signing. SDK parsing also uses simdjson; see the JSON parsing inventory.

auto signed_card = a2a::core::SignAgentCard(card, key_id, private_key_pem);
auto verified = a2a::core::VerifyAgentCardJson(raw_json, key_resolver, now);
discovery.SetAgentCardVerifier([&](std::string_view json) {
  return a2a::core::VerifyAgentCardJson(json, key_resolver, current_time());
});

Protected JWS headers contain alg: EdDSA, nonempty kid, and typ: JOSE. RFC 8785 JCS canonicalizes the payload after removing signatures. The private adapter rejects duplicate decoded keys, invalid Unicode and nonfinite numbers, sorts members by UTF-16 code units, uses ECMAScript number formatting and retains array order. Limits are 1 MiB and 128 nesting levels. Simdjson’s On-Demand API parses all values as binary64 where JCS requires it, including integer tokens beyond 64 bits. Simdjson is not a JCS implementation: the adapter supplies these serialization rules and validates excluded signatures too.

Verification preserves original JSON, including unknown fields. At least one signature must verify with an application-trusted key; unknown/invalid/expired/ revoked signatures do not defeat another valid signature. Signing and verification allow at most 16 signatures (kMaxAgentCardSignatures); oversized arrays are rejected before resolver calls or cryptographic verification. Resolvers provide keys, validity and revocation; callers supply time. Noncritical protected headers (typ, jku, etc.) and unprotected annotations are accepted; overlapping names, crit and unencoded payloads are rejected. ES256/RS256 are not implemented. jku never fetches keys. Signing uses protobuf field-presence serialization; empty/default-field differences await A2A #2122.

Discovery verifies public and extended cards before parsing. Public cache hits recheck signatures against current key policy. AgentCardVerifier names the owning callback type; replacing or clearing it invalidates the cache. Invalid cached cards are evicted and refreshed; refresh failure never returns the invalid card. Without a verifier, unsigned behavior remains unchanged. Applications choose signature requirements and provision trusted keys.

Conformance and validation

The SDK implements A2A protocol 1.0 across HTTP+JSON, JSON-RPC and gRPC. Binding compatibility, version negotiation and security integration describe the public contracts.

Release validation snapshot

For v0.5.2 release preparation, unmodified upstream TCK 5daf0144b4a4adbdefb62180739b13c5bd7d8196 ran on all three transports with each store:

EvidenceIn-memoryPostgreSQL
Executed upstream tests249 passed, 16 conditional skips249 passed, 16 conditional skips
Mandatory requirement coverage80.9%80.9%
Overall requirement coverage80.0%80.0%

Registered requirements without executable upstream fixtures remain NOT TESTED. Independent SDK C++ tests verify additional binding, version and security behavior; they do not increase upstream TCK percentages. This snapshot is not a claim of full TCK compliance. Review reports for the specific commit you deploy.

Reproduce the upstream suite

Use the same deterministic workflow as .github/workflows/tck.yml:

# Check out the TCK and prepare Python dependencies.
TCK_REPO=${TCK_REPO:-a2aproject/a2a-tck}
TCK_REF=${TCK_REF:-main}
git clone --depth 1 --branch "${TCK_REF}" "https://github.com/${TCK_REPO}.git" tck-repo
python3 -m venv tck-repo/.venv
source tck-repo/.venv/bin/activate
python3 -m pip install --upgrade pip
python3 -m pip install -e ./tck-repo python-dotenv pyopenssl

# Run the repository entrypoint from the repository root.
export TCK_WORKDIR=tck-repo
export TCK_TRANSPORTS=grpc,jsonrpc,http_json
export A2A_TCK_REQUIRED_EXTENSIONS=urn:a2a:tck:required-extension
export A2A_TCK_STORE_BACKEND=inmemory
export TCK_REPORT_DIR=tck-artifacts/reports/inmemory
export TCK_LOG_DIR=tck-artifacts/logs/inmemory
./scripts/run_tck_sut.sh
trap './scripts/stop_tck_sut.sh' EXIT
./scripts/run_tck_mandatory.sh
./scripts/stop_tck_sut.sh

# Repeat using a running PostgreSQL instance.
export A2A_TCK_STORE_BACKEND=postgres
export A2A_TCK_POSTGRES_DSN=postgresql://a2a:a2a@127.0.0.1:5432/a2a
export A2A_TCK_POSTGRES_SCHEMA=tck_postgres
export TCK_REPORT_DIR=tck-artifacts/reports/postgres
export TCK_LOG_DIR=tck-artifacts/logs/postgres
./scripts/run_tck_sut.sh
./scripts/run_tck_mandatory.sh
./scripts/stop_tck_sut.sh
trap - EXIT

Expected artifacts:

  • build-tck/tck-sut.log
  • tck-artifacts/reports/{inmemory,postgres}/compatibility.{json,html}
  • tck-artifacts/logs/{inmemory,postgres}/tck-run.log

The mandatory runner executes the upstream TCK entrypoint and preserves its reports. It adds no repository-specific test module or requirement report gate. Use scripts/summarize_tck_report.py to inspect failed, skipped, and untested requirements. Independent C++ SDK tests run through CTest and are reported separately from upstream TCK compliance.

CI evidence

The TCK workflow uploads separate backend reports and logs. The main CI workflow also exercises SDK integration, interoperability, sanitizers and examples. See contributor validation for local SDK checks.

A2A protocol version handling

A2A protocol versions identify wire semantics and are independent of SDK release versions. This SDK release implements A2A 1.0; an agent’s release/version field is also separate from each interface’s protocolVersion.

Negotiation matches Major.Minor. Numeric patch numbers are ignored by clients and servers (1.0.42 selects 1.0). Servers reject malformed versions and unsupported major or minor versions with VersionNotSupportedError. As required by specification `3.6, an empty or omitted version denotes 0.3. Since this SDK does not implement 0.3 semantics, it rejects that fallback, including in the SUT. It never silently treats an empty version as 1.0.

Public C++ SDK clients send A2A-Version on every unary operation, push CRUD, streaming send, and subscription. gRPC sends the lowercase a2a-version metadata key. The default is 1.0. Request a version explicitly using CallOptions:

a2a::client::CallOptions options;
options.protocol_version = "1.0.42";
auto result = client.GetTask(request, options);

The explicit option determines the version, even if arbitrary headers or an authentication hook supplies a conflicting version header. SDK clients remove case-insensitive header aliases and emit exactly one canonical parameter after credentials are applied. They reject malformed versions before sending a request. An explicit empty option sends an empty value to exercise the 0.3 fallback. Unsupported but syntactically valid versions are sent to the server for negotiation.

SDK server adapters validate versions before dispatch, then place the selected Major.Minor in RequestContext::protocol_version. HTTP+JSON, JSON-RPC and gRPC use the same SDK validator. The legacy require_version_header=false setting changes the missing-header diagnostic; it does not bypass the required 0.3 fallback. Wire headers/metadata remain available unchanged in client_headers.

RequirementIndependent SDK coverage
VER-CLIENT-001All eight unary/push methods, streaming send and subscription emit the version parameter on every binding
VER-CLIENT-002Requested 1.0.42 emits 1.0; raw wire patch versions select the same 1.0 semantics; conflicting header aliases/hooks are removed
VER-SERVER-001Accepted requests dispatch with 1.0 semantics in RequestContext, independently of SUT handlers
VER-SERVER-002Unsupported versions never dispatch and return JSON-RPC -32009, HTTP 400, or gRPC UNIMPLEMENTED with protocol-code metadata
VER-SERVER-003Empty 0.3 fallback is rejected before dispatch on every operation and binding

Core/version-validator unit tests cover malformed components, patch handling, case-insensitive lookup and empty/missing versions. protocol_version_integration_test constructs SDK adapters and dispatch independently of the SUT, records actual HTTP headers or real gRPC metadata, and identifies the operation and binding on failure. Live SUT version scenarios run with both storage backends.

ctest --test-dir build -L protocol_version --output-on-failure
ctest --test-dir build -R 'CoreVersionTest|VersionHeaderValidatorTest' --output-on-failure

See conformance and validation for SDK tests versus upstream requirement coverage.

Binding compatibility

HTTP+JSON, JSON-RPC and gRPC expose the same SDK operations through shared dispatcher and executor interfaces. Applications can attach the adapters to one dispatcher and shared stores when resources must be visible across bindings.

Independent SDK integration tests exercise all nine ordered binding pairs with in-memory and PostgreSQL stores: task identity, history/artifacts, messages, continuation, cancellation, list pages, push configuration, streaming, subscriptions, capability errors and authenticated access. Generated IDs from independent sends can differ. Subscription snapshots omit history and artifacts by contract.

Transport error envelopes differ: HTTP authentication failures use 401/403, gRPC uses UNAUTHENTICATED/PERMISSION_DENIED, and JSON-RPC protocol errors retain their prescribed error codes. A shared application security policy determines caller access on every binding.

SDK integration coverage is separate from upstream TCK coverage and from cross-SDK interoperability. See protocol version handling and conformance evidence.

To reproduce the shared-binding tests from the repository root:

cmake -S . -B build -DA2A_ENABLE_TESTING=ON -DA2A_ENABLE_POSTGRES_STORE=ON
cmake --build build --parallel
A2A_TEST_POSTGRES_DSN=postgresql://a2a:a2a@127.0.0.1:5432/a2a \
  ctest --test-dir build -L binding_equivalence --output-on-failure

Live scenarios require Python and libcurl. PostgreSQL scenarios explicitly skip without A2A_TEST_POSTGRES_DSN. Each backend uses isolated fixture processes and PostgreSQL schemas; test identities are not a deployment authorization model.

JSON parsing

The SDK uses simdjson 3.0+ for JSON syntax, UTF-8 validation, SDK message decoding, and transport envelopes. This is a required core dependency even with A2A_ENABLE_SIGNING=OFF. OpenSSL remains optional. No public SDK signature exposes simdjson types. Protobuf continues to serialize messages.

Parsing inventory

Entry pointImplementation and remaining conversions
core::JsonToMessageShared simdjson validation followed by reflection-based decoding of ordinary SDK fields. Both protobuf and JSON field names work. Unknown-field and strict-null/duplicate options are preserved.
Agent Card discovery (including discovery for gRPC)Shared decoder; the verifier still receives the original, complete JSON before typed decoding, preserving unknown signed fields. Native gRPC messages use protobuf wire decoding.
HTTP+JSON requests, responses and errorsExisting binding validation and error tagging call the shared decoder; google.rpc.Status and metadata remain protobuf messages.
JSON-RPC client unary results, errors and SSEShared envelope parser; the original result JSON is decoded directly. Removed intermediate protobuf Struct/Value, result replacement, and separate ListTasks/SSE scanners.
JSON-RPC server requests and push configurationsShared envelope parser; original params JSON reaches the shared decoder. Removed the transport’s flat-message reflection parser. IDs retain their existing protobuf Value representation for outgoing envelope serialization.
JSON-RPC ListTasks binding parametersShared simdjson-to-Struct conversion followed by the existing binding-specific filters and validation. This Struct remains to preserve binding errors and legacy parameter semantics.
HTTP+JSON and JSON-RPC SSE event bodiesShared message decoder. SSE framing remains in SseParser, which parses event framing rather than JSON.
Push-notification configuration payloadsShared decoder through each binding; delivery serializes task payloads and does not parse callback bodies.
Struct, Value, ListValuesimdjson-to-protobuf conversion; these objects are the actual application data model, rather than an intermediate representation of a typed message. Numbers retain protobuf Value’s binary64 semantics.
Bytes, uncommon numeric scalar types, non-string map keys and well-known messagesProtobuf’s semantic decoder on original JSON tokens. This deliberately retains base64 variants, exact int64/range rules, timestamps, durations, wrappers, Any and FieldMask behavior without reimplementing those codecs. Bytes use the protobuf wrapper decoder only for that field; uncommon numeric types and non-string maps use the fallback for their message subtree. Quoted/exponent int32 tokens use the protobuf wrapper decoder. Null-bearing typed messages retain protobuf decoding because supported protobuf versions differ on null container entries; strict SDK validation runs first.
Outgoing JSON-RPC serializationExisting protobuf Value bridges remain where envelope writers require them; parsing these generated payloads uses the shared implementation. Serialization redesign is outside this migration.
Signed Agent CardsThe existing signing parser and dedicated RFC 8785 serializer remain. simdjson does not implement JCS; general parsing never reconstructs the input used for signature verification.

The former public structural range helper a2a/core/json_value.h was removed with its custom grammar, tests and scanner-only benchmarks. SDK transports no longer need it.

Ownership and input policy

Each internal document exclusively leases a DOM parser from a thread-local cache. Nested/reentrant parses acquire separate parsers; there is no process-wide lock. The on-demand cursor owns padded input and its own parser. DOM storage and cursor views never escape into SDK results or application callbacks. Returned protobuf messages and envelope JSON strings own their data. Each cache retains at most one parser with input capacity up to 1 MiB. Larger documents remain supported, but their DOM and on-demand parsers are released after use instead of retaining their large buffers on worker threads.

The complete input is validated before decoding or skipping unknown fields. A second on-demand pass reads original tokens for typed payloads and subtree fallbacks, avoiding binary64 rounding of decimal integers during extraction. JSON-RPC envelopes must be objects and reject duplicate decoded member names, including escaped spellings. Typed strict parsing also rejects duplicate known fields/aliases in nested messages. Ordinary typed decoding keeps the last occurrence of repeated and message fields, replacing earlier arrays or objects even when the last occurrence is empty. Ordinary message fallbacks reject duplicate known fields instead of depending on version-specific merging. Protobuf data maps retain their normal map semantics. Binding-specific null restrictions remain in place; ordinary protobuf nulls leave fields unset.

Inputs are limited to 64 MiB and nesting depth 128. Malformed JSON, trailing data, invalid UTF-8 and numbers outside simdjson’s supported numeric range return Error::Serialization; transports retain their HTTP status, transport tag and binding-specific error mapping. Protobuf numeric fallback receives original tokens, so rounding cannot make an invalid integer acceptable. Signing retains its own stricter JCS number policy and existing limits.

Validation and measurements

The shared golden/parity fixtures exercise aliases, enums, int32/exponent limits, int64 precision, bytes, timestamps, metadata, nulls and oneofs. Existing transport, streaming, discovery and signing suites exercise the migrated entry points. Cross-binding scenarios include binary parts and null/list metadata.

The parsing benchmarks include small messages, Agent Cards, task lists, SSE event messages, and a task with 256 additional history messages and a 16 KiB binary artifact. Client and server benchmarks measure binding processing separately from parser-only timing. One Linux sample compared bed242d with this migration using GCC 15.3, protobuf 3.21.12 and simdjson 3.12.3, Release builds with signing disabled, and identical Google Benchmark definitions. Values are median CPU microseconds from three repetitions with a 0.1-second minimum per repetition on a shared host. These are indicative measurements, rather than cross-platform guarantees.

WorkloadBefore (µs)After (µs)
Small SendMessage request12.781.43
Agent Card21.142.00
SSE StreamResponse payload21.203.84
Large task history/artifact (290,486 bytes)2,035.36339.05
HTTP+JSON client ListTasks, 200 tasks638.64629.12
JSON-RPC client ListTasks, 200 tasks876.59621.81
JSON-RPC server GetTask, in-process binding/dispatch110.2242.79

A separate warmed allocation probe counted C++ new/new[] calls: small message 305 → 10, Agent Card 487 → 25, SSE payload 479 → 60, large task 5,161 → 1,668, and mocked JSON-RPC GetTask 1,313 → 233. This excludes direct malloc calls and retained parser buffers. Whole-process peak RSS was approximately 13 MiB for both probe executables, so these results do not establish lower resident memory.

The required network performance smoke check produced 54 result rows with zero errors. It is a correctness smoke check; parser-only and in-process timings do not establish network latency or throughput improvements. Full native validation passed 804 configured CTest checks with two expected TLS skips. Unmodified upstream TCK runs across all three transports and both stores each passed 249 tests with 16 conditional skips and no failed assertions. Upstream reports 80.9% mandatory / 80.0% overall compliance because 25 registry requirements have no executable fixtures; these gaps remain explicit in the PR validation report.

Cross-SDK interoperability

The SDK’s CI uses a2aproject/a2a-python at the configured A2A_PYTHON_REF. Record that ref and the C++ commit when comparing results.

Two mixed-runtime gRPC fixture flows run through scripts/run_mixed_runtime_interop.sh:

  • python-server-cpp-client-interop: a Python server with a C++ client.
  • cpp-server-python-client-interop: a C++ server with a Python client.

These fixtures check messaging, task reads and cancellation, subscription events, unknown-task errors and unsupported push operations. Their intentionally limited capabilities do not represent every SDK operation or binding.

The separate python-cross-sdk-interop job installs/imports the Python SDK and runs C++ gRPC integration tests through scripts/run_python_cross_sdk_interop.sh. That environment check alone is not evidence of mixed-runtime exchange.

Cross-binding SDK tests and upstream TCK provide different evidence. Inspect workflows and test fixtures for the version and operation you depend on rather than assuming complete Go/Python API parity.

a2a-cpp examples

The repository contains user-facing CMake consumer examples for the a2a-cpp SDK. The examples are small applications under examples/apps/, and the two consumer templates build the same app sources in the two common downstream integration modes.

  • fetch_content_consumer/ shows how to consume a2a-cpp directly from a Git repository with CMake FetchContent.
  • installed_package_consumer/ shows how to consume an installed SDK package with find_package(a2a_cpp CONFIG REQUIRED).

Applications

  • hello_agent: smallest end-to-end in-process client/server example.
  • simple_client: deterministic client-side request construction and task fetch flow.
  • rest_server: REST server transport setup and in-process request handling.
  • json_rpc_server: JSON-RPC server transport setup with a client request.
  • grpc_server: gRPC service object setup with a unary call path.
  • streaming_client: client-side streaming consumption with deterministic server-sent events.
  • streaming_server: server-side stream session publication and consumption.
  • push_notifications: push notification store and delivery abstraction.
  • auth_policy_server: auth metadata handling shape for server-side policy examples.

FetchContent consumer

cmake -S examples/fetch_content_consumer -B build-example -DA2A_EXAMPLE_APP=hello_agent
cmake --build build-example --parallel
./build-example/a2a_example

Installed package consumer

cmake -S examples/installed_package_consumer -B build-installed-example -DCMAKE_PREFIX_PATH=<install-prefix> -DA2A_EXAMPLE_APP=hello_agent
cmake --build build-installed-example --parallel
./build-installed-example/a2a_example

Smoke runner

Run every app through the FetchContent consumer template:

./scripts/run_examples.sh

Run selected apps:

./scripts/run_examples.sh hello_agent streaming_server push_notifications

Learning paths

apps/ contains focused, deterministic capability examples. tutorials/ contains realistic, separately deployable multi-process applications that consume the installed public SDK. The recommended path is hello_agent, then either the Job Application Assistant or Customer Support Copilot, then the streaming client/server examples.

Guides

Example applications

Run commands from the repository root. These small deterministic apps consume public SDK targets through the CMake consumer templates.

Build and run

cmake -S examples/fetch_content_consumer -B build-example \
  -DA2A_EXAMPLE_APP=hello_agent -DA2A_CPP_GIT_TAG=v0.5.2
cmake --build build-example --parallel
./build-example/a2a_example

Replace hello_agent with an app below. For an installed SDK, configure examples/installed_package_consumer with -DCMAKE_PREFIX_PATH=<install-prefix>. Multi-configuration Windows builds place the executable under RelWithDebInfo/.

Each app links a2a::client, a2a::server and a2a::core through the consumer templates, prints concise task/status/event or delivery output, and exits nonzero on an SDK error. Network streaming examples have their own client and server guides.

hello-agent

Smallest end-to-end in-process SDK example.

Source.

simple-client

Client-side request construction and task fetch flow.

Source.

rest-server

Server-side REST transport setup and in-process handling.

Source.

json-rpc-server

Server-side JSON-RPC transport setup.

Source.

grpc-server

gRPC service object setup and unary operation path.

Source.

push-notifications

Push notification configuration, store, and delivery abstraction.

Source.

auth-policy-server

Server-side auth metadata handling and policy shape.

Source.

streaming_client

streaming_client is a production-default streaming client example. It uses the SDK’s libcurl-backed default HTTP transports instead of a synthetic requester and supports both HTTP+JSON SSE and JSON-RPC-over-SSE.

Prerequisites

The SDK always requires gRPC and Protobuf. This example also requires libcurl for the default HTTP+JSON and JSON-RPC streaming transports.

  • Debian/Ubuntu: run ./scripts/install_build_deps.sh.
  • macOS: run brew install cmake ninja protobuf grpc re2 abseil curl simdjson.
  • Windows: use Visual Studio 2022 with the Desktop development with C++ workload and Git for Windows. Run ./scripts/install_build_deps.sh from Git Bash.

Build the client and example server

Linux or macOS:

./scripts/run_examples.sh build-example streaming_server streaming_client

The runner builds both programs and invokes their --help modes as non-blocking smoke checks. It does not leave the server running.

Windows Git Bash:

./scripts/install_build_deps.sh
rm -rf build-example-streaming_server build-example-streaming_client
./scripts/run_examples.sh build-example streaming_server streaming_client

The dependency script bootstraps vcpkg under ${VCPKG_ROOT:-$HOME/vcpkg}, installs the root manifest’s gRPC, Protobuf, and curl dependencies, and defaults both triplets to x64-windows. The example runner uses the same defaults, passes the vcpkg CMake toolchain, builds RelWithDebInfo, and locates the Visual Studio multi-configuration output automatically.

Delete an example build directory before retrying if it was previously configured without CMAKE_TOOLCHAIN_FILE; CMake caches the toolchain during the first configure.

Run the paired examples

Terminal 1 — start the HTTP+JSON SSE server:

./build-example-streaming_server/a2a_example

Terminal 2 — send a streaming request:

./build-example-streaming_client/a2a_example \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

On Windows Git Bash, use:

./build-example-streaming_server/RelWithDebInfo/a2a_example.exe
./build-example-streaming_client/RelWithDebInfo/a2a_example.exe \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

Stop the server with Ctrl+C. See ../streaming_server/README.md for custom listen addresses and server details.

Usage

Linux and macOS:

./build-example-streaming_client/a2a_example \
  --transport http_json|jsonrpc \
  --endpoint <url> \
  --operation send|subscribe \
  [--task-id <id>] \
  [--timeout-ms <milliseconds>] \
  [--cancel-after-first-event]

Windows Git Bash:

./build-example-streaming_client/RelWithDebInfo/a2a_example.exe \
  --transport http_json|jsonrpc \
  --endpoint <url> \
  --operation send|subscribe \
  [--task-id <id>] \
  [--timeout-ms <milliseconds>] \
  [--cancel-after-first-event]

The target server must advertise capabilities.streaming: true and expose the selected transport endpoint. Use --task-id with --operation send only when updating an existing task. Use --task-id with --operation subscribe to identify the existing task subscription.

Send streaming message

HTTP+JSON:

./build-example-streaming_client/a2a_example \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

JSON-RPC:

./build-example-streaming_client/a2a_example \
  --transport jsonrpc \
  --endpoint http://127.0.0.1:8080/rpc \
  --operation send \
  --timeout-ms 10000

The repository’s streaming_server example currently exposes HTTP+JSON SSE. Use a JSON-RPC-capable server for the JSON-RPC command.

Subscribe to an existing task

./build-example-streaming_client/a2a_example \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation subscribe \
  --task-id task-123 \
  --timeout-ms 10000

For JSON-RPC, use the JSON-RPC endpoint and --transport jsonrpc. On Windows, use the multi-configuration executable path shown above.

Cancellation

Add --cancel-after-first-event to demonstrate explicit cancellation after the first decoded event. Cancellation is requested by the main thread after the observer signals that the first event arrived; callbacks are not expected after cancellation settles.

Output and lifecycle notes

The example prints every supported stream variant: Task, TaskStatusUpdateEvent, and TaskArtifactUpdateEvent. Observer callbacks run on the transport worker thread, so the observer is kept alive until completion, error, cancellation, or timeout. The wait is bounded by --timeout-ms; a timeout cancels the stream and returns non-zero.

streaming_server

streaming_server is a runnable HTTP+JSON SSE server for the streaming_client example. It listens on 127.0.0.1:8080 by default and exposes the REST A2A endpoint at /a2a.

Build

Linux or macOS:

./scripts/run_examples.sh build-example streaming_server

Windows Git Bash:

./scripts/install_build_deps.sh
rm -rf build-example-streaming_server
./scripts/run_examples.sh build-example streaming_server

The runner builds the server and invokes --help as a non-blocking smoke check. Start the resulting executable manually when using it with the client.

Run with streaming_client

Build both examples:

./scripts/run_examples.sh build-example streaming_server streaming_client

Terminal 1 — start the server:

./build-example-streaming_server/a2a_example

Terminal 2 — send a streaming request:

./build-example-streaming_client/a2a_example \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

On Windows Git Bash, use these executable paths instead:

./build-example-streaming_server/RelWithDebInfo/a2a_example.exe
./build-example-streaming_client/RelWithDebInfo/a2a_example.exe \
  --transport http_json \
  --endpoint http://127.0.0.1:8080/a2a \
  --operation send \
  --timeout-ms 10000

Stop the server with Ctrl+C.

Custom address

Pass a different IPv4 host and port as the only argument:

./build-example-streaming_server/a2a_example 127.0.0.1:9090

Then point the client to http://127.0.0.1:9090/a2a.

What it demonstrates

The server publishes one terminal TaskStatusUpdateEvent through the SDK’s RestServerTransport, HttpAdapter, and ServerStreamSession APIs. It advertises capabilities.streaming: true in its Agent Card.

Production tutorials

These standalone C++20 applications demonstrate real multi-process A2A delegation:

  • Job Application Assistant: a coordinator delegates resume and job analysis to a profile specialist.
  • Customer Support Copilot: a coordinator delegates a support ticket to a specialist; the Docker flow adds OAuth-protected MCP resource access through Keycloak and ContextForge.

Both use the deterministic backend by default, so no external credentials are required.

Run both with Docker Compose

Docker Compose 2.20.3 or newer is required. The same command works on Linux, macOS, PowerShell, CMD, and Git Bash with Docker Desktop on Windows; WSL is not required.

For an interactive run with Compose’s service-prefixed, colored logs from the applications and smoke clients:

docker compose -f examples/tutorials/compose.yaml up --build --attach profile-analyst --attach application-coordinator --attach application-smoke --attach support-specialist --attach support-coordinator --attach support-smoke --attach tutorials-smoke tutorials-smoke

Wait for Tutorial Docker smoke tests passed, then press Ctrl+C and clean up:

docker compose -f examples/tutorials/compose.yaml down --volumes --remove-orphans

For an automated one-shot smoke run:

docker compose -f examples/tutorials/compose.yaml run --build --rm tutorials-smoke
docker compose -f examples/tutorials/compose.yaml down --volumes --remove-orphans

On Linux/macOS, ./scripts/run_tutorial_docker_smoke.sh is a convenience wrapper around the automated flow.

Native Linux smoke

From the repository root:

./scripts/run_tutorials.sh

This builds and installs the SDK, builds both tutorials as downstream projects, and runs the Job Application Assistant smoke flow. Customer Support Copilot is intentionally Docker-only because its Keycloak and ContextForge MCP infrastructure is part of the tutorial.

Build the SDK for an individual Job Application run

The native Job Application Assistant uses the installed CMake package:

export A2A_INSTALL_DIR="$PWD/build-tutorials/install"

cmake -S . -B build-tutorials/sdk \
  -DA2A_ENABLE_TESTING=OFF \
  -DA2A_BUILD_EXAMPLES=OFF \
  -DA2A_ENABLE_POSTGRES_STORE=OFF \
  -DCMAKE_INSTALL_PREFIX="$A2A_INSTALL_DIR"

cmake --build build-tutorials/sdk --parallel
cmake --install build-tutorials/sdk

Then follow the individual tutorial guide:

Optional model configuration

Set these variables before starting the agents or Docker Compose to use an OpenAI-compatible endpoint:

export A2A_TUTORIAL_MODEL_PROVIDER=openai_compatible
export A2A_TUTORIAL_MODEL_BASE_URL=https://provider.example/v1
export A2A_TUTORIAL_MODEL_NAME=your-model
export A2A_TUTORIAL_MODEL_API_KEY=your-api-key

Gemini free tier example

Gemini exposes an OpenAI-compatible API. For the Gemini API free tier:

export A2A_TUTORIAL_MODEL_PROVIDER=openai_compatible
export A2A_TUTORIAL_MODEL_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai/
export A2A_TUTORIAL_MODEL_NAME=gemini-3.5-flash-lite
export A2A_TUTORIAL_MODEL_API_KEY=your-gemini-api-key

Use the equivalent environment-variable syntax for your shell on Windows. Do not commit API keys.

Job Application Assistant

A standalone C++20 tutorial for HTTP+JSON A2A delegation.

application_client -> A2A coordinator -> A2A profile analyst

The client sends a resume and job description to the coordinator, which delegates analysis to the specialist and returns structured analysis plus an application draft.

Run individually with Docker Compose

From the repository root:

docker compose -f examples/tutorials/job_application_assistant/compose.yaml up --build application-smoke

Compose streams the profile analyst, coordinator, and smoke-client logs with service prefixes and colors. After the smoke client prints the application draft, press Ctrl+C and clean up:

docker compose -f examples/tutorials/job_application_assistant/compose.yaml down --remove-orphans

For a one-shot automated run:

docker compose -f examples/tutorials/job_application_assistant/compose.yaml run --build --rm application-smoke

Run individually on Linux

First install the SDK for an individual local run, then build this tutorial:

cmake -S examples/tutorials/job_application_assistant \
  -B build-tutorials/job_application_assistant \
  -DCMAKE_PREFIX_PATH="$A2A_INSTALL_DIR"
cmake --build build-tutorials/job_application_assistant --parallel

Start the three processes in separate terminals from the repository root.

Profile analyst:

./build-tutorials/job_application_assistant/profile_analyst 127.0.0.1:8081

Coordinator:

A2A_TUTORIAL_SPECIALIST_URL=http://127.0.0.1:8081 \
./build-tutorials/job_application_assistant/application_coordinator 127.0.0.1:8080

Client:

./build-tutorials/job_application_assistant/application_client \
  --coordinator-url http://127.0.0.1:8080 \
  --resume-file examples/tutorials/job_application_assistant/samples/resume.txt \
  --job-file examples/tutorials/job_application_assistant/samples/job_description.txt

See the production tutorials guide for optional model configuration.

Customer Support Copilot

A standalone C++20 tutorial for A2A delegation backed by an OAuth-protected MCP resource.

support_client -> A2A coordinator -> A2A specialist -> MCP -> ContextForge
                                                ^
                                                |
                                         Keycloak token

The tutorial is intentionally MCP-only: the client sends a ticket_resource URI, and the specialist always retrieves the ticket through ContextForge. There is no file-input fallback.

Run individually with Docker Compose

Docker Compose 2.20.3 or newer is required. From the repository root:

docker compose -f examples/tutorials/customer_support_copilot/compose.yaml -f examples/tutorials/customer_support_copilot/compose.contextforge.yaml up --build --attach support-specialist --attach support-coordinator --attach support-smoke support-smoke

Compose streams only the specialist, coordinator, and smoke-client logs; Keycloak and ContextForge remain available without flooding the tutorial output. The flow generates ephemeral secrets and certificates, bootstraps a least-privilege MCP principal and ticket resource, verifies OAuth-protected MCP 2025-11-25 resources/read, and runs the A2A client.

After the smoke client completes, press Ctrl+C and clean up:

docker compose -f examples/tutorials/customer_support_copilot/compose.yaml -f examples/tutorials/customer_support_copilot/compose.contextforge.yaml down --volumes --remove-orphans

For a one-shot automated run:

docker compose -f examples/tutorials/customer_support_copilot/compose.yaml -f examples/tutorials/customer_support_copilot/compose.contextforge.yaml run --build --rm support-smoke

See the production tutorials guide for optional model configuration.

Troubleshooting Docker

To include infrastructure logs while debugging:

docker compose -f examples/tutorials/customer_support_copilot/compose.yaml -f examples/tutorials/customer_support_copilot/compose.contextforge.yaml logs

Build with CMake

a2a-cpp is a C++20 SDK built and packaged with CMake. The project can be used directly from source with FetchContent, installed into a CMake package prefix, or built with dependencies supplied by vcpkg.

Requirements

  • CMake 3.25 or newer.
  • A C++20 compiler.
  • Protobuf and gRPC development packages.
  • Optional: libcurl for the default buffered outbound HTTP implementation.
  • Optional: PostgreSQL client libraries when A2A_ENABLE_POSTGRES_STORE=ON.

On Ubuntu-like systems, the repository helper installs the dependencies used by CI:

./scripts/install_build_deps.sh

On macOS, install equivalent packages with Homebrew:

brew install cmake ninja protobuf grpc re2 abseil curl

On Windows, install Visual Studio 2022 with the Desktop development with C++ workload and Git for Windows. Then run the repository dependency helper from Git Bash:

./scripts/install_build_deps.sh

Configure from source

The default source build enables tests, keeps the curated example apps out of the top-level build, and enables libcurl-backed HTTP support when CMake can find CURL::libcurl.

cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DA2A_ENABLE_TESTING=ON

When dependencies are installed outside standard search paths, pass a CMake prefix path:

cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DCMAKE_PREFIX_PATH="/opt/homebrew;/opt/homebrew/opt/curl"

Build and test

Single-configuration generators:

cmake --build build --parallel
ctest --test-dir build --output-on-failure

Visual Studio generators from Git Bash:

cmake --build build --config RelWithDebInfo --parallel
ctest --test-dir build -C RelWithDebInfo --output-on-failure

For the repository’s full local code validation flow, run:

./scripts/verify_changes.sh

That script runs the same main gates expected before a code PR: formatting, configure/build, tests, and clang-tidy.

CMake options

OptionDefaultDescription
A2A_ENABLE_TESTINGONBuilds unit and integration tests and enables CTest.
A2A_BUILD_EXAMPLESONCompatibility/message-only option for the root build today; curated examples are built as standalone consumers from examples/fetch_content_consumer or examples/installed_package_consumer.
A2A_BUILD_BENCHMARKSOFFBuilds benchmark targets under benchmarks/.
A2A_ENABLE_LIBCURLONEnables the default libcurl-backed outbound HTTP implementation when libcurl is found. Disable it to require injected requesters/fetchers.
A2A_ENABLE_POSTGRES_STOREOFFBuilds PostgreSQL-backed store targets when PostgreSQL dependencies are available.

Generated protobuf headers

The SDK generates A2A protocol C++ sources during the build. Primary generated A2A headers are written under build/generated/a2a/v1/, and generated Google API annotation headers are written under build/generated/google/api/.

Those generated headers are installed with the SDK, so downstream projects should include headers from the installed package rather than copying build-tree generated files.

Install as a CMake package

Install the SDK to a prefix:

cmake --install build --prefix /tmp/a2a-cpp-install

The install tree includes public headers, generated protobuf headers, libraries, and package configuration files under lib/cmake/a2a_cpp.

A downstream project can then consume the installed package:

cmake_minimum_required(VERSION 3.25)
project(my_a2a_app LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(a2a_cpp CONFIG REQUIRED)

add_executable(my_a2a_app main.cpp)
target_link_libraries(my_a2a_app PRIVATE a2a::client a2a::server a2a::core)

Configure that downstream project with CMAKE_PREFIX_PATH pointing at the install prefix:

cmake -S path/to/app -B build-app \
  -DCMAKE_PREFIX_PATH=/tmp/a2a-cpp-install
cmake --build build-app --parallel

FetchContent consumer

For application projects that prefer source integration, use CMake FetchContent and pin GIT_TAG to a release tag or reviewed commit:

include(FetchContent)

set(A2A_ENABLE_TESTING OFF CACHE BOOL "" FORCE)
set(A2A_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(A2A_BUILD_BENCHMARKS OFF CACHE BOOL "" FORCE)
set(A2A_ENABLE_POSTGRES_STORE OFF CACHE BOOL "" FORCE)

FetchContent_Declare(
  a2a_cpp
  GIT_REPOSITORY https://github.com/MisterVVP/a2a-cpp.git
  GIT_TAG v0.5.2
)
FetchContent_MakeAvailable(a2a_cpp)

target_link_libraries(my_a2a_app PRIVATE a2a::client a2a::server a2a::core)

See examples/fetch_content_consumer/ for a minimal runnable consumer.

Exported targets

Common exported targets include:

  • a2a::core for shared core types and utilities.
  • a2a::client for client APIs.
  • a2a::server for server APIs.
  • a2a::http for HTTP support internals used by higher-level targets.
  • a2a::proto_generated for generated protobuf bindings.
  • a2a::store_postgres when PostgreSQL store support is enabled.

Most applications should link the smallest set they use. The examples link a2a::client, a2a::server, and a2a::core for a combined client/server sample.

Build the curated examples

Use the repository runner for FetchContent examples:

./scripts/run_examples.sh build-example hello_agent

When VCPKG_ROOT is set, the runner forwards the vcpkg toolchain and optional target/host triplets. It builds RelWithDebInfo by default and finds either build-example-hello_agent/a2a_example or the Visual Studio output at build-example-hello_agent/RelWithDebInfo/a2a_example.exe.

Windows Git Bash:

./scripts/install_build_deps.sh
rm -rf build-example-hello_agent
./scripts/run_examples.sh build-example hello_agent

Platform notes

  • Linux CI configures with CMake and validates build, tests, examples, clang-format, clang-tidy, coverage, and selected sanitizer/interop flows.
  • macOS CI builds with Homebrew-provided dependencies and Ninja, then runs all registered CTest tests, including available Python-backed checks.
  • Windows CI and local Windows builds use vcpkg manifest dependencies and the Visual Studio 2022 generator. CI runs all registered C++ tests and the applicable Python-backed checks; three POSIX/compilation-database-dependent script tests are excluded with reasons documented in the workflow. See vcpkg for the helper script, manifest, triplet, and overlay details.

Build with vcpkg

a2a-cpp provides vcpkg metadata for two related workflows:

  1. Manifest dependency mode for building this repository with vcpkg-supplied third-party dependencies.
  2. Overlay port mode for consuming a2a-cpp itself as a vcpkg package before it is available from a public registry.

The repository root vcpkg.json pins the dependency baseline and declares the SDK’s third-party dependencies: protobuf, gRPC, and curl.

Prerequisites

Install or clone vcpkg and bootstrap it:

git clone https://github.com/microsoft/vcpkg.git "$HOME/vcpkg"
"$HOME/vcpkg/bootstrap-vcpkg.sh"

On Windows PowerShell:

git clone https://github.com/microsoft/vcpkg.git C:\vcpkg
C:\vcpkg\bootstrap-vcpkg.bat

Set VCPKG_ROOT for convenience:

export VCPKG_ROOT="$HOME/vcpkg"
$env:VCPKG_ROOT = 'C:\vcpkg'

Repository helper on Windows Git Bash

From the repository root, the Bash helper clones, bootstraps, and installs the vcpkg manifest dependencies:

./scripts/install_build_deps.sh

The default vcpkg checkout is $HOME/vcpkg; no fixed C:/vcpkg location is required. Override the root or triplets with environment variables:

export VCPKG_ROOT=/d/tools/vcpkg
export VCPKG_TARGET_TRIPLET=x64-windows-static
export VCPKG_HOST_TRIPLET=x64-windows
./scripts/install_build_deps.sh

Build this repository with manifest dependencies

From the repository root, let vcpkg install the manifest dependencies and then configure CMake with the vcpkg toolchain file:

"$VCPKG_ROOT/vcpkg" install
cmake -S . -B build-vcpkg \
  -DVCPKG_MANIFEST_MODE=ON \
  -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DA2A_ENABLE_TESTING=ON
cmake --build build-vcpkg --parallel
ctest --test-dir build-vcpkg --output-on-failure

On multi-config generators such as Visual Studio, pass the configuration during build and test:

& "$env:VCPKG_ROOT\vcpkg.exe" install
cmake -S . -B build-vcpkg -G "Visual Studio 17 2022" -A x64 `
  -DVCPKG_MANIFEST_MODE=ON `
  -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT\scripts\buildsystems\vcpkg.cmake"
cmake --build build-vcpkg --config RelWithDebInfo --parallel
ctest --test-dir build-vcpkg -C RelWithDebInfo --output-on-failure

Use a specific triplet

Pass the same target triplet to vcpkg and CMake. For native builds, use the same value for the host triplet so host tools such as protoc and grpc_cpp_plugin are resolved consistently:

"$VCPKG_ROOT/vcpkg" install --triplet x64-linux --host-triplet x64-linux
cmake -S . -B build-vcpkg \
  -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
  -DVCPKG_TARGET_TRIPLET=x64-linux \
  -DVCPKG_HOST_TRIPLET=x64-linux

Windows CI uses the repository triplet triplets/ci-x64-windows-release.cmake to build release-only dependencies and reduce dependency build time:

$env:VCPKG_OVERLAY_TRIPLETS = "$PWD\triplets"
& "$env:VCPKG_ROOT\vcpkg.exe" install --triplet ci-x64-windows-release --host-triplet ci-x64-windows-release
cmake -S . -B build -G "Visual Studio 17 2022" -A x64 `
  -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT\scripts\buildsystems\vcpkg.cmake" `
  -DVCPKG_TARGET_TRIPLET=ci-x64-windows-release `
  -DVCPKG_HOST_TRIPLET=ci-x64-windows-release

Build standalone FetchContent examples on Windows

The example runner uses the already-installed root manifest dependencies. It automatically passes the vcpkg toolchain and triplets when VCPKG_ROOT is set:

./scripts/install_build_deps.sh
rm -rf build-example-streaming_client
./scripts/run_examples.sh build-example streaming_client
./build-example-streaming_client/RelWithDebInfo/a2a_example.exe --help

Delete a build directory that was configured before the toolchain was supplied; changing CMAKE_TOOLCHAIN_FILE in an existing CMake cache is not reliable.

Consume a2a-cpp through the repository overlay port

The repository includes an overlay port at vcpkg-overlay-ports/a2a-cpp. A downstream manifest can depend on a2a-cpp and point vcpkg at that overlay.

vcpkg.json:

{
  "name": "my-a2a-app",
  "version-string": "0.5.2",
  "dependencies": [
    "a2a-cpp"
  ]
}

vcpkg-configuration.json:

{
  "default-registry": {
    "kind": "builtin",
    "baseline": "3426db05b996481ca31e95fff3734cf23e0f51bc"
  },
  "overlay-ports": [
    "path/to/a2a-cpp/vcpkg-overlay-ports"
  ]
}

Then configure the application with the vcpkg toolchain file on the first CMake configure and use the installed CMake package:

find_package(a2a_cpp CONFIG REQUIRED)
target_link_libraries(my_a2a_app PRIVATE a2a::client a2a::server a2a::core)

A complete example is available in examples/installed_package_consumer/.

Enable PostgreSQL store support

The overlay port exposes a postgres-store feature. Enable it in manifest mode when your application needs PostgreSQL-backed stores:

{
  "name": "my-a2a-app",
  "version-string": "0.5.2",
  "dependencies": [
    {
      "name": "a2a-cpp",
      "features": ["postgres-store"]
    }
  ]
}

When the feature is enabled, link the additional target where needed:

target_link_libraries(my_a2a_app PRIVATE a2a::store_postgres)

Classic mode smoke install

For a direct overlay smoke test, run classic mode from a directory that does not contain a vcpkg.json manifest:

mkdir -p /tmp/a2a-vcpkg-smoke
cd /tmp/a2a-vcpkg-smoke
"$VCPKG_ROOT/vcpkg" install a2a-cpp --overlay-ports=/path/to/a2a-cpp/vcpkg-overlay-ports

Add a triplet if needed:

"$VCPKG_ROOT/vcpkg" install a2a-cpp:x64-linux --overlay-ports=/path/to/a2a-cpp/vcpkg-overlay-ports

Binary caching

Large dependencies such as gRPC and protobuf can take time to build. Enable binary caching for local and CI runs:

export VCPKG_BINARY_SOURCES="clear;files,$HOME/.cache/vcpkg-binary-cache,readwrite"
mkdir -p "$HOME/.cache/vcpkg-binary-cache"

On Windows PowerShell:

$env:VCPKG_BINARY_SOURCES = 'clear;files,C:\vcpkg-binary-cache,readwrite'
New-Item -ItemType Directory -Force C:\vcpkg-binary-cache | Out-Null

Troubleshooting

  • CMake cannot find gRPC or Protobuf: confirm CMAKE_TOOLCHAIN_FILE points to scripts/buildsystems/vcpkg.cmake before the first configure. If you configured without it, delete the build directory and configure again.
  • Unexpected manifest behavior in classic mode: classic vcpkg install a2a-cpp should be run outside directories containing vcpkg.json, otherwise vcpkg switches to manifest mode.
  • Different host and target triplets: pass both VCPKG_TARGET_TRIPLET and VCPKG_HOST_TRIPLET when cross-compiling or when CI uses a custom host triplet.
  • Slow clean builds: enable binary caching and prefer release-only dependency triplets for CI jobs that only link release configurations.
  • Example executable is not in the build root on Windows: Visual Studio is multi-configuration; use build-example-<app>/RelWithDebInfo/a2a_example.exe, or let scripts/run_examples.sh locate and run it.
  • The dependency helper reports an unsupported shell on Windows: run scripts/install_build_deps.sh from Git Bash rather than another Windows shell.

CMake consumer templates

FetchContent consumer

Use this template when your application should build a2a-cpp from a Git repository as part of your CMake configure step.

cmake -S examples/fetch_content_consumer -B build-example -DA2A_EXAMPLE_APP=hello_agent
cmake --build build-example --parallel
./build-example/a2a_example

Select another app with -DA2A_EXAMPLE_APP=<name>. For reproducible builds, pin A2A_CPP_GIT_TAG to a release tag or commit instead of relying on the default branch:

cmake -S examples/fetch_content_consumer -B build-example \
  -DA2A_EXAMPLE_APP=rest_server \
  -DA2A_CPP_GIT_TAG=<release-tag-or-commit>

Installed package consumer

Use this template when a2a-cpp has already been installed and your application should consume it with find_package(a2a_cpp CONFIG REQUIRED).

With an existing install prefix

cmake -S examples/installed_package_consumer -B build-installed-example \
  -DCMAKE_PREFIX_PATH=<install-prefix> \
  -DA2A_EXAMPLE_APP=hello_agent
cmake --build build-installed-example --parallel
./build-installed-example/a2a_example

With the local vcpkg overlay

cd examples/installed_package_consumer
vcpkg install
cmake -S . -B ../../build-installed-example \
  -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" \
  -DA2A_EXAMPLE_APP=hello_agent
cmake --build ../../build-installed-example --parallel
../../build-installed-example/a2a_example

Select another app with -DA2A_EXAMPLE_APP=<name>.

Run commands from the repository root unless the example explicitly changes directory.

Packages and release artifacts

The SDK exports installed CMake targets under the a2a:: namespace. Use CMake integration or the repository-local vcpkg overlay to consume a reviewed release.

Release tags use v<major>.<minor>.<patch>. The release packaging workflow produces source .tar.gz and .zip archives and SHA256SUMS.txt on GitHub Releases. Verify the checksum after downloading. Pin source dependencies to a release tag or reviewed commit and keep generated protobuf headers and linked libraries from the same package or build tree.

The repository-local overlay is distinct from publication in the public microsoft/vcpkg registry. A local overlay does not prove registry availability. See release compatibility notes and supported versions before upgrading.

Performance testing

The A2A C++ SDK includes a report-only performance test kit for repeatable local and CI measurements. The Python runner still owns matrix orchestration and writes results.json, results.csv, and summary.md; measured operations are delegated to the in-process C++ SDK-backed driver (a2a_performance_driver) and, for real transport rows, the wire-level client driver (a2a_wire_performance_driver).

Run locally

./scripts/run_performance_tests.sh --store-backends inmemory --requests 100 --concurrency 1,4 --warmup-seconds 0

The runner writes:

  • perf-artifacts/results.json
  • perf-artifacts/results.csv
  • perf-artifacts/summary.md

Subscription terminal phase diagnostics

Subscription attribution is compiled out of normal SDK builds. Enable runtime collection with the environment switch; the runner automatically configures a separate optimized diagnostics build with the private CMake option enabled:

A2A_SUBSCRIPTION_DIAGNOSTICS=1 \
  ./scripts/run_performance_tests.sh

The normal build remains in build/performance; diagnostics use the isolated build/performance-subscription-diagnostics tree. A2A_PERF_BUILD_DIR changes the normal build-tree base, and the runner appends the diagnostics suffix for profiling runs so a diagnostics-enabled binary cannot be reused as a normal benchmark binary.

Wire results keep server_subscription_diagnostics and client_subscription_diagnostics separate because the SUT and SDK client run in different processes. Each phase contains count, total_ns, and max_ns. server_cancel_task_total and terminal_publication_total are total timers and must not be added to their nested phase measurements.

Reading the reports

The Markdown summary keeps fundamentally different workloads separate. Its execution summary groups counts by store and measurement path for compact coverage and correctness checking, but deliberately contains no combined throughput or latency statistic. Subsequent tables separate in-memory from PostgreSQL, in-process from wire measurements, and each wire transport from the others. PostgreSQL pool sizes also have distinct tables. This prevents a faster in-memory row, a wire round trip, or a different pool configuration from being averaged into a number that describes no concrete workload.

Each result table pivots the configured concurrency levels into cN ops/s and cN p95 ms column pairs. Read horizontally to see how one scenario at one store/path/transport/pool coordinate scales; columns are generated from the levels actually present, including single-level runs. In-process rows exercise SDK service and store code without a transport, so Markdown renders their transport as — rather than attributing them to the transport selected to launch the driver. These coordinate tables are collapsed by default so the execution summary remains easy to scan; expand the named section to inspect its scaling results.

The Cross-backend scaling signals table uses only scenario, path, transport, and concurrency coordinates present in both stores, with each PostgreSQL pool kept separate. For each coordinate it divides the highest shared-concurrency p95 and throughput by their respective lowest shared-concurrency values. A zero denominator is reported as n/a. These relative ratios help expose scaling patterns shared by both backends; they do not compare absolute PostgreSQL speed with in-memory speed and are not an automatic bottleneck verdict.

The detailed matrix remains available in a collapsible section. Its Repetition column appears only when at least one row belongs to a repeated profile, such as postgres-tail. For streaming measurements, both the detailed matrix and the separate, collapsible Streaming latency rollup distinguish total operation latency from first-event and stream-completion latency. Missing streaming dimensions are rendered as n/a, so unary rows are not mistaken for zero-latency streams. results.csv and results.json retain every raw row and field and are the authoritative outputs for further analysis; the Markdown restructuring does not transform those measurements. The cross-backend signals, PostgreSQL diagnostics, and postgres-tail median tables are also collapsible because they can contain many rows.

If A2A_PERF_DRIVER, A2A_PERF_WIRE_DRIVER, or A2A_PERF_SUT are not set, the runner configures and builds the needed binaries in build/performance. Set A2A_PERF_BUILD_DIR to reuse another CMake build tree.

Configuration

You can configure the matrix and load profile with command-line flags or the matching environment variables.

SettingEnvironment variableDefault
Transports (grpc, jsonrpc, http_json, or all)A2A_PERF_TRANSPORTSgrpc,jsonrpc,http_json
Store backends (inmemory, postgres, or all)A2A_PERF_STORE_BACKENDSinmemory,postgres
Operations per result rowA2A_PERF_REQUESTS2000
Concurrency levelsA2A_PERF_CONCURRENCY1,4
Warmup secondsA2A_PERF_WARMUP_SECONDS1
Duration seconds limitA2A_PERF_DURATION_SECONDS0
Report directoryA2A_PERF_REPORT_DIRperf-artifacts
Existing in-process driver binaryA2A_PERF_DRIVERunset
Existing wire driver binaryA2A_PERF_WIRE_DRIVERunset
Existing performance SUT binaryA2A_PERF_SUTunset
In-process driver timeout secondsA2A_PERF_DRIVER_TIMEOUT_SECONDS600
Wire driver timeout secondsA2A_PERF_WIRE_DRIVER_TIMEOUT_SECONDS600
Auto-build directoryA2A_PERF_BUILD_DIRbuild/performance
PostgreSQL pool sizesA2A_PERF_POSTGRES_POOL_SIZES4

Workload modes

When A2A_PERF_DURATION_SECONDS=0, each row runs request-count mode and stops after A2A_PERF_REQUESTS operations. When A2A_PERF_DURATION_SECONDS is greater than zero, each row stops when either the configured request count or the duration limit is reached, whichever happens first. Warmup runs before the measured window, so warmup operations are excluded from latency, throughput, operations, and measured_duration_seconds. Reports include both configured_requests / configured_duration_seconds and the actual operations / measured_duration_seconds.

Scenario coverage

The SDK-backed driver executes these real service/store flows through the shared example executor, task lifecycle service, task subscription service, in-memory task store, in-memory push notification store, and push notification service:

  • task lifecycle: SendMessage create, GetTask, CancelTask, list with and without pagination, follow-up SendMessage, and missing-task lookup;
  • streaming and subscriptions: finite SendStreamingMessage, existing-task subscription first event, simultaneous multi-subscriber delivery to the same task, terminal update delivery followed by stream completion, and disconnect isolation where one cancelled subscription does not prevent remaining subscribers from receiving a later update;
  • push notifications: create/get/list/delete config, an end-to-end many-config task update, pre-seeded many-config list lookup, many-config create cost, payload construction, and in-process callback fan-out through a local recording delivery client implementation of the SDK delivery interface. Rows expose scenario-specific counters such as successful_deliveries, failed_deliveries, event_count, callback_count, fanout_per_operation, and total_fanout_count.

Each row includes the required stable fields plus driver_type and transport_path. The current driver type is cpp_sdk_in_process.

Push notification row attribution

The in-process push rows intentionally separate setup-heavy and delivery-only work:

  • PushConfig_Get uses one immutable config fixture, PushConfig_List uses a fixed three-config fixture, and PushConfig_Delete uses one independently pre-seeded task/config pair per operation. Warmup deletes use separate task/config pairs, so they cannot consume measured fixtures. PushConfig_Create retains one measured create against a pre-existing task.
  • PushNotify_EndToEndManyConfigs creates a task, writes eight push-notification configs, sends one task update, lets the push service list configs from the configured store, builds the update payload, and invokes the local recording callback once per config.
  • PushConfig_ListManyConfigs uses a task and eight configs seeded before warmup and measures only the list operation for that fixed fan-out.
  • PushDelivery_CallbackFanout uses preloaded configs and a prebuilt payload seeded before warmup, then measures only the in-process callback delivery loop. It does not create tasks, create configs, query the store, or perform network I/O inside the timed operation.
  • PushConfig_CreateMany uses a task seeded before warmup and measures only eight real CreateTaskPushNotificationConfig calls. On the same-storage PostgreSQL path, each call performs one atomic task-aware push_config_upsert command with no separate task_get.
  • PushDelivery_BuildPayload measures construction of the push status-update payload separately.

The default fan-out is eight configs per operation and is reported in fanout_per_operation. total_fanout_count is cumulative across measured operations and reflects actual attempted/configured fan-out where known; for example, 2,000 successful operations at fan-out 8 report fanout_per_operation=8 and total_fanout_count=16000. fanout_count remains as a backward-compatible alias for the cumulative total. Callback rows report actual attempted callbacks in callback_count and split delivery outcomes into successful_deliveries and failed_deliveries, including failed operations.

Transport coverage

Reports contain two clearly separated measurement paths:

  • In-process rows come from a2a_performance_driver. They exercise SDK service, executor, store, streaming, and push-notification code without sockets and are reported as driver_type=cpp_sdk_in_process with transport_path=in_process.
  • Wire rows come from a2a_wire_performance_driver. The runner starts the performance_sut fixture, waits for HTTP and gRPC ports, and then the wire driver sends real client calls to the selected endpoint. These rows are reported as driver_type=wire_tck_sut with transport_path=wire_http_json, wire_jsonrpc, or wire_grpc.

The current real wire-level scenario set covers core lifecycle operations, push notification config CRUD, finite streaming, and first-event task subscription for HTTP+JSON, JSON-RPC, and gRPC. The common wire scenarios are ListTasks_NoPagination, ListTasks_WithPagination, SendMessage_CreateTask, GetTask_ExistingTask, CancelTask_WorkingTask, SendMessage_FollowUpExistingTask, SendMessage_FollowUpAtHistoryDepth/8, GetTask_MissingTaskError, PushConfig_Create, PushConfig_Get, PushConfig_List, PushConfig_Delete, SendStreamingMessage_FiniteStream, SubscribeToTask_FirstEventLatency, and IdleStream_ClientCancellationLatency. The historical SendStreamingMessage_FiniteStream and SubscribeToTask_FirstEventLatency rows preserve the original one-client-per-worker topology so before/after comparisons remain equivalent to older reports. HTTP+JSON and JSON-RPC additionally run SendStreamingMessage_FiniteStream_SharedClient and SubscribeToTask_FirstEventLatency_SharedClient, where every measured worker uses one shared A2AClient. These shared-client rows are separate scalability coordinates and must not be substituted for the historical rows when evaluating regressions or issue acceptance. gRPC does not run the shared-client variants. The idle-stream cancellation scenario seeds a task, establishes a real subscription, waits for its initial event, and then measures only the synchronous local StreamHandle::Cancel() call. It does not invoke the protocol-level CancelTask operation or ask the server to publish a terminal event. For HTTP transports it retains the shared-client stress topology because it has no historical baseline. The wire driver otherwise reuses one client/transport per worker thread so measured operations do not recreate gRPC channels or HTTP transport objects. The libcurl-backed HTTP path submits both unary and streaming requests through a process-wide pool of at most four CURLM reactors. Reusable easy-handle slots keep their reactor assignment for connection-cache locality. Each client also aligns its first unary and streaming handles to one reactor shard, allowing common request-to-stream sequences to reuse that shard’s connection cache while additional concurrent handles remain distributed across the bounded pool. List scenarios run before mutating lifecycle scenarios and seed a fixed fixture of 20 tasks, then measure only ListTasks calls, keeping the listed task set bounded in CI. Multi-subscriber subscription, disconnect isolation, terminal-completion subscription, and callback fan-out remain SDK in-process rows in this implementation; they are not duplicated as transport rows and must not be interpreted as full wire_tck_sut coverage.

Focused wire fixtures are also prepared before timing: existing-task lookup uses a shared task; push create uses a pre-existing task; push get uses a shared immutable config; push list uses a fixed three-config set; and every push delete operation owns a distinct single-config task. Warmup uses a separate fixture namespace. Consequently, lower latency in these rows reflects corrected benchmark attribution rather than an SDK runtime optimization.

For PostgreSQL, each focused operation executes one matching store command: task_get for GetTask_ExistingTask, push_config_upsert for PushConfig_Create, push_config_get for PushConfig_Get, push_config_list_select for PushConfig_List, or push_config_delete for PushConfig_Delete.

Store backend coverage

inmemory uses the real in-memory task and push notification stores. postgres uses the repository PostgresStoreFactory to create real PostgreSQL-backed task and push notification stores when the driver is built with A2A_ENABLE_POSTGRES_STORE=ON. The Python runner automatically adds that CMake option when postgres is selected and it needs to auto-build the driver. PostgreSQL runs must provide the same local DSN style used by the repository store tests (A2A_TEST_POSTGRES_DSN); CI starts a local PostgreSQL service for the performance job. For wire-level PostgreSQL rows, the runner maps A2A_TEST_POSTGRES_DSN to A2A_TCK_POSTGRES_DSN for performance_sut and assigns a matrix-scoped schema named a2a_perf_<transport>_<concurrency>_<port> so rows do not share the default public schema or accumulate data across matrix entries. The runner passes each selected size to both the in-process driver and wire SUT. Every PostgreSQL result row records postgres_pool_size in JSON and CSV, and the Markdown detail and diagnostic tables include a pool-size column. Multiple comma-separated sizes create a comparison matrix without source changes. The postgres-tail profile defaults to pool sizes 4,16,64 at concurrency levels 4,16,64; an explicit --postgres-pool-sizes value or A2A_PERF_POSTGRES_POOL_SIZES overrides that profile default.

Attributed PostgreSQL write profile

Use --profile postgres-write to reproduce the four write-saturation signals without wire-transport work. The profile fixes the pool size at 64, runs SendMessage_CreateTask, SendMessage_FollowUpExistingTask, PushConfig_Create, and PushConfig_CreateMany independently at concurrency 1, 4, 16, and 64, and records five repetitions. A distinct schema is used for every scenario, coordinate, and repetition, preventing accumulated rows or another scenario’s locks from changing the comparison.

While each scenario runs, the runner samples pg_stat_activity and records session state, concurrent active sessions, idle transactions, and PostgreSQL wait-event type/event. It also takes before/after snapshots of pg_stat_database, pg_stat_wal, and the MultiXactMember and MultiXactOffset rows from pg_stat_slru. The resulting postgres_database_diagnostics object in results.json contains sampled wait counts and deltas for transactions, tuple writes, cache activity, WAL bytes, WAL writes/syncs, full WAL buffers, PostgreSQL-reported block/WAL timing, and MultiXact SLRU block activity. The local task-aware push path now coordinates create/delete with transaction-scoped advisory locks, so its MultiXact deltas should remain zero; non-zero activity points to other or legacy row-lock work. These server observations complement the per-operation connection_acquire_wait, task_upsert, task_history_snapshot, and push_config_upsert phase latencies already emitted by the SDK driver. task_history_snapshot is the non-locking snapshot read used by optimistic history appends. task_history_lock_read remains a distinct legacy/locking phase so reports do not misattribute optimistic snapshot latency or retries to row-lock acquisition.

A2A_TEST_POSTGRES_DSN=postgresql://a2a:a2a@127.0.0.1:5432/a2a \
./scripts/run_performance_tests.sh --profile postgres-write \
  --report-dir perf-artifacts/postgres-write

The profile also captures EXPLAIN (ANALYZE, BUFFERS, WAL) output for representative task-conflict and push-config insert writes inside a rolled-back transaction. Interpret the evidence before changing production code:

  • increasing WAL:WALWrite or IO:WALSync samples, WAL sync time, and WAL bytes with negligible acquisition wait indicates server durability throughput, not pool starvation;
  • Lock:transactionid or tuple-lock samples concentrated on an update fixture indicate same-row conflict contention;
  • rising buffer reads or read time and an unexpected scan in the captured plan indicate a plan, index, or cache issue;
  • high idle_in_transaction is a transaction-scope defect and should remain zero for these autocommit writes.

The diagnostics use cumulative cluster counters, so run this profile against an otherwise idle PostgreSQL instance. Wait events are sampled observations rather than exact durations. Each scenario is isolated specifically so its counter delta and wait samples can be correlated with one performance row.

CI behavior

CI runs the broad performance matrix and focused PostgreSQL tail profile as independent jobs so they execute in parallel. The normal job uses 1,000 requests per row across three transports, two stores, and concurrency levels 1, 4, 16, and 64; its PostgreSQL rows use a 64-connection pool. The tail job retains 2,000 requests, five repetitions, pool sizes 4,16,64, and concurrency levels 4,16,64.

The in-process SDK/service/store rows do not exercise a transport, so the runner executes them once per store/concurrency pair instead of repeating identical in-process work under every selected transport. The jobs upload perf-artifacts-normal and perf-artifacts-postgres-tail, append their own summaries to the GitHub Actions step summary, and fail only on crashes, functional operation errors, malformed output, missing artifacts, or driver timeouts. They do not enforce latency or throughput thresholds. The runner prints a workload estimate at startup and flushes [perf] start ... / [perf] done ... progress lines for every in-process and wire matrix row so GitHub Actions logs show forward progress. Both driver subprocesses have explicit timeouts controlled by A2A_PERF_DRIVER_TIMEOUT_SECONDS and A2A_PERF_WIRE_DRIVER_TIMEOUT_SECONDS; on a wire timeout, recent performance_sut logs are included in the failure message when available.

Larger local benchmark

A2A_PERF_TRANSPORTS=grpc,jsonrpc,http_json \
A2A_PERF_STORE_BACKENDS=inmemory,postgres \
A2A_PERF_REQUESTS=2000 \
A2A_PERF_POSTGRES_POOL_SIZES=4,16,64 \
A2A_PERF_CONCURRENCY=1,4,16,64 \
A2A_PERF_WARMUP_SECONDS=5 \
A2A_PERF_REPORT_DIR=perf-artifacts \
./scripts/run_performance_tests.sh

JSON shape

results.json contains host metadata and a results array. Each result includes scenario name, transport, store backend, driver type, transport path, concurrency, configured request and duration limits, measured duration, operation counts, success and error counts, throughput, latency percentiles, max latency, scenario-specific delivery/event/callback counters, SDK commit SHA in metadata, and host OS/CPU metadata.

Performance SUT wire-level driver

The dedicated performance_sut binary and the conformance-only tck_sut binary are thin entry points over one shared runtime. This keeps their endpoint, transport, store, fixture, and shutdown behavior aligned while allowing only performance_sut to collect HTTP and subscription diagnostics. The performance runner builds performance_sut when needed, or accepts its path through A2A_PERF_SUT. Logs are captured as performance_sut_<store>_<port>.log for CI diagnosis.

Endpoint layout is the same as the TCK flow:

  • REST/HTTP+JSON: http://<host>:<port>/a2a
  • JSON-RPC: http://<host>:<port>/rpc
  • gRPC: <host>:<port + 1>

The SUT supports A2A_TCK_STORE_BACKEND=inmemory|postgres, A2A_TCK_POSTGRES_DSN, A2A_TCK_POSTGRES_SCHEMA, A2A_TCK_POSTGRES_POOL_SIZE (default 4), and the existing extended agent-card mode environment variable. The TCK conformance workflow explicitly starts the PostgreSQL-backed SUT with a pool size of 64, while the SDK-facing default remains 4 for compatibility. Run it manually with:

cmake --build build/performance --target performance_sut
./build/performance/tests/performance_sut 127.0.0.1:50061

Performance reports distinguish the low-overhead SDK service/store layer from transport-level coverage. In-process rows use driver_type=cpp_sdk_in_process and transport_path=in_process. Wire rows use driver_type=wire_tck_sut and one of wire_http_json, wire_jsonrpc, or wire_grpc. Wire coverage includes bounded list with and without pagination, send/create, get existing, cancel working, follow-up send, missing-task get errors, finite streaming, first-event subscription, and push config create/get/list/delete across gRPC, JSON-RPC, and HTTP+JSON. Streaming rows record event counts plus first-event and completion latency histograms. Known limitation: multi-subscriber subscription, disconnect isolation, terminal-completion subscription, and local HTTP callback fan-out are currently not full wire rows.

PostgreSQL command attribution

PostgreSQL result rows expose postgres_phase_latency_ms, postgres_phase_call_count, and postgres_phase_calls_per_operation. The phase names are stable: connection_acquire_wait, task_get, task_upsert, task_history_snapshot, task_history_lock_read, push_config_upsert, push_config_get, push_config_delete, push_config_list_count, push_config_list_select, transaction_begin, and transaction_commit. A command phase counts one invocation per PQexecParams call. Latency timers surround the database command only, rather than result parsing or service work. When one phase executes multiple commands during one operation, its latency sample is the cumulative command time for that phase within the operation; reported percentiles therefore describe per-operation phase totals, not individual command latency. Phase latency histograms include successful operations, while call counts include both successful and failed operations so failures do not hide database work. JSON retains the nested maps, while CSV and Markdown provide the same totals and calls per measured operation.

The combined PostgreSQL push-list statement is attributed to push_config_list_select; push_config_list_count remains part of the stable diagnostic schema but the final list path does not issue a separate count command. The local task-aware create statement, including the task-lock helper, is attributed entirely to push_config_upsert; it does not emit a separate task_get, transaction_begin, or transaction_commit phase.

Focused scenario fixture preparation must occur before the measured window; setup commands must not be attributed to the named operation.

PostgreSQL store costs

See storage authority and schema requirements for current task/push ownership, shared-pool, role, isolation and row-security contracts. A successful same-storage create/update uses one push command and one lease; shared-pool listing uses one combined statement. Separate-pool listing performs the authoritative task lookup plus one combined push statement. External/custom task stores remain authoritative.

These are structural command counts. Throughput and latency claims require controlled current-run artifacts; compare identical workloads, topology, build configuration and database settings.

Performance benchmarks

The SDK includes C++ microbenchmarks for core hot paths. Benchmarks are run in CI with threshold checks to catch accidental performance regressions.

Architecture

  • C++ / Google Benchmark measures SDK internals directly. This avoids Go-to-C++ boundary costs, process startup costs, and HTTP socket overhead when the benchmark is intended to isolate serialization, routing, task store, task lifecycle, UUID generation, or transport handling logic.
  • Go benchmark runner handles orchestration/reporting. It consumes Google Benchmark JSON, validates fixed thresholds from benchmarks/thresholds.json, emits a Markdown summary, and returns deterministic CI exit codes.

The Markdown summary groups results by component so the transport totals and their parse, conversion, projection, lifecycle, and response-building costs remain easy to compare as the suite grows.

Build and run locally

Benchmarks are not built by default. Use a Release build for meaningful numbers:

cmake -S . -B build-bench \
  -DCMAKE_BUILD_TYPE=Release \
  -DA2A_BUILD_BENCHMARKS=ON

cmake --build build-bench --target a2a_benchmarks -j"$(nproc)"

./build-bench/benchmarks/a2a_benchmarks

Run benchmarks with machine-readable output and threshold validation:

./build-bench/benchmarks/a2a_benchmarks \
  --benchmark_out=benchmark-results.json \
  --benchmark_out_format=json \
  --benchmark_repetitions=5 \
  --benchmark_report_aggregates_only=true

go run ./tools/bench_runner/cmd/a2a-bench-runner \
  --results benchmark-results.json \
  --thresholds benchmarks/thresholds.json \
  --summary benchmark-summary.md

You can also build the Go runner once:

go build -o build-bench/a2a-bench-runner ./tools/bench_runner/cmd/a2a-bench-runner

./build-bench/a2a-bench-runner \
  --results benchmark-results.json \
  --thresholds benchmarks/thresholds.json \
  --summary benchmark-summary.md

Thresholds

benchmarks/thresholds.json uses fixed upper bounds in nanoseconds. Initial thresholds are intentionally conservative so the CI job catches major regressions without being flaky on shared runners. To update thresholds intentionally:

  1. Run the Release benchmark job several times on comparable CI runners.
  2. Use aggregate mean values from Google Benchmark JSON.
  3. Set max_time_ns to a conservative multiple of observed CI means.
  4. Keep the Markdown summary artifact with the PR for review context.

Do not compare Debug or sanitizer benchmark results against Release thresholds. Debug and sanitizer builds add instrumentation and different optimization settings, so their timings are not a valid regression signal.

Adding a benchmark

  1. Add a deterministic C++ benchmark under benchmarks/ with a stable BM_<Component>_<Operation>_<Scenario> name.
  2. Avoid real network I/O and avoid logging inside benchmark loops.
  3. Move setup outside the measured loop unless setup cost is intentionally being measured.
  4. Use benchmark::DoNotOptimize(...) and benchmark::ClobberMemory() where appropriate.
  5. Add a corresponding entry to benchmarks/thresholds.json.
  6. Run the Go benchmark runner and inspect benchmark-summary.md.

Coverage notes

The current suite covers proto/JSON serialization for every protobuf response shape, JSON-RPC envelope parsing and serialization, REST query parsing and response building, task-store projection, serialization-free task lifecycle operations, UUIDv7 task ID generation, transport mux routing, REST and JSON-RPC transport handling, Agent Card generation, and the HTTP adapter.

A2A performance driver

a2a_performance_driver is the in-process C++ SDK performance driver used by scripts/run_performance_tests.sh and scripts/performance_runner.py. It runs a fixed set of report-only scenarios against the SDK’s example executor and prints a JSON array of per-scenario measurements.

What it measures

The driver covers task, streaming, subscription, push-configuration, and push notification paths. Each scenario reports:

  • operation counts and success/error totals;
  • throughput in operations per second;
  • latency percentiles (p50, p90, p95, p99) and maximum latency in milliseconds;
  • metadata identifying the transport label, store backend, and SDK dispatch path.

Warmup operations run before timing starts, so setup and warmup work are excluded from performance calculations. During measured execution, each worker records its own counters and latency samples, then the driver aggregates those samples after workers finish. This avoids adding result-collection mutex contention to the measured operation latency.

The historical wire streaming scenario names use one A2AClient per benchmark worker, preserving the topology used by earlier reports. HTTP+JSON and JSON-RPC also expose SendStreamingMessage_FiniteStream_SharedClient and SubscribeToTask_FirstEventLatency_SharedClient. Those variants route every measured worker through one A2AClient without changing the historical comparison rows. HTTP streaming easy handles are sharded across a process-wide pool of at most four libcurl reactors, while callbacks use the fixed shared dispatch pool. Reusable stream slots retain their reactor assignment so sequential finite streams keep connection-cache locality. gRPC does not run the shared-client variants. HTTP streaming rows include client_process_thread_count, allowing thread growth to be compared across concurrency levels without conflating the two client topologies.

HTTP wire rows also report finite-stream connection lifecycle diagnostics. The http_finite_stream_connections and http_completed_finite_streams fields count connections carrying finite streams and successfully completed finite streams. http_finite_streams_per_connection reports their ratio, while http_connections_reused_after_finite_stream counts successful parsing of a subsequent request on a connection after its terminal chunk. The counters are collected for the complete SUT run and are therefore shared by all scenario rows from that run.

Follow-up workloads

Follow-up fixtures are fully created before the measured region. Each measured operation uses a distinct task, so request count and execution order do not alter the task’s initial state:

  • SendMessage_FollowUpExistingTask starts with one history entry and measures one follow-up, representing the common first-follow-up case.
  • SendMessage_FollowUpAtHistoryDepth/8 starts with exactly eight history entries and measures one follow-up, explicitly exercising deeper-history processing without continually growing a shared hot task.

Both the in-process and wire drivers use these semantics. Their JSON and CSV rows include the numeric history_depth field in addition to the depth-bearing stress scenario name, keeping the workload distinction machine-readable.

Store backends

By default, scenarios use the in-memory stores owned by the example executor. To exercise PostgreSQL-backed stores, run with --store-backend postgres and set A2A_TEST_POSTGRES_DSN to a valid connection string. The driver creates a unique schema name for each PostgreSQL run.

Example

./build/tests/a2a_performance_driver \
  --transport grpc \
  --store-backend inmemory \
  --requests 1000 \
  --concurrency 4 \
  --warmup-seconds 1

For the canonical wrapper and generated summary artifacts, prefer:

./scripts/run_performance_tests.sh --store-backends inmemory --requests 1000 --concurrency 1,4

PostgreSQL tail validation

Run the focused tail-validation matrix against a local PostgreSQL instance with:

A2A_TEST_POSTGRES_DSN=postgresql://a2a:a2a@127.0.0.1:5432/a2a \
  ./scripts/run_performance_tests.sh --profile postgres-tail \
  --report-dir perf-artifacts/postgres-tail

The command runs five focused in-process scenarios five times for every combination of concurrency 4,16,64 and PostgreSQL pool size 4,16,64, using 2,000 requests and a one-second warmup. It writes per-run and median aggregate JSON, CSV, and Markdown reports under perf-artifacts/postgres-tail/. The report also records EXPLAIN (ANALYZE, BUFFERS) output and checks the task lookup and the explicit push-config created_sequence sort. The removed push-config ordering index must not appear in the combined plan.

Benchmark reports and trends

The CI benchmark job keeps the existing hard threshold check and records benchmark-trend.json and benchmark-trend-summary.md in its benchmark-results artifact, alongside the raw results and threshold summary. Artifacts are retained for 90 days, giving each commit a compact history point without publishing Pages or writing to a branch. Download these JSON files for longer-term analysis before the artifacts expire.

From the repository root, compare local Google Benchmark outputs:

go run ./tools/bench_runner/cmd/a2a-bench-trend \
  --results benchmark-results.json \
  --baseline-results previous-main/benchmark-results.json \
  --output benchmark-trend.json \
  --summary benchmark-trend-summary.md \
  --commit "$(git rev-parse HEAD)" \
  --environment 'ubuntu-24.04; Release -O3; threads=4; repetitions=5'

The compact schema contains schema_version (currently 1), commit SHA, CI run URL, UTC recording time, measured field, environment description, and sorted benchmark rows with name, mean_ns, and median_ns. Missing aggregates are omitted; zero timings are retained. Raw repetitions are averaged and sorted to compute a median if explicit Google Benchmark aggregates are absent. Values retain fractional nanoseconds. Standard deviation and coefficient of variation rows are excluded.

bash tools/bench_runner/scripts/compare-main.sh accepts the same command flags and finds the previous successful push run of ci.yml on main, created before the current CI run. It requires GITHUB_REPOSITORY, the gh CLI, and an Actions-read token in GH_TOKEN. The creation-time filter is applied by GitHub before the fetch limit, so newer runs cannot hide an older rerun’s baseline. It excludes the current run on reruns and never uses PR artifacts as baselines. It downloads the raw JSON, so runs predating the trend schema also work. If no baseline exists, the artifact has expired, or the API is unavailable (including limited fork permissions), it records the current snapshot and reports the absent baseline. Invalid downloaded JSON fails clearly. If the current run’s creation time cannot be retrieved, baseline lookup is skipped so a rerun cannot accidentally compare against a newer run.

PR benchmark job summaries show signed mean and median percentage changes for all benchmarks, including the key benchmarks covered by thresholds. Positive means slower; negative means faster. Added and missing benchmarks are identified; missing aggregates and zero denominators show n/a. Comparisons use real_time by default; --time-field cpu_time selects CPU timings in both input files. For local comparisons, use results from the same machine and build configuration. Hosted CI hardware can vary even with an identical runner label.

Signals use the median when both runs provide it, falling back to mean otherwise. --noise-percent defaults to 5: changes within ±5% are marked as noise. The CI benchmark job uses five repetitions. Trend changes are advisory and never fail a run; confirm a pattern over multiple runs before using it for roadmap decisions. The threshold runner and its exit codes are unchanged.

Validate both commands with gofmt, go vet ./..., go test -race ./..., and go build ./cmd/... from tools/bench_runner. The tests include compiled CLI and mocked GitHub artifact retrieval coverage and do not require network access.

Contributor validation

Run commands from the repository root. Contribution requirements and repository engineering rules remain in CONTRIBUTING.md, AGENTS.md, and cpp_conventions.md. Those files define the required checks and scoped exceptions. This chapter explains how to run the SDK validation tools.

SDK checks

./scripts/install_build_deps.sh
./scripts/verify_changes.sh

The verifier runs formatting, build, CTest and split clang-tidy profiles. For PostgreSQL, start a local database and set:

A2A_TEST_POSTGRES_DSN=postgresql://a2a:a2a@127.0.0.1:5432/a2a \
A2A_VERIFY_POSTGRES=1 ./scripts/verify_changes.sh

For optional signing, also set A2A_VERIFY_SIGNING=ON and install OpenSSL 3.0+ and simdjson 3.0+. Live TLS fixtures additionally require Python, libcurl, nginx and the OpenSSL CLI; use ./scripts/install_security_test_deps.sh. Tests that require an unavailable backend explicitly skip.

Coverage

python3 -m pip install --upgrade gcovr
./scripts/run_coverage.sh

This enforces:

  • src/core line coverage >= 85%
  • src/client line coverage >= 80%
  • src/server line coverage >= 80%

Additional profiles

Documentation-only changes use the scoped rules in AGENTS.md. Build the book with mdbook build book and check moved links before publishing.

Local SDK development

The repository’s dev/local/ directory contains local SDK development helpers.

PostgreSQL store

The PostgreSQL store is optional. A default build does not require PostgreSQL.

Start the local PostgreSQL container:

./dev/local/postgres_up.sh

Equivalent direct Docker Compose command:

docker compose -f dev/local/docker-compose.postgres.yml up -d

Configure and build with PostgreSQL support:

cmake -S . -B build-postgres \
  -DCMAKE_BUILD_TYPE=Debug \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DA2A_ENABLE_TESTING=ON \
  -DA2A_ENABLE_POSTGRES_STORE=ON
cmake --build build-postgres -j"$(nproc)"

Run PostgreSQL-enabled tests:

A2A_TEST_POSTGRES_DSN="postgresql://a2a:a2a@127.0.0.1:5432/a2a" ctest --test-dir build-postgres --output-on-failure

ThreadSanitizer validation

The ThreadSanitizer (TSan) profile is a focused race-detection check for SDK-owned concurrency. It uses Clang with -fsanitize=thread -fno-omit-frame-pointer, builds only the selected test executables, and runs tests carrying the tsan CTest label.

Run the same profile as CI from the repository root:

./scripts/run_thread_sanitizer.sh

Set A2A_TSAN_BUILD_DIR to use a build directory other than build-tsan. Set A2A_TSAN_CXX_COMPILER to select a particular Clang executable. TSAN_OPTIONS may also be set by a developer; CI uses the script default, halt_on_error=1.

Test selection

The profile covers:

  • stream-handle lifecycle, cancellation, and cancellation-watcher coordination;
  • the shared HTTP client reactor and dispatch executor lifecycle;
  • HTTP+JSON and JSON-RPC streaming, including cancellation;
  • subscription publication, cancellation, and shutdown;
  • in-memory task-store behavior; and
  • dispatcher and task-store integration.

The concrete executables are listed in scripts/run_thread_sanitizer.sh. Their discovered tests carry the tsan label in tests/CMakeLists.txt. To extend the profile, add the executable to the script’s TARGETS array and label its gtest_discover_tests call with LABELS "tsan".

PostgreSQL and gRPC transport integration tests are intentionally outside this focused profile. They add third-party runtime activity without improving coverage of the synchronization primitives targeted here. The selected HTTP tests retain libcurl coverage because the shared reactor is one of the principal race-detection targets.

No TSan suppression file is used. A report in the selected tests is therefore a failure. If verified third-party noise appears in the future, prefer narrowing the test selection; any unavoidable suppression must identify the specific external symbol and document the supporting investigation here.

Releases and Versions

This documentation is intended to stay version-aware without embedding a release number in every page title.

Unreleased development toward v0.6.0

ListTasks development replaces numeric offsets with opaque, versioned cursors and orders tasks by storage update time descending, then task ID descending. Clients must restart old pagination sequences with an empty token. Custom stores used with secured listing must supply aligned cursor metadata, and externally managed PostgreSQL schemas need the ordering-index migration. See the ListTasks cursor contract for compatibility, consistency and migration details.

SDK JSON parsing now requires simdjson 3.0+ even when signing is disabled. The obsolete public a2a/core/json_value.h structural scanner was removed. General JSON input is limited to 64 MiB and nesting depth 128. See the JSON parsing inventory for migration paths, protobuf compatibility exceptions, and ownership/input policies.

The stable v0.5.2 behavior and release notes below remain unchanged.

Current documented release

The current documented release is v0.5.2 and is recommended for new consumers.

Highlights since v0.5.1

SDK security and signed Agent Cards

The dispatcher can authenticate callers, enforce operation and task permissions, filter visible task counts and pages, and recheck permissions around blocking stream reads. Hidden and missing tasks share the same errors. The new TaskAuthorizationService persists explanatory auth_required states and coordinates revision-checked transitions with live subscriptions. Applications supply identity validation, permission rules and credential policy.

HTTP clients support certificate and hostname verification with per-call TLS options; gRPC uses native credentials. Optional Ed25519/JWS Agent Card signing uses RFC 8785 canonicalization and verifies original JSON before conversion to SDK types. Discovery preserves unknown signed fields and can revalidate cached cards against key rotation, revocation and expiry policies. Signing is disabled by default; enabling A2A_ENABLE_SIGNING and linking a2a::signing requires OpenSSL 3.0+ and simdjson 3.0+. See the security scenarios guide for application policy, supported signing features and live-test coverage.

Protocol versions and binding validation

Public C++ clients send A2A protocol versions on every operation across HTTP+JSON, JSON-RPC and gRPC. Negotiation matches Major.Minor and ignores numeric patch components. Servers reject malformed and unsupported versions before dispatch. Empty or omitted versions select the unsupported A2A 0.3 fallback and are rejected; clients should explicitly send 1.0. CallOptions::protocol_version allows an explicit selection. SDK release 0.5.2 and A2A protocol 1.0 are separate version numbers.

Independent C++ integration scenarios exercise all nine ordered binding pairs against a shared agent with both in-memory and PostgreSQL stores. SDK evidence and unmodified upstream TCK coverage are reported separately; passing SDK tests does not increase upstream coverage percentages.

CI retains compact benchmark trend artifacts and compares median timings with the preceding successful main run. A configurable noise band and advisory signals help identify changes that warrant confirmation across multiple runs; existing benchmark thresholds are unchanged. Go-only benchmark-runner changes have a focused formatting, vet, race-test and build validation path.

Documentation consolidation

Public SDK guidance now lives in this book, including complete storage and schema migration, security integration, examples and tutorials, and performance testing. Source-folder READMEs link to the SDK guides. Repository-wide contribution, agent, coding, security-reporting and support policies remain authoritative in the root repository files; they are not duplicated in this book. Duplicate guides and historical internal planning records are removed from the public documentation tree.

Compatibility notes

This release retains numeric ListTasks continuation tokens and creation-order listing. Omitted protocol-facing page sizes still default to 50, and explicit sizes must be between 1 and 100. Clients should copy next_page_token unchanged. Opaque cursors and descending update-time ordering from PR #312 are reserved for v0.6.0. The broader SDK JSON parsing migration in issue #311 is follow-up work; this release uses simdjson only in the optional signing path.

Raw clients that omit the A2A version must send A2A-Version: 1.0 (or gRPC a2a-version metadata). Configured security policies now enforce access before returning resources and can reject calls previously accepted without those checks. Review the application callbacks and task-authorization contract before upgrading secured deployments. Existing applications can continue with signing disabled; ordinary builds do not require OpenSSL or simdjson for signing.

Rebuild the SDK and downstream binaries together. Public request/context and dispatcher layouts have changed since v0.5.1; this release does not promise binary compatibility. Existing PostgreSQL schema and privilege requirements remain in effect; this release does not include the cursor-ordering indexes.

Previous release: v0.5.1

The following notes describe v0.5.1.

Highlights since v0.5.0

Multi-agent tutorials and MCP resources

Two standalone C++20 tutorials demonstrate Agent Card discovery, A2A delegation from a coordinator to a specialist, and structured artifacts: Job Application Assistant and Customer Support Copilot. They default to deterministic model responses and also support an optional OpenAI-compatible model endpoint.

The tutorial-local MCP client supports initialization, session handling, and textual resources/read validation. Job Application Assistant accepts local inputs or MCP resources; Customer Support Copilot retrieves tickets through OAuth-protected ContextForge with Keycloak. Docker Compose smoke flows cover both tutorials, while the native runner covers Job Application Assistant. See the production tutorials guide for setup and model configuration. This MCP integration is tutorial-local, not a new general-purpose public SDK client.

Streaming and subscription reliability

Synchronous HTTP stream completion now retains shared completion state through callback notification, avoiding lifetime races. Subscription cancellation waits until coroutine resumers have released the frame-owned resume mutex before destroying the frame. gRPC transports use timed reads for sessions that support them, observing cancellation without invoking Cancel() concurrently with a blocking Next(); other sessions retain the cancellation-watcher fallback.

A focused ThreadSanitizer profile and CI job exercise SDK-owned streaming, subscription, reactor, and in-memory store concurrency without a suppression file.

Performance harness reliability

Wire benchmarks now use a dedicated performance_sut entrypoint, keeping performance diagnostic endpoints and counters out of the conformance-focused tck_sut. Both share the transport lifecycle runtime. Each wire scenario runs as a separate driver invocation against the shared SUT; periodic health checks report unexpected SUT exits with the active workload, exit code or POSIX signal, and log tail, then stop the driver promptly.

This release improves diagnostic isolation and failure reporting. It does not introduce a separate non-blocking performance HTTP server or claim a new measured throughput improvement.

Cross-platform test execution and portability

Windows and macOS CI now explicitly enable testing and run CTest after the build, with failure output and an error for an empty suite. macOS selects all registered tests; Windows selects all C++ tests and applicable Python checks, excluding only three documented script tests that depend on POSIX execution or a compilation database unavailable with Visual Studio.

The expanded execution caught and fixed libcurl test selection, a client-test lifetime error, gRPC unit-test runtime initialization, accepted HTTP socket mode and idle shutdown differences, and protobuf-version-dependent duplicate field alias handling in flat JSON-RPC requests. HTTP persistence regressions cover sequential reuse, pipelining, fragmented requests, concurrency, and idle shutdown.

Compatibility notes

No public APIs are intentionally removed. ServerStreamSession gains a virtual SupportsTimedNext() const noexcept method whose default is false, so existing derived classes remain source-compatible. Sessions opting in must implement the timed-read contract through NextFor(). The public HTTP header lookup helper also gains an overload for ordered header containers. Rebuild the SDK and downstream binaries together; the added virtual method changes the class vtable and this release does not promise binary compatibility with v0.5.0.

Custom performance tooling should use performance_sut and A2A_PERF_SUT; conformance tooling continues to use tck_sut. The historical wire result value driver_type=wire_tck_sut remains unchanged for report compatibility. Pagination and PostgreSQL schema/privilege requirements from v0.5.0 remain in effect.

Earlier release: v0.5.0

The following notes describe v0.5.0; its benchmark comparisons are historical evidence for that release, not measurements of v0.5.1.

Highlights since v0.4.1

PostgreSQL write scalability

The built-in PostgreSQL stores reduce redundant task reads and database round trips on write paths. Push-configuration create and delete coordination now uses schema- and task-scoped transaction advisory locks instead of task-row FOR KEY SHARE locks, and the push-configuration schema reduces index and write amplification. Task-history persistence uses a bounded, optimistic, revision-aware update, with created_sequence included in compare-and-swap protection against delete/recreate ABA cases. These changes preserve transaction, task-history, concurrency, and least-privilege correctness.

In normal performance artifacts collected on GitHub-hosted runners, the geometric-mean movement across the c1, c4, c16, and c64 PostgreSQL in-process coordinates was approximately:

ScenarioThroughputp95
SendMessage_CreateTask+60.3%-36.4%
SendMessage_FollowUpExistingTask+51.5%-33.9%
PushConfig_Create+20.6%-1.7%
PushConfig_CreateMany+22.3%-19.8%

These controlled CI measurements are benchmark evidence, not guaranteed application performance. In particular, the PushConfig_Create c64 p95 coordinate was noisy across independent runs; the results do not imply that all PostgreSQL tail-latency coordinates improved.

Streaming scalability and latency

Synchronous HTTP streaming now runs through bounded, process-wide libcurl multi-reactors rather than assigning an OS worker thread to every stream by default. Linux builds integrate epoll, eventfd, and timerfd; other platforms use a portable libcurl multi-event fallback. A separate bounded callback executor preserves serialized callback ordering within each stream and limits callback backlog without blocking network progress.

The streaming paths also reduce SSE parsing and framing allocations and copies, avoid unnecessary JSON/protobuf conversions, and safely reuse HTTP connections after finite streams. Cancellation, shutdown, object destruction, and callback races are handled without changing the existing public synchronous APIs.

A c64 in-memory wire comparison between the v0.4.1 normal performance artifact 9277084128 and current-main artifact 10403618734 reported:

ScenarioTransportThroughput deltaFirst-event p95 deltaCompletion p95 delta
Finite streamgRPC+21.3%-13.6%-15.2%
Finite streamHTTP+JSON+86.6%-37.6%-36.6%
Finite streamJSON-RPC+92.1%-38.9%-38.8%
SubscribegRPC+12.4%-21.4%-13.6%
SubscribeHTTP+JSON+32.7%-52.6%-43.3%
SubscribeJSON-RPC+21.6%-48.0%-40.2%

Both artifacts reported zero operation errors. As with the PostgreSQL results, these controlled CI measurements characterize those runs and are not universal production guarantees.

Performance observability

Performance tooling now provides focused PostgreSQL write diagnostics, including wait-event, lock, WAL, and buffer attribution, plus command-level phase diagnostics. Markdown reports expose first-event and stream-completion p50/p95 columns, streaming-specific rollups, and n/a rather than misleading zeroes for streaming dimensions that do not apply.

PostgreSQL production hardening

Managed task-aware push schemas now validate during startup that the effective push-store role can execute a2a_lock_task_for_push_config(TEXT). Administrative TRUNCATE a2a_tasks operations remove locally owned push configurations while preserving externally owned configurations.

SDK-managed schemas migrate to the current task-aware push-configuration schema version. Operators of externally managed PostgreSQL schemas must apply the helper, trigger, and privilege requirements in the storage documentation; missing required schema objects or privileges fail validation early.

Compatibility notes

There are no intentional public API removals in v0.5.0. Existing synchronous A2AClient, streaming observer, transport, and server APIs remain source-compatible. HTTP streaming execution changed internally, not at the public API level.

The pagination behavior documented for v0.4.1 remains unchanged: omitted protocol-facing ListTasks.page_size defaults to 50, explicit values must be between 1 and 100, and callers follow next_page_token for additional pages.

PostgreSQL users should allow SDK-managed schemas to migrate. Externally managed schemas may require migration to satisfy the current validation contract, including helper functions, trigger wiring, schema access, and function EXECUTE privileges. The task-aware push-configuration delete and truncate coordination must run at READ COMMITTED; repeatable-read and serializable transactions are rejected because a stale snapshot cannot safely perform the required cleanup. These are operational schema requirements rather than public C++ API removals.

Earlier release: v0.4.1

v0.4.1 optimized PostgreSQL push-configuration and task persistence paths, added HTTP/1.1 reuse for unary HTTP transports, hardened typed ListTasks validation, expanded component performance diagnostics, and introduced repository-wide Conventional Commit validation.

Its compatibility behavior remains relevant: public include paths and exported CMake targets were unchanged by the internal transport source reorganization, and valid ListTasks responses remain compatible across HTTP+JSON and JSON-RPC.

Earlier release: v0.4.0

v0.4.0 focused on configurable PostgreSQL pool sizing, bounded protocol-facing ListTasks pagination, optimized in-memory task listing, interruptible gRPC stream cancellation, expanded performance validation, and centralized HTTP server response construction.

Versioning guidance

  • Pin CMake FetchContent integrations to a release tag such as v0.5.2 or to a reviewed commit.
  • Prefer find_package(a2a_cpp CONFIG REQUIRED) for installed SDK packages.
  • Keep generated protobuf headers and linked SDK libraries from the same installed package or build tree.
  • Review release notes before upgrading between versions.

Documentation policy

Page titles and navigation should remain mostly version agnostic. Release-specific notes belong on this page or in clearly marked compatibility sections.

API Reference

The generated C++ API reference is built from public headers under include/a2a/**.

Generated reference

When published with the documentation site, open:

Generate locally

./scripts/generate_api_reference.sh

The script writes generated pages to book-build/api/cpp.

Public API areas

  • a2a::core: results, errors, protocol constants, JSON/protobuf helpers, Agent Card support, task state helpers, and versioning.
  • a2a::client: A2AClient, transports, discovery, auth hooks, call options, interceptors, and streaming observers.
  • a2a::server: executor, dispatcher, transports, interceptors, task stores, task lifecycle helpers, push notifications, and Agent Card serialization.
  • a2a::http: shared outbound HTTP client abstraction used by default REST/JSON-RPC/discovery/push paths when libcurl is enabled.