Cogitator
Integrations

A2A Protocol (Agent-to-Agent)

Native implementation of the A2A protocol, 1.0 and 0.3 on one server, for cross-framework agent interoperability.

Overview

The @cogitator-ai/a2a package implements the A2A (Agent2Agent) protocol, the open standard for agent-to-agent communication, in both of its current versions: 1.0 and 0.3, on the same server. Cogitator agents talk to agents from any framework that speaks A2A (the official A2A SDKs, Google ADK, LangGraph and others) over JSON-RPC 2.0, and over the A2A 1.0 HTTP+JSON (REST) binding.

  • A2AServer - expose any Cogitator agent as an A2A service, one Agent Card and endpoint per agent, both versions at once
  • A2AClient - talk to any A2A agent: it speaks 1.0 when the card offers it, else 0.3, over JSON-RPC or HTTP+JSON
  • asTool() Bridge - wrap remote A2A agents as local Cogitator tools
  • Framework Adapters - Express, Hono, Fastify, Koa, Next.js

Conformance is tested: every response is validated against the official 1.0.0 and 0.3.0 JSON schemas, and the official A2A JavaScript SDK (1.3 and 0.3) talks to A2AServer (and A2AClient to a server built with the SDK) in the test suite, over JSON-RPC and REST.

pnpm add @cogitator-ai/a2a

A2AServer

Exposing Agents

import { Cogitator, Agent } from '@cogitator-ai/core';
import { A2AServer } from '@cogitator-ai/a2a';
import { a2aExpress } from '@cogitator-ai/a2a/express';
import express from 'express';

const cogitator = new Cogitator();

const researcher = new Agent({
  name: 'researcher',
  description: 'Research agent that finds information',
  model: 'openai/gpt-6.1-sol',
  instructions: 'You are a research assistant.',
});

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
});

const app = express();
app.use(a2aExpress(a2aServer));
app.listen(3000);

This exposes:

  • GET /.well-known/agent-card.json - Agent Card discovery, in the version the client asks for
  • POST /a2a - JSON-RPC endpoint for messaging, streaming and task management, A2A 1.0 with A2A-Version: 1.0, else 0.3
  • /a2a/rest/... - the A2A 1.0 HTTP+JSON binding
  • GET /.well-known/agent.json - the pre-v0.3 card path, kept as an alias

basePath (default /a2a, must start with /) is the JSON-RPC path the adapters serve, relative to where they are mounted, readable as a2aServer.basePath. restPath (default <basePath>/rest, false turns it off) is where the REST binding is served. When an agent is named rest, its endpoint is the default restPath: the server then leaves REST off with a warning, and an explicit restPath that is an agent's endpoint is refused.

Protocol Versions

A request names its protocol version in the A2A-Version header, or in an A2A-Version query parameter, as Major.Minor (a patch number is ignored). A request without a version speaks 0.3, as the specification says, so every A2A 0.3 client keeps working unchanged. One with A2A-Version: 1.0 gets A2A 1.0: the PascalCase methods, the ProtoJSON model, google.rpc error details. A version the server does not speak is refused with -32009 Version not supported (HTTP 400 on REST), its ErrorInfo metadata listing the supported versions.

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  protocolVersions: ['1.0', '0.3'], // the default, ['0.3'] restores the earlier server
  restPath: '/a2a/rest', // the default, false turns the REST binding off
});

What changes on the wire in 1.0:

A2A 0.3A2A 1.0
kind on parts, messages, tasks and eventsNo kind, a StreamResponse wraps task, statusUpdate and so on
role: 'user', state: 'completed'role: 'ROLE_USER', state: 'TASK_STATE_COMPLETED'
TextPart, FilePart, DataPartOne Part: text, raw, url or data, plus mediaType
final: true on the last status updateThe stream closes on a terminal or interrupted state
blocking: falsereturnImmediately: true
message/send, tasks/get and so onSendMessage, GetTask and so on
error.data is an objecterror.data is a list of google.rpc.ErrorInfo and BadRequest

The server keeps one model of every task, so a task created over 0.3 is readable over 1.0 and back, and the task stores (InMemoryTaskStore, RedisTaskStore, your own TaskStore) are unchanged. A 1.0 data part may hold any JSON value: a value that is not an object is kept as { value } with the part metadata key cogitator:dataValue, the only form a 0.3 data part has, and comes back bare over 1.0. ProtoJSON input is read leniently: fields in camelCase or snake_case, enums by name or number, bytes in standard or URL-safe base64.

Agent Cards

The card is generated from the agent and comes in the version the client asks for. Without A2A-Version it is the A2A 0.3 card with every interface of both versions added in supportedInterfaces, so a client of either version finds its endpoint:

{
  "protocolVersion": "0.3.0",
  "name": "researcher",
  "description": "Research agent that finds information",
  "url": "https://my-server.com/a2a",
  "preferredTransport": "JSONRPC",
  "additionalInterfaces": [{ "transport": "JSONRPC", "url": "https://my-server.com/a2a" }],
  "supportedInterfaces": [
    {
      "url": "https://my-server.com/a2a",
      "protocolBinding": "JSONRPC",
      "tenant": "researcher",
      "protocolVersion": "1.0"
    },
    {
      "url": "https://my-server.com/a2a/rest",
      "protocolBinding": "HTTP+JSON",
      "tenant": "researcher",
      "protocolVersion": "1.0"
    },
    { "url": "https://my-server.com/a2a", "protocolBinding": "JSONRPC", "protocolVersion": "0.3" }
  ],
  "version": "1.0.0",
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": false,
    "extensions": [{ "uri": "https://cogitator.app/a2a/extensions/tool-approvals/v1" }]
  },
  "defaultInputModes": ["text/plain", "application/json"],
  "defaultOutputModes": ["text/plain", "application/json"],
  "skills": [
    {
      "id": "web_search",
      "name": "web_search",
      "description": "Search the web",
      "tags": ["tool"],
      "inputModes": ["text/plain", "application/json"],
      "outputModes": ["text/plain", "application/json"]
    }
  ]
}

With A2A-Version: 1.0 it is the pure A2A 1.0 card: the same supportedInterfaces, capabilities with extensions and extendedAgentCard, securitySchemes and securityRequirements in their 1.0 form, and none of the 0.3 fields. The interfaces come in the order clients should prefer them: JSON-RPC 1.0, HTTP+JSON 1.0, JSON-RPC 0.3. A server that speaks one version only serves its card to everyone.

The URLs are absolute: without cardUrl the adapters derive them from the request that fetches the card, behind a proxy that changes the host or the path set cardUrl to the public URL of the JSON-RPC endpoint (the REST interface sits next to it as restPath sits next to basePath). The description is the agent's description (its name when unset), never its instructions. Every tool becomes a skill, and an agent without tools gets one chat skill, as A2A 1.0 needs a card to list one. agentVersion sets version (default 1.0.0) and provider: { organization, url } names who runs the agent. With auth the card lists its security schemes, with extendedCardGenerator it declares the extended card, and with cardSigning it carries a JWS in signatures.

Card responses carry Vary: A2A-Version, an ETag (the SHA-256 of the body) and Cache-Control: public, max-age=300. A request with a matching If-None-Match gets 304 Not Modified.

Multiple Agents

const a2aServer = new A2AServer({
  agents: { researcher, writer },
  cogitator,
});

Every agent gets its own card and endpoint, so any A2A client reaches it by URL:

RouteServes
GET /.well-known/agent-card.jsonCard of the first agent
POST <basePath>First agent, or the one named by an agentName param
GET <basePath>/<agent>/.well-known/agent-card.jsonCard of <agent>, whose url is <basePath>/<agent>
POST <basePath>/<agent><agent>
GET /.well-known/agent.jsonPre-v0.3 path: the card, or every card in an array
import { ClientFactory } from '@a2a-js/sdk/client';

// any A2A v0.3 client: point it at the agent's base URL
const writer = await new ClientFactory().createFromUrl('https://my-server.com/a2a/writer/');

// A2AClient: name the agent
const writerClient = new A2AClient('https://my-server.com', { agentName: 'writer' });

An unknown agent path answers 404, an unknown agentName param -32602 Invalid params.

Tenants

Over A2A 1.0 every agent is a tenant. Its interfaces carry its name as tenant, and an A2A 1.0 client sends it back in every request: as tenant in the JSON-RPC params, as the /<tenant>/ path segment on REST. On the shared endpoint the tenant picks the agent, on an agent's own endpoint a different tenant is refused with -32602.

A task created over 1.0 belongs to the agent that created it and is visible only through that agent, whatever the version of the request: GetTask, CancelTask, SubscribeToTask, the push config methods, ListTasks (and their 0.3 forms, tasks/list included) and a message that continues the task answer a task of another agent with -32001 Task not found. The agent is kept in the task metadata (cogitator:agent) and never sent to clients. Tasks created over 0.3, and tasks stored before tasks recorded their agent, are bound to no agent and stay visible to every agent, as they always were. A new message whose contextId holds a task bound to another agent is refused with -32602 Invalid params, over either version, so an agent never reads another agent's transcripts or ends its paused runs.

On REST, a first path segment that is the name of an agent is read as its tenant first: with an agent named tasks, GET /tasks/tasks lists that agent's tasks, and a path that names no method under the tenant (GET /tasks/<id>) still reads without one.

HTTP+JSON Binding

The A2A 1.0 REST binding is served under restPath, with the routes the proto's google.api.http bindings define. Every route also exists under /<tenant>/:

RouteMethodSuccess
POST /message:sendSendMessage200
POST /message:streamSendStreamingMessage (SSE)200
GET /tasks/{id}?historyLength=GetTask200
GET /tasks?contextId=&status=&pageSize=&pageToken=ListTasks200
POST /tasks/{id}:cancelCancelTask200
GET or POST /tasks/{id}:subscribeSubscribeToTask (SSE)200
POST /tasks/{taskId}/pushNotificationConfigsCreateTaskPushNotificationConfig201
GET /tasks/{taskId}/pushNotificationConfigsListTaskPushNotificationConfigs200
GET /tasks/{taskId}/pushNotificationConfigs/{id}GetTaskPushNotificationConfig200
DELETE /tasks/{taskId}/pushNotificationConfigs/{id}DeleteTaskPushNotificationConfig204
GET /extendedAgentCardGetExtendedAgentCard200
curl -X POST https://my-server.com/a2a/rest/researcher/message:send \
  -H 'Content-Type: application/a2a+json' -H 'A2A-Version: 1.0' \
  -d '{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"Hello"}]}}'

Bodies are application/a2a+json or application/json, query parameters camelCase (includeArtifacts=true). The binding speaks only A2A 1.0, so every request needs A2A-Version: 1.0. Errors are google.rpc.Status bodies with the HTTP status of the specification:

{
  "error": {
    "code": 404,
    "status": "NOT_FOUND",
    "message": "Task not found: task_123",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "TASK_NOT_FOUND",
        "domain": "a2a-protocol.org",
        "metadata": { "taskId": "task_123" }
      }
    ]
  }
}

Streams are SSE whose events are StreamResponse objects (data: {"statusUpdate":{...}}), and a failure during a stream ends it with an event: error frame holding such a body. Custom integrations call a2aServer.handleRest({ method, path, query, body, authToken }) with a path relative to restPath.

Run time limits

A client may ask for a shorter run with configuration.timeout (a Cogitator extension), never a longer one. It must be a positive integer, and the server caps it at the agent's own timeout, or at maxRunTimeoutMs (default 120000, the Cogitator run default) for an agent without one:

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  maxRunTimeoutMs: 300_000,
});

Without a client timeout the agent's own limit applies. An A2A 1.0 client asks for it with the run-timeout extension, metadata["https://cogitator.app/a2a/extensions/run-timeout/v1"].timeoutMs on the SendMessage request.

A2AClient

Connecting to a Remote Agent

import { A2AClient } from '@cogitator-ai/a2a';

const client = new A2AClient('https://remote-agent.example.com');

const card = await client.agentCard();
console.log(card.name, card.description, card.skills);

The client reads the card at /.well-known/agent-card.json (falling back to /.well-known/agent.json for servers before v0.3) and talks to an interface the card names, as the specification requires. It reads every form of card: an A2A 0.3 card, the hybrid card of a Cogitator server, and a pure A2A 1.0 card. By default (protocolVersion: 'auto') it speaks A2A 1.0 when the card offers a 1.0 interface, taking the first one the card lists (or the one of transport) and sending that interface's tenant in every request, else JSON-RPC 0.3. Its API speaks the A2A 0.3 model either way, so code written for 0.3 keeps working against a 1.0 server, and agentCard() returns the card in the 0.3 form with every interface in supportedInterfaces.

OptionEffect
headersSent with every request, e.g. Authorization
timeoutRequest timeout in ms (default 30000), the idle timeout between events of a stream
agentCardPathCard path relative to the base URL, without fallback
rpcPathSend JSON-RPC to this path at the base URL instead of the card's interface, without the card
agentNameAn agent of a Cogitator server hosting several: use its own card and endpoint
protocolVersion'auto' (default), '1.0' (refuse a server without 1.0, -32009) or '0.3' (always 0.3)
transport'JSONRPC' or 'HTTP+JSON': the A2A 1.0 binding to prefer when the card offers both
extensionsExtension URIs to ask for in A2A-Extensions on every request
const client = new A2AClient('https://remote-agent.example.com', { transport: 'HTTP+JSON' });
console.log(await client.endpoint());
// { protocolVersion: '1.0', transport: 'HTTP+JSON', url: 'https://.../a2a/rest', tenant: 'researcher' }

Sending Messages

const result = await client.sendMessage({
  role: 'user',
  parts: [{ kind: 'text', text: 'Research quantum computing trends' }],
});

if (result.kind === 'task') {
  console.log(result.status.state); // 'completed'
  console.log(result.artifacts); // [{ artifactId, parts: [{ kind: 'text', text: '...' }] }]
}

sendMessage returns the task the server started or continued, or a direct reply message (kind: 'message') from servers that answer that way. The client fills in kind: 'message' and a fresh messageId when a message leaves them out. Parts are { kind: 'text', text }, { kind: 'data', data } and { kind: 'file', file: { uri | bytes, mimeType?, name? } }.

Streaming

for await (const event of client.sendMessageStream({
  role: 'user',
  parts: [{ kind: 'text', text: 'Analyze market trends' }],
})) {
  console.log(event.kind, event);
}

Send Configuration

OptionEffect
blocking: falseReturn the task at once (submitted), poll getTask or use a webhook
historyLengthReturn only the last N history messages (0 = none), also on getTask
acceptedOutputModesOnly return artifacts with a part of these MIME types
pushNotificationConfigRegister a webhook before the task starts executing
timeoutCogitator extension: a shorter run time limit in ms, see above

Over A2A 1.0 the client sends the 1.0 SendMessageConfiguration: returnImmediately: true for blocking: false, taskPushNotificationConfig for the webhook, and the run timeout as metadata["https://cogitator.app/a2a/extensions/run-timeout/v1"].timeoutMs in the request (the run-timeout extension). A historyLength of 0 leaves the history out of a 1.0 task altogether.

const task = await client.sendMessage(
  { role: 'user', parts: [{ kind: 'text', text: 'Long running analysis' }] },
  { blocking: false, pushNotificationConfig: { url: 'https://my-app.com/hooks/a2a' } }
);

Task Management

const task = await client.getTask('task_abc123', 5);
await client.cancelTask('task_abc123');

for await (const event of client.resubscribeTask('task_abc123')) {
  console.log(event.kind);
}

asTool() Bridge

Wrap any remote A2A agent as a local Cogitator tool:

const client = new A2AClient('https://research-agent.example.com');
const card = await client.agentCard();

const remoteTool = client.asToolFromCard(card, {
  name: 'remote_researcher',
  description: 'Delegate research to remote agent',
});

const orchestrator = new Agent({
  name: 'orchestrator',
  model: 'openai/gpt-6.1-sol',
  instructions: 'Use the remote_researcher for information gathering.',
  tools: [remoteTool],
});

const result = await cogitator.run(orchestrator, {
  input: 'Write a report on AI trends',
});

The orchestrator calls the remote agent like any tool with a single task string parameter. asToolFromCard names and describes the tool from the card unless you override them, client.asTool({ name?, description?, timeout? }) does the same without a card (default name a2a_remote_agent). A card's name is meant for people, so it is turned into a name every LLM provider accepts, as normalizeToolName does: a card named Research Agent gives the tool Research_Agent. A name you pass is used as it is, so keep it to letters, digits, _ and -. The tool is marked with the external side effect and forwards the run's abort signal.

The tool result is { output, success, error?, taskId?, state?, pendingApprovals? }. output is the text of the task's status message, else of its last agent message, else of its artifacts. When the remote agent asks a question (state: 'input-required'), output holds the question and taskId lets you answer. When it waits for tool approvals, pendingApprovals lists the calls.

Multi-Turn Conversations

Answering a question

A task that waits on the client (input-required, or auth-required) takes the answer as a message with its taskId. The server appends it to the task and runs the agent again with the task transcript:

const task = await client.sendMessage({
  role: 'user',
  parts: [{ kind: 'text', text: 'Book a flight to Paris' }],
});

if (task.kind === 'task' && task.status.state === 'input-required') {
  // the question is in task.status.message
  const answered = await client.continueTask(task.id, 'Next Friday');
}

Carrying a conversation on

A task in a terminal state (completed, failed, canceled, rejected) can't be restarted (section 7.1 of the specification): a message for it is refused with -32600 Invalid request. Send a new message in the same contextId instead:

const first = await client.sendMessage({
  role: 'user',
  parts: [{ kind: 'text', text: 'Research quantum computing' }],
});

const next = await client.sendMessage({
  role: 'user',
  contextId: first.kind === 'task' ? first.contextId : undefined,
  parts: [{ kind: 'text', text: 'Now compare it with classical computing' }],
});

Runs are threaded by contextId (threadId), and the agent gets the transcript of the earlier tasks of the context, so follow-ups work even without a memory adapter. Artifacts accumulate across the turns of a task. A task that is still running takes no second message.

Tool Approvals

When the agent calls a tool that needs approval (requiresApproval), its run pauses and the task waits in input-required, never completed. Its status message says Waiting for approval of <tools> and carries the waiting calls in a data part ({ kind: 'tool-approval-request', approvals: [{ toolCallId, toolName, arguments, description }] }). The client answers with a tool-approval-response data part in the message that continues the task, and the server resumes the run with those decisions:

import { readToolApprovalRequest } from '@cogitator-ai/a2a';

const task = await client.sendMessage({
  role: 'user',
  parts: [{ kind: 'text', text: 'Refund A-1' }],
});

const waiting = task.kind === 'task' ? readToolApprovalRequest(task) : undefined;
if (waiting) {
  await client.answerApprovals(task.id, {
    decisions: { [waiting[0].toolCallId]: { approved: true } },
  });
}

toolApprovalResponsePart({ decisions?, defaultDecision? }) builds the part for a hand-written message. Calls left without a decision keep the task waiting, a text reply declines them and moves on. The server resumes through cogitator.resume() by the task's contextId, so the paused run has to be where the server Cogitator keeps paused runs (its memory, or runCheckpoints shared by every server instance).

Listing Tasks

A2A 1.0 ListTasks pages through the caller's tasks of the agent, the most recently updated first (ties broken by id in the cursor's order), behind a keyset cursor: a page never repeats or skips a task that did not change while the client paged.

const page = await client.listTasksPage({ state: 'completed', pageSize: 20 });
console.log(page.tasks.length, page.totalSize);

if (page.nextPageToken) {
  const next = await client.listTasksPage({ state: 'completed', pageToken: page.nextPageToken });
}
Query fieldEffect
pageSize1 to 100, default 50
pageTokenThe nextPageToken of the previous page
contextId, stateFilters (status with a TASK_STATE_* on the wire)
statusTimestampAfterOnly tasks whose status changed after this ISO time
historyLengthTrim each history, 0 leaves it out
includeArtifactsInclude artifacts (default false, then the field is absent)

The response carries tasks, nextPageToken ('' on the last page), pageSize and totalSize (the matches across all pages). A page token the server did not issue is refused with -32602, its BadRequest naming pageToken. The cursor is base64url of { v: 1, t, id } over TaskStore.list(), so any store works: the cursor sorts the tasks itself, and tasks/list keeps the order of the store.

Over A2A 0.3, tasks/list is a Cogitator extension method with offset paging. client.listTasks(filter?) lists every match in either version (over 1.0 it walks the pages, with artifacts):

const allTasks = await client.listTasks();
const conversationTasks = await client.listTasks({ contextId: 'ctx_abc123' });
const completedTasks = await client.listTasks({ state: 'completed', limit: 10, offset: 0 });

Streaming

message/stream answers with Server-Sent Events. Every event is a JSON-RPC response carrying the request id, its result is the task, a status-update or an artifact-update:

data: {"jsonrpc":"2.0","id":1,"result":{"kind":"task","id":"task_1","status":{"state":"submitted"},...}}

data: {"jsonrpc":"2.0","id":1,"result":{"kind":"status-update","taskId":"task_1","status":{"state":"working"},"final":false,...}}

data: {"jsonrpc":"2.0","id":1,"result":{"kind":"artifact-update","artifact":{"artifactId":"art_1","parts":[{"kind":"text","text":"Roses"}]},"lastChunk":false,...}}

data: {"jsonrpc":"2.0","id":1,"result":{"kind":"artifact-update","artifact":{"artifactId":"art_1","parts":[{"kind":"text","text":" are red"}]},"append":true,"lastChunk":true,...}}

data: {"jsonrpc":"2.0","id":1,"result":{"kind":"status-update","taskId":"task_1","status":{"state":"completed",...},"final":true,...}}
for await (const event of client.sendMessageStream({
  role: 'user',
  parts: [{ kind: 'text', text: 'Write a poem about the ocean' }],
})) {
  if (event.kind === 'artifact-update') {
    for (const part of event.artifact.parts) {
      if (part.kind === 'text') process.stdout.write(part.text);
    }
  }
  if (event.kind === 'status-update' && event.final) {
    console.log(`\n${event.status.state}`);
  }
}

The reply streams token by token as chunks of one artifact: the first chunk starts it, the next ones carry append: true, the last one lastChunk: true. When the final reply differs from the streamed text (text the model wrote before a tool call, for instance), the last chunk replaces the artifact (append: false), so the artifact a client assembles is always the one tasks/get returns. Artifacts arrive before the final status update, and the stream ends after the status update with final: true (a terminal state, input-required or auth-required).

A request that fails before the stream starts (bad params, unknown task, missing credentials) is answered with a plain JSON-RPC error instead of a stream, a failure during the stream ends it with a JSON-RPC error response. tasks/resubscribe reconnects to a task: the task as it is now, then its updates while it still runs in this process. When the client disconnects, the adapters abort the agent run.

Over A2A 1.0, SendStreamingMessage streams a StreamResponse in every result, and there is no final: the stream closes after the status update that ends the task or makes it wait on the client.

data: {"jsonrpc":"2.0","id":1,"result":{"task":{"id":"task_1","contextId":"ctx_1","status":{"state":"TASK_STATE_SUBMITTED"}}}}

data: {"jsonrpc":"2.0","id":1,"result":{"artifactUpdate":{"taskId":"task_1","contextId":"ctx_1","artifact":{"artifactId":"art_1","parts":[{"text":"Roses"}]}}}}

data: {"jsonrpc":"2.0","id":1,"result":{"statusUpdate":{"taskId":"task_1","contextId":"ctx_1","status":{"state":"TASK_STATE_COMPLETED"}}}}

A2AClient marks that last update final for you, so the loop above works over both versions. SubscribeToTask refuses a task that already ended with -32004, as the specification says.

Tasks Carried Out Elsewhere

A task does not have to be run by a Cogitator agent. TaskManager.advanceTask() moves a task that something outside the manager carries out (another process, a person, an agent of another runtime) through the same lifecycle, with the same events and the same store:

import { TaskManager, textPart, toMessage } from '@cogitator-ai/a2a';

const tasks = new TaskManager({ taskStore });
const fromClient = (text: string) => toMessage({ role: 'user', parts: [textPart(text)] });

const task = await tasks.createTask(fromClient('Write the tests'), undefined, {
  metadata: { 'acme:ticket': 'OPS-12' },
});

await tasks.advanceTask(task.id, { state: 'working' });
await tasks.advanceTask(task.id, {
  state: 'input-required',
  message: 'Mock Redis or run a real one?',
});
await tasks.continueTask(task.id, fromClient('Mock it'));
await tasks.advanceTask(task.id, { state: 'completed', message: 'Done: 14 tests pass' });

The message is recorded as the agent's: added to the history and kept as the status message. Changes of one task's state run one after another, moves, cancels and client messages alike, so two made at once do not overwrite each other. A task does not move (taskNotContinuable) when it is in a terminal state, when a run of the manager is executing it, or when a run of the manager paused on it for approvals or answers. createTask takes metadata to store with the task in the same write. The keys the manager keeps for itself (owner, agent, creation time) are dropped from it, so metadata passed on from a client cannot set them. The agent bridge runs its jobs this way.

RedisTaskStore

import { A2AServer, RedisTaskStore } from '@cogitator-ai/a2a';
import Redis from 'ioredis';

const redis = new Redis('redis://localhost:6379');

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  taskStore: new RedisTaskStore({
    client: redis,
    keyPrefix: 'a2a:task:',
    ttl: 86400,
  }),
});

RedisTaskStore implements the full TaskStore interface, including list() with filtering by contextId and state, pagination and newest-first sorting. Updates are atomic when the client supports eval (Lua).

Push Notifications

The server POSTs the task to every webhook registered for it on each status change. A config keeps the protocol version it was registered with (the server never sends it back): one registered over A2A 0.3 gets the task as tasks/get returns it, as application/json. One registered over A2A 1.0 gets a StreamResponse, { "task": { ... } } in the 1.0 form, as application/a2a+json, with Authorization: <scheme> <credentials> for the one scheme of its authentication.

Registering Webhooks

const config = await client.setPushNotificationConfig(task.id, {
  url: 'https://my-app.com/webhooks/a2a',
  token: 'per-task-secret',
  authentication: { schemes: ['Bearer'], credentials: 'my-webhook-token' },
});

The webhook request carries X-A2A-Notification-Token: <token> and Authorization: Bearer <credentials> (or Basic <credentials>) for the first of authentication.schemes the server knows.

Managing Webhooks

const one = await client.getPushNotificationConfig(task.id, config.pushNotificationConfig.id);
const all = await client.listPushNotificationConfigs(task.id);
await client.deletePushNotificationConfig(task.id, config.pushNotificationConfig.id!);

Every config method requires an existing task the caller may see (-32001 Task not found otherwise). Over 1.0, ListTaskPushNotificationConfigs pages by pageSize (1 to 100, default 50) and pageToken, with a nextPageToken while more remain, and listPushNotificationConfigs() walks the pages. To subscribe before the task starts, pass configuration.pushNotificationConfig with blocking: false.

Server Configuration

Configs live in an InMemoryPushNotificationStore unless you pass your own PushNotificationStore:

import { A2AServer, InMemoryPushNotificationStore } from '@cogitator-ai/a2a';

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  pushNotificationStore: new InMemoryPushNotificationStore(),
});

Webhook delivery is SSRF-hardened unless allowPrivateUrls: true: loopback, private, link-local, CGNAT, multicast and IPv4-mapped IPv6 targets are rejected, the check applies to the address the socket actually connects to, and redirects are not followed.

Agent Card Signing

Cards are signed as A2A 1.0 specifies (section 8.4): a JWS (RFC 7515, detached payload) whose protected header is { alg, typ: 'JOSE', kid, jku? }, over the JCS (RFC 8785) of the card's A2A 1.0 form without signatures and without the fields ProtoJSON leaves out (empty strings and lists, false defaults). That is exactly the payload the official SDK signs and verifies, so its verifyAgentCardSignature accepts a Cogitator card. Signing runs on node:crypto, with no extra dependency.

Server-Side

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  cardSigning: {
    alg: 'ES256', // 'RS256', 'PS256' or 'EdDSA'
    privateKey: process.env.CARD_SIGNING_KEY!, // PEM, a private JWK, or a KeyObject
    kid: 'cards-2026',
    publishJwks: true, // serves the public key at /.well-known/jwks.json
    jku: 'https://my-server.com/.well-known/jwks.json', // optional
  },
});
algKey
ES256ECDSA on P-256, signatures in IEEE P1363 form
RS256RSA, PKCS#1 v1.5
PS256RSA (or RSA-PSS), salt as long as the digest
EdDSAEd25519 or Ed448

A key that does not fit the algorithm is refused when the server is created. The A2A 1.0 card and the hybrid 0.3 card carry the same signature. It covers the 1.0 form, so the 0.3 fields of a signed card must follow from it: a 0.3 or hybrid card verifies only when its url (with preferredTransport and protocolVersion) and every additionalInterfaces entry are 0.3 interfaces of its supportedInterfaces, its security schemes and requirements come back from their 1.0 form unchanged (an OAuth scheme with several flows, or none, does not, since a 1.0 scheme holds one flow), and it claims no stateTransitionHistory. The signer refuses to sign a card that fails this, with the reason legacyCoverageProblem(card) gives, and a server that speaks only 1.0 serves the 0.3 form of its card unsigned. A client on 0.3 takes its endpoint from the signed 0.3 interface, never from url. Signatures are kept per payload, so an unchanged card keeps its signature, and its ETag, even with randomized ECDSA and RSA-PSS signatures.

Client-Side Verification

// trusted keys by kid, or a JWKS
const isValid = await client.verifyAgentCard({ keys: { 'cards-2026': publicKeyPem } });
await client.verifyAgentCard({ keys: await (await fetch(jwksUrl)).json() });

// your own key lookup
await client.verifyAgentCard({ resolveKey: async (kid, jku) => keyStore.get(kid) });

// the JWKS of the signature's jku, fetched only from the card's own origin by default
await client.verifyAgentCard({});
await client.verifyAgentCard({ trustJku: ['https://keys.example.com'] });

A jku on another origin than the card's is never fetched unless trustJku lists that origin. verifyAgentCardJws(card, options) checks a card (1.0, hybrid or 0.3) without a client, canonicalizeAgentCard(card) returns the signed payload.

Shared Secret (deprecated)

cardSigning: { secret } still signs every served card with HMAC HS256 over its own canonical JSON, and client.verifyAgentCard(secret) or verifyAgentCardSignature(card, secret) checks it. It is deprecated: anyone who can verify such a signature can also forge one.

import { signAgentCard, verifyAgentCardSignature } from '@cogitator-ai/a2a';

const signed = signAgentCard(card, { secret: 'my-secret' });
const valid = verifyAgentCardSignature(signed, 'my-secret');

Authenticated Extended Agent Card

GetExtendedAgentCard (A2A 0.3: agent/getAuthenticatedExtendedCard) returns a more detailed card to authenticated clients:

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  auth: { type: 'bearer', validate: async (token) => token === process.env.A2A_SECRET },
  extendedCardGenerator: (agentName) => ({
    ...a2aServer.getAgentCard(agentName),
    skills: [
      {
        id: 'deep_research',
        name: 'Deep research',
        description: 'Multi-source deep research',
        tags: ['research'],
      },
    ],
  }),
});

const client = new A2AClient('https://remote-agent.example.com', {
  headers: { Authorization: 'Bearer my-token' },
});
const extendedCard = await client.extendedAgentCard();

The public card declares it (capabilities.extendedAgentCard, 0.3: supportsAuthenticatedExtendedCard) only with extendedCardGenerator. Without it the 0.3 method answers -32007 Authenticated Extended Card not configured, and the 1.0 method -32004 Unsupported operation, as for any capability a card does not declare. Over 1.0 the generated card comes in its 1.0 form, with the agent's own interfaces unless it lists others in supportedInterfaces.

Extensions

Cards declare the extensions an agent supports in capabilities.extensions. Every Cogitator agent supports three, none of them required:

URIWhat it is
https://cogitator.app/a2a/extensions/tool-approvals/v1Tool approvals as tool-approval-request data parts
https://cogitator.app/a2a/extensions/interrupts/v1Questions tools ask, as interrupt-request data parts
https://cogitator.app/a2a/extensions/run-timeout/v1A shorter run: metadata[uri].timeoutMs (0.3: configuration.timeout)

Declare your own next to them:

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  extensions: [
    { uri: 'https://example.com/extensions/geo/v1', description: 'Location', required: true },
  ],
});

A client asks for extensions in the A2A-Extensions header (X-A2A-Extensions in 0.3), comma-separated, and the response names the ones the agent supports in the same header. A message that does not ask for a required extension is refused with -32008 Extension support required (HTTP 400 on REST). A2AClient takes extensions: [...] to ask for some on every request, and adds the run-timeout extension itself when a send sets timeout.

Framework Adapters

Every adapter serves the routes listed under Multiple Agents, the HTTP+JSON binding under restPath and the JWKS at /.well-known/jwks.json when the server publishes one, takes application/a2a+json bodies, streams only for message/stream and tasks/resubscribe (1.0: SendStreamingMessage and SubscribeToTask, an Accept: text/event-stream header alone does not switch message/send to SSE), answers JSON-RPC notifications with HTTP 204, a body that is not application/json with 415, and missing or rejected credentials with 401. While a stream is open it writes a : keep-alive comment every sseHeartbeatMs (an A2AServer option, 5 seconds by default, 0 turns it off), so a proxy (nginx closes after 60 s) or Bun (after 10 s) does not cut a run that waits on a slow tool. Structurally invalid JSON-RPC requests get -32600 Invalid Request, only unparseable JSON gets -32700 Parse error.

Errors that are neither A2A errors nor CogitatorErrors (in parsing, authentication, routing, streams or agent runs) are logged on the server and answered as -32603 Internal error, without their text. A CogitatorError is answered as -32603 Internal error: <message>. A task that fails that way gets the status message Internal error.

Express

import { a2aExpress } from '@cogitator-ai/a2a/express';
app.use(a2aExpress(a2aServer));

A body a parser upstream read (express.json()) is taken as it is. Otherwise the router parses application/json and application/a2a+json itself, up to 1 MiB (413 above it), also when an Express 4 parser left {} on a body it skipped.

Hono

import { a2aHono } from '@cogitator-ai/a2a/hono';
app.route('/', a2aHono(a2aServer));

Fastify

The plugin registers a content type parser for application/a2a+json and wildcard routes under restPath:

import { a2aFastify } from '@cogitator-ai/a2a/fastify';
fastify.register(a2aFastify(a2aServer));

Koa

The Koa middleware takes ctx.request.body when a body parser set it, and reads the raw body itself otherwise, up to 1 MiB (so an application/a2a+json body a parser skipped, or left as {}, works too, and a larger body gets 413):

import bodyParser from 'koa-bodyparser';
import { a2aKoa } from '@cogitator-ai/a2a/koa';

app.use(bodyParser());
app.use(a2aKoa(a2aServer));

Next.js

a2aNext returns route handlers. In a catch-all route they serve every A2A route by the request path, the REST binding and its DELETE included:

// app/[[...a2a]]/route.ts
import { a2aNext } from '@cogitator-ai/a2a/next';

export const { GET, POST, DELETE } = a2aNext(a2aServer);

Exported from fixed routes they keep working as before: GET answers with the Agent Card and POST with JSON-RPC, and in a dynamic [agent] route they serve that agent's own card and endpoint:

// app/.well-known/agent-card.json/route.ts -> GET
// app/a2a/route.ts -> POST (the route at basePath)
// app/a2a/[agent]/route.ts -> POST, app/a2a/[agent]/.well-known/agent-card.json/route.ts -> GET
export const { GET, POST } = a2aNext(a2aServer);

Task Store

Tasks are stored in memory by default. InMemoryTaskStore keeps up to maxSize tasks (default 10,000) and evicts the oldest finished task first:

import { A2AServer, InMemoryTaskStore } from '@cogitator-ai/a2a';

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  taskStore: new InMemoryTaskStore({ maxSize: 50_000 }),
});

For production, use RedisTaskStore or implement the TaskStore interface (create, get, update, list, delete). Your list must honour filter.visibleTo: when it is set, return only tasks owned by that user and tasks without an owner (null means a caller without a user), or tasks/list leaks other users' tasks. The helpers the built-in stores use are exported for a store of your own: isTaskVisibleTo(task, userId), taskTime(task), taskCreatedAt(task) and compareTasksNewestFirst(a, b).

Authentication

const a2aServer = new A2AServer({
  agents: { researcher },
  cogitator,
  auth: {
    type: 'bearer',
    validate: async (token) => token === process.env.A2A_SECRET,
  },
});

validate receives the credential and returns true, false or a caller. Every adapter extracts the credential (Authorization: Bearer ..., or the x-api-key header or headerName for type: 'apiKey') with a2aServer.getAuthToken(). A missing or rejected credential is answered with HTTP 401 (and WWW-Authenticate: Bearer for bearer auth) and the JSON-RPC error -32000 Unauthorized, over 1.0 with an ErrorInfo of reason UNAUTHENTICATED, and on REST with status: 'UNAUTHENTICATED'. The Agent Card itself stays public and declares the scheme in securitySchemes and security.

One caller per user

When several users or tenants share the server, return who the caller is instead of true:

auth: {
  type: 'bearer',
  validate: async (token) => {
    const session = await sessions.verify(token);
    return session ? { userId: session.userId } : false;
  },
},

Each task then belongs to the user who created it: another user's tasks/get, tasks/cancel, tasks/resubscribe, push notification calls and attempts to continue the task get Task not found, tasks/list returns only their own tasks (plus tasks without an owner), and a contextId holding someone else's tasks is refused. Runs carry the userId, so the agent's threads and memory are scoped to the user as well (multi-user). The owner is kept in the task's metadata on the server and never sent to clients. Returning true admits the caller without a user: such callers share the tasks that have no owner.

Clients include credentials via headers:

const client = new A2AClient('https://remote-agent.example.com', {
  headers: { Authorization: 'Bearer my-secret-token' },
});

A2A Protocol Methods

A2A 1.0 (A2A-Version: 1.0)A2A 0.3 (no version)Description
SendMessagemessage/sendSend a message (blocking or background)
SendStreamingMessagemessage/streamSend a message with SSE streaming
GetTasktasks/getRetrieve a task by id
ListTaskstasks/list (Cogitator extension)List tasks: cursor pages (1.0), offset (0.3)
CancelTasktasks/cancelCancel a running task
SubscribeToTasktasks/resubscribeReconnect to the stream of a task
CreateTaskPushNotificationConfigtasks/pushNotificationConfig/setRegister a webhook for a task
GetTaskPushNotificationConfigtasks/pushNotificationConfig/getGet a webhook config
ListTaskPushNotificationConfigstasks/pushNotificationConfig/listList the webhook configs of a task
DeleteTaskPushNotificationConfigtasks/pushNotificationConfig/deleteRemove a webhook config
GetExtendedAgentCardagent/getAuthenticatedExtendedCardFetch the authenticated extended Agent Card

Error Codes

CodeMeaningREST statusNotes
-32700Parse error400
-32600Invalid request4000.3: also a message for a task that can't take one
-32601Method not found404REST: a route that names no method
-32602Invalid params, also an unknown agent4001.0: with a google.rpc.BadRequest naming the fields
-32603Internal error500
-32001Task not found4041.0: also a push config that does not exist
-32002Task cannot be canceled400
-32003Push notification not supported400
-32004Unsupported operation4001.0: a message to, or a subscription of, an ended task
-32005Content type not supported400
-32006Invalid agent response500
-32007Authenticated Extended Card not configured400
-32008Extension support required400A required extension the request did not ask for
-32009Version not supported400ErrorInfo metadata lists the supported versions
-32000Cogitator: missing or rejected credentials401

Over A2A 1.0, error.data is a list of google.rpc details: an ErrorInfo (reason such as TASK_NOT_FOUND, domain: 'a2a-protocol.org', the details of the error as string metadata) and, for invalid params, a BadRequest with its fieldViolations. REST answers the same details in { error: { code, status, message, details } }. Over A2A 0.3 errors keep the form they always had.

Task States

StateDescription
submittedTask created, the run has not started yet
workingAgent is processing
input-requiredAgent needs more input, or approval of tool calls
auth-requiredAgent needs the client to authenticate
completedTask finished successfully
failedTask encountered an error
canceledTask was canceled
rejectedServer rejected the task

Migrating from earlier versions

With A2A 1.0 on by default, a request without A2A-Version and an A2AClient set to protocolVersion: '0.3' see the server as before. Three defaults changed: the card without a version is the hybrid card (0.3 fields plus supportedInterfaces), the REST binding is served under <basePath>/rest, and A2AClient speaks 1.0 to a server that offers it. protocolVersions: ['0.3'] on the server and protocolVersion: '0.3' on the client turn all three off, restPath: false the REST binding alone.

Earlier versions of this package spoke their own dialect, which A2A v0.3 clients and servers did not understand. The wire format now follows the specification:

  • Parts use kind ({ kind: 'text', text }), file parts nest the file ({ kind: 'file', file: { uri } }), data parts have no mimeType. Messages carry kind: 'message' and a messageId (A2AClient fills both in). Tasks carry kind: 'task', artifacts artifactId instead of id.
  • status.message is an agent message instead of a string, read its text with messageText(task.status.message). errorDetails is gone.
  • Stream events use kind, carry contextId, and the final status update has final: true. Every SSE event is a JSON-RPC response, there is no [DONE] marker, and tokens arrive as artifact-update chunks instead of token events.
  • The card is at /.well-known/agent-card.json with protocolVersion, preferredTransport, a required description and skill tags. version is the agent version, not the protocol version. Security schemes use in and name. capabilities.extendedAgentCard became supportsAuthenticatedExtendedCard, and signatures are JWS objects in signatures.
  • Methods: tasks/pushNotification/* became tasks/pushNotificationConfig/{set,get,list,delete} with spec params (url, token, authentication), webhooks receive the task, and agent/extendedCard became agent/getAuthenticatedExtendedCard. On the client: setPushNotificationConfig, getPushNotificationConfig, listPushNotificationConfigs, deletePushNotificationConfig.
  • A completed task can't be continued, send a new message in its contextId. agentNotFound is -32602, a refused continuation -32600, and -32007 is the extended card error of the specification.

On this page