Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

A2A for SAP agents: agent cards, tasks and SAP's Agent Gateway

How agents from different vendors call each other over A2A, how SAP's Agent Gateway lets outside agents call Joule agents, and how to build both sides.

Updated Nov 16, 2026Foundational 8 minDeep 40 min
Foundational layer · 8 min read

The 60-second version

Companies now run AI agents from several vendors at once: one in Microsoft Copilot, one on AWS, one in SAP's Joule. Each is good at its own systems. A sales assistant in Copilot can't see why an order is blocked in SAP. An SAP agent can't see the customer emails in Outlook.

A2A (Agent2Agent) is an open protocol that lets one agent hand a piece of work to another, even when different companies built them. It defines three things in plain terms:

  • An agent card: a public description of the agent: its name, what it can do (its skills), where to reach it and how to log in.
  • A task: one piece of delegated work, with a status such as working, needs input, completed or rejected.
  • Messages: what the two agents say to each other while the task runs.

A2A doesn't move data between databases and doesn't replace APIs. It is how agents ask each other for help.

As of November 2026, SAP supports A2A in two directions with different maturity. Outside agents calling SAP's agents goes through SAP's Agent Gateway; SAP announced it as generally available in October 2026 (SAP Architecture Center). Joule calling an agent you built works through a Joule scenario, and SAP's own page says some parts of it are not yet generally available (SAP Architecture Center).

Why it matters to the business

Take the fictional pump maker Calder Pumpworks, which this course follows. Its customer service team works in a CRM assistant. When a distributor asks "where is my order?", the clerk switches to SAP, finds that order 1000002 for Hallam Fluid Systems is on credit block, and emails the credit analyst. That is three systems and a few minutes for every question.

With A2A, the CRM assistant can ask an SAP-side agent directly: "why is order 1000002 stuck, and draft a credit release request". The SAP agent answers with the reason, asks the clerk for a business reason, and leaves a draft for the credit analyst. Nobody copies data between screens.

What leaders should weigh:

  • Value: fewer swivel-chair steps between front-office tools and SAP. The gain is real only where questions cross systems often.
  • Risk: an outside agent is now a door into SAP processes. The questions are who may knock, on whose behalf, and what they may ask for. SAP's design answers this with a registration, an access list and the user's own SAP authorizations (SAP Architecture Center).
  • Cost: each delegated task runs two agents, so two sets of model calls. For what SAP charges for custom Joule Studio agents, see pricing custom agents after the free runtime.
  • Lock-in: because A2A is open, an agent built today can be called by tomorrow's assistant, whichever vendor wins your front office.

How SAP does it

As of November 2026, SAP's Architecture Center describes two directions:

Direction What it means How it works Status on SAP's pages
Inbound An outside agent (Copilot Studio, AWS, Google) calls a Joule agent The Agent Gateway checks the caller's registration, token and access list, then routes the call GA announced 27 October 2026 (news); reference pages updated days earlier still say some components are not GA (inbound)
Outbound Joule calls an agent your team built You register the agent's A2A endpoint in a Joule scenario; Joule acts as the client Some components not yet GA (outbound)
Two-way through the gateway SAP agents delegating to third-party agents through the Agent Gateway Planned: outbound A2A and outbound MCP Not yet supported; on SAP's roadmap

Three points from SAP's design are worth repeating to any vendor:

  1. Discovery is not permission. Seeing an agent in the catalog doesn't allow calling it. The access list does.
  2. The SAP agent acts as the signed-in user. It gets no wider access than the person behind the request.
  3. Every call is checked, and calls are logged for audit.

SAP's pages also name the outside platforms. The inbound page lists Google Vertex AI, Microsoft Copilot Studio and AWS Bedrock AgentCore as callers (inbound). Separate pages describe the Copilot path (Microsoft Copilot) and an AWS path through AgentCore (Amazon Quick). Both of those pages, updated on 23 October 2026, still call the Agent Gateway not yet GA, so ask SAP which state applies to your tenant.

Which pattern fits: a decision guide

Situation Use Why
Front-office assistant needs SAP's own agent (sourcing, receivables) Inbound A2A through the Agent Gateway SAP's governed route, with user permissions and audit
Joule users need an agent your team built and hosts Outbound A2A: a Joule scenario pointing at your agent Joule stays the one place users ask
An agent only needs to read or update SAP data MCP tools or released APIs, not A2A A tool is simpler than a second agent; see the Model Context Protocol
Two agents inside one team's code Plain function calls in one framework A2A adds a network hop and a security boundary you don't need
A partner's agent wants to call your self-hosted agent Your own A2A endpoint behind your API gateway SAP's gateway covers SAP agents, not yours

The rule of thumb: use A2A when the other side has its own reasoning, owner and permissions. If it is just data, use a tool.

Questions to ask

  • Which direction do we need: outside agents calling SAP agents, or Joule calling ours? Their status differs.
  • Is inbound A2A generally available for our tenant and region today, and which A2A version does it accept?
  • Whose identity reaches SAP: the end user's, or a technical user? Who maps outside users to SAP users?
  • Which SAP agents may each outside client call, who approves that list, and how often is it reviewed?
  • What can the called agent change? Does it draft for a person, or post directly?
  • How are calls logged, and can we trace one request from the outside assistant to the SAP document it touched?
  • What does each delegated task cost on both sides, in model calls and SAP units?

Common misconceptions

  • "A2A gives the outside agent access to SAP data." It doesn't. The outside agent asks; the SAP agent works within the signed-in user's authorizations and returns a result.
  • "If an agent is in the catalog, anyone registered can call it." SAP separates discovery from permission: an access list decides who may call which agent.
  • "A2A replaces MCP." They do different jobs. MCP connects an agent to tools; A2A connects an agent to another agent.
  • "Inbound GA means everything A2A is GA." Only the inbound direction was announced as GA. Two-way communication through the gateway is still planned.
  • "Every A2A product speaks the same version." SAP's reference pages describe A2A 0.3.0, while the current specification is 1.0.0. Versions must be checked per product.

Key terms

All course terms, A to Z, in the glossary

  • A2A (Agent2Agent): an open protocol for one agent to delegate work to another, across vendors.
  • Agent card: a public description of an agent: name, skills, endpoint and how to authenticate.
  • Skill: one thing an agent card says the agent can do, such as "order status".
  • Task: one unit of delegated work with a status that moves from submitted to a final state.
  • Input required: a task status meaning the agent needs more information before it can finish.
  • Agent Gateway: SAP's governed entry point through which outside agents call SAP agents.
  • Access list (ACL): the list of SAP agents a registered outside client may call.
  • Inbound and outbound A2A: inbound is an outside agent calling SAP; outbound is SAP's Joule calling another agent.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1What does A2A standardize between two agents?

Answer: C. A2A defines agent cards for discovery, tasks for delegated work and messages for the exchange. It doesn't move data between databases or choose models; each agent keeps its own.

2Calder's CRM assistant should ask an SAP-delivered Joule agent for help. Which SAP route fits, as of November 2026?

Answer: D. Outside agents calling SAP agents is the inbound direction, and SAP routes it through the Agent Gateway, announced as GA in October 2026. Outbound is the opposite direction, Joule calling an agent you host.

3A partner's agent appears in SAP's discovery catalog. What does that tell you?

Answer: D. SAP separates discovery from permission. The access list, set during onboarding, decides which SAP agents a registered client may invoke, and it is checked on every call.

4Whose permissions limit what an SAP agent does when an outside assistant calls it?

Answer: A. SAP's design keeps the user's identity across the call, and the SAP agent works within that user's business authorizations. The outside agent gets no broader access than the person.

5A vendor says its assistant "supports A2A, so it will work with SAP". What should you ask first?

Answer: D. SAP's reference pages describe A2A 0.3.0, while the specification's current version is 1.0.0, and the gateway needs a token exchanged for the signed-in user. Version and identity decide whether the two sides can talk.

6When is A2A the wrong choice?

Answer: B. A2A is for delegating to another agent with its own reasoning and permissions. Reading data is a job for a tool or a released API, which is simpler and cheaper.
Deep layer · 40 min read

Mental model

A2A is HTTP for delegation. One agent (the client) reads another agent's card, sends it a message, and gets back a task it can follow until the task ends. Everything else is detail around three questions:

  1. Can I find you? The agent card, served at a well-known URL.
  2. May I ask? Ordinary web security: a bearer token, checked on every request. A2A deliberately leaves identity to the transport (A2A specification).
  3. Where is my answer? The task's state, which moves to completed, rejected, failed or canceled, or pauses at input required.

Keep one contrast in mind. MCP lets an agent call a tool: the caller decides, the tool executes. A2A lets an agent hand work to a peer that decides for itself, may ask questions back, and has its own permissions. That is why an A2A call needs an identity story and a task lifecycle, and a tool call usually doesn't.

How it works

The objects

The A2A specification lists 1.0.0 as its latest released version (earlier: 0.3.0, 0.2.6, 0.1.0). Its main objects:

Object What it holds Calder example
Agent card name, description, version, supportedInterfaces (each with url, protocolBinding, protocolVersion), capabilities, securitySchemes, skills The order exceptions agent, skills order_status and credit_release_draft
Message messageId, role (ROLE_USER or ROLE_AGENT), parts, optional taskId and contextId "draft credit release 1000002"
Part One piece of content: text, data (structured JSON with a mediaType), url or raw {"data": {"skill": "order_status", "salesOrder": "1000002"}}
Task id, contextId, status (a state and an optional message), artifacts, history task-0003, state TASK_STATE_INPUT_REQUIRED
Artifact An output of the task, made of parts Draft CRR-1000002

A task's state is one of TASK_STATE_SUBMITTED, WORKING, INPUT_REQUIRED, AUTH_REQUIRED, COMPLETED, FAILED, CANCELED or REJECTED (all with the TASK_STATE_ prefix). The last four are terminal: a finished task takes no more messages.

The operations

A2A 1.0 offers three protocol bindings: JSON-RPC, gRPC and HTTP+JSON. In JSON-RPC, the methods are named SendMessage, SendStreamingMessage, GetTask, ListTasks, CancelTask and SubscribeToTask, plus methods for push notification settings and GetExtendedAgentCard. The HTTP+JSON binding maps them to endpoints such as POST /message:send and GET /tasks/{id} (A2A specification).

A2A errors have fixed JSON-RPC codes: -32001 task not found, -32002 task not cancelable, -32004 unsupported operation, -32009 version not supported, among others.

sequenceDiagram
  participant C as Client agent (CRM assistant)
  participant S as Server agent (order exceptions)
  C->>S: GET /.well-known/agent-card.json
  S-->>C: card: skills, interfaces, auth
  C->>S: SendMessage "draft credit release 1000002" + bearer token
  S-->>C: task-0003 INPUT_REQUIRED "give a reason"
  C->>S: SendMessage on task-0003 "Hallam paid invoice 90000003"
  S-->>C: task-0003 COMPLETED, artifact CRR-1000002
  C->>S: GetTask task-0003 (later, any time)
  S-->>C: same task, full history

Versions: the detail that breaks integrations

Version 1.0 changed the wire format. Clients must send an A2A-Version header, and a request without one is treated as 0.3. The 0.3 JSON-RPC method names were different (message/send, tasks/get); parts carried a kind field; and states were lower case (input-required). A server that speaks only 1.0 answers a 0.3 client with VersionNotSupportedError (A2A specification). An agent card can list several interfaces, so one server can offer both versions.

This matters for SAP today. SAP's inbound and outbound reference pages both describe A2A 0.3.0, and the outbound page says Joule sends message/send (outbound). AWS's AgentCore contract also shows a 0.3.0 card (AWS). The Python SDK, a2a-sdk 1.3.0, implements 1.0 with a 0.3 compatibility mode (PyPI). Plan for both versions until SAP's pages say otherwise.

Identity sits outside the messages

A2A messages carry no user. The specification leaves authentication to established web security: the card declares schemes (API key, HTTP auth, OAuth 2.0, OpenID Connect, mutual TLS), and the server must authenticate every request. Authorization after that is the server's own business (A2A specification). In practice, the user travels in the bearer token, and SAP's whole inbound design is about minting the right token (see The SAP way).

Build it yourself: serve a Calder agent over A2A and call it from a second agent

You will run Calder's order exceptions agent as an A2A server on your laptop, then call it from a second agent, the CRM assistant. You will see discovery, a task that pauses for input, a refused caller, a caller limited to its own customer, and the version difference that SAP integrations hit today.

Before you start: complete Set up your computer for this course and Set up for Unit 9, which create the orchestrate-course folder, the .venv virtual environment, the .env file and the unit09 subfolder. This walkthrough doesn't repeat those steps.

flowchart LR
  CRM[CRM assistant<br/>a2a_lab.py call] -- 1 read card --> CARD[/.well-known/agent-card.json/]
  CRM -- 2 SendMessage + token --> SRV[Order exceptions agent<br/>a2a_lab.py serve :8776]
  SRV -- checks --> ACL[Course access list<br/>tokens, skills, customers]
  SRV -- reads --> ORD[Calder open orders<br/>1000002-1000007]
  SRV -- 3 task, artifacts --> CRM

What you need

  • The course folder, virtual environment and .env file from the setup topics.
  • Python 3.11 or newer. The lab uses built-in modules only; it reads .env with python-dotenv from the Unit 9 setup.
  • Two terminal windows: one for the server, one for the client.
  • Cost: free. Time: about 40 minutes.

Step 1: Open your course folder and turn on the virtual environment

  1. Open a terminal.
  2. Go to the course folder and activate the environment.

Windows (PowerShell):

cd $HOME\orchestrate-course
.venv\Scripts\Activate.ps1

macOS or Linux:

cd ~/orchestrate-course
source .venv/bin/activate

You should see (.venv) at the start of the prompt.

Step 2: Save the script

In VS Code, right-click the unit09 folder, choose New File, name it a2a_lab.py, paste the code below and save.

"""A2A lab: serve a Calder agent over A2A and call it from a second agent.

Course: Orchestrate, Unit 9, "A2A for SAP agents".
Built-in modules only. No account, no model, no randomness.

The order-exceptions agent below is a course stand-in. It is not SAP code and
not a full A2A implementation: it speaks a teaching subset of the A2A JSON-RPC
binding (SendMessage, GetTask, CancelTask in version 1.0, and message/send,
tasks/get, tasks/cancel in version 0.3). Tokens, client names, skills and the
access list are course values. Calder Pumpworks and every number are fictional.

Commands:
  python unit09/a2a_lab.py serve                      serve the agent on 127.0.0.1:8776
  python unit09/a2a_lab.py card                       print the agent card a client would read
  python unit09/a2a_lab.py call --order 1000002       a second agent reads the card and asks for the order status
  python unit09/a2a_lab.py call --order 1000002 --skill credit_release_draft --reason "..."
  python unit09/a2a_lab.py get --task task-0003       read a task again (GetTask)
  python unit09/a2a_lab.py cancel --task task-0002    cancel an open task (CancelTask)
  python unit09/a2a_lab.py selftest                   start a private server and run the course checks
"""

import argparse
import json
import os
import re
import sys
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

try:                                   # read tokens from the course .env file when python-dotenv is installed
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

HOST, PORT = "127.0.0.1", 8776
CARD_PATH = "/.well-known/agent-card.json"
OLD_CARD_PATH = "/.well-known/agent.json"   # the older name some tools still look for
RPC_PATH = "/a2a"

# Open orders from the order-to-cash topic (fictional). Amounts in USD; 1000005 has no price yet.
ORDERS = {
    "1000002": {"customer": "10000002", "name": "Hallam Fluid Systems", "amount": "24288.00",
                "problem": "credit block", "owner": "Credit analyst"},
    "1000003": {"customer": "10000001", "name": "Brennock Water Utility", "amount": "12300.00",
                "problem": "billing data incomplete", "owner": "Sales order team"},
    "1000004": {"customer": "10000001", "name": "Brennock Water Utility", "amount": "24600.00",
                "problem": "partly confirmed", "owner": "Order fulfillment"},
    "1000005": {"customer": "10000002", "name": "Hallam Fluid Systems", "amount": "",
                "problem": "price missing", "owner": "Pricing team"},
    "1000006": {"customer": "10000001", "name": "Brennock Water Utility", "amount": "4200.00",
                "problem": "billing block", "owner": "Billing clerk"},
    "1000007": {"customer": "10000001", "name": "Brennock Water Utility", "amount": "8400.00",
                "problem": "delivery block", "owner": "Customer service"},
}

# Course access list: who may call, on whose behalf, and which skills.
# In SAP's Agent Gateway the access list lives in the gateway, not in the agent.
CLIENTS = {
    "calder-lab-token-crm": {"client": "crm-assistant", "acts_for": "user 00100265",
                             "customers": None, "skills": {"order_status", "credit_release_draft"}},
    "calder-lab-token-portal": {"client": "hallam-portal-agent", "acts_for": "customer 10000002",
                                "customers": {"10000002"}, "skills": {"order_status"}},
}

SKILLS = [
    {"id": "order_status", "name": "Order status",
     "description": "Explain why one open Calder sales order is stuck and who owns the next step.",
     "tags": ["sales-order", "read-only"], "examples": ["status 1000002"]},
    {"id": "credit_release_draft", "name": "Credit release request draft",
     "description": "Draft a credit release request for an order on credit block. Asks for a reason first. "
                    "Drafts only: a credit analyst decides.",
     "tags": ["sales-order", "draft", "needs-input"], "examples": ["draft credit release 1000002"]},
]

STATES_03 = {"TASK_STATE_SUBMITTED": "submitted", "TASK_STATE_WORKING": "working",
             "TASK_STATE_INPUT_REQUIRED": "input-required", "TASK_STATE_COMPLETED": "completed",
             "TASK_STATE_CANCELED": "canceled", "TASK_STATE_FAILED": "failed",
             "TASK_STATE_REJECTED": "rejected"}
TERMINAL = {"TASK_STATE_COMPLETED", "TASK_STATE_CANCELED", "TASK_STATE_FAILED", "TASK_STATE_REJECTED"}
METHODS = {"1.0": {"send": "SendMessage", "get": "GetTask", "cancel": "CancelTask"},
           "0.3": {"send": "message/send", "get": "tasks/get", "cancel": "tasks/cancel"}}
ERRORS = {"parse": (-32700, "Invalid JSON"), "method": (-32601, "Method not found"),
          "params": (-32602, "Invalid params"), "notfound": (-32001, "Task not found"),
          "notcancelable": (-32002, "Task cannot be canceled"),
          "unsupported": (-32004, "Unsupported operation"), "version": (-32009, "Version not supported")}


def agent_card(base_url):
    """The agent card: public, so a client can discover the agent before it has a token."""
    return {
        "name": "Calder order exceptions agent",
        "description": "Explains blocked Calder sales orders and drafts credit release requests. "
                       "Course stand-in, fictional data.",
        "version": "2026.11",
        "provider": {"organization": "Calder Pumpworks (fictional)", "url": "https://calder-pumpworks.example"},
        "supportedInterfaces": [
            {"url": base_url + RPC_PATH, "protocolBinding": "JSONRPC", "protocolVersion": "1.0"},
            {"url": base_url + RPC_PATH, "protocolBinding": "JSONRPC", "protocolVersion": "0.3"},
        ],
        "capabilities": {"streaming": False, "pushNotifications": False},
        "securitySchemes": {"bearer": {"httpAuthSecurityScheme": {"scheme": "Bearer"}}},
        "securityRequirements": [{"schemes": {"bearer": {"list": []}}}],
        "defaultInputModes": ["text/plain", "application/json"],
        "defaultOutputModes": ["text/plain", "application/json"],
        "skills": SKILLS,
    }


class Store:
    """Tasks in memory, numbered so every run gives the same IDs."""

    def __init__(self):
        self.tasks, self.lock, self.n_task, self.n_ctx, self.n_art = {}, threading.Lock(), 0, 0, 0

    def new_task(self, context_id):
        with self.lock:
            self.n_task += 1
            if not context_id:
                self.n_ctx += 1
                context_id = f"ctx-{self.n_ctx:04d}"
            task = {"id": f"task-{self.n_task:04d}", "contextId": context_id,
                    "status": {"state": "TASK_STATE_SUBMITTED"}, "artifacts": [], "history": [],
                    "metadata": {}}
            self.tasks[task["id"]] = task
            return task

    def artifact_id(self):
        with self.lock:
            self.n_art += 1
            return f"art-{self.n_art:04d}"


def read_request(message):
    """Pull the skill and order out of a message: a data part wins, else the text."""
    skill, order, text = None, None, ""
    for part in message.get("parts", []):
        if isinstance(part.get("data"), dict):
            skill = part["data"].get("skill", skill)
            order = part["data"].get("salesOrder", order)
        if "text" in part:
            text += part["text"] + " "
    if not order:
        found = re.search(r"\b(\d{7})\b", text)
        order = found.group(1) if found else None
    if not skill:
        skill = "credit_release_draft" if "release" in text.lower() else "order_status"
    return skill, order, text.strip()


def agent_message(text, task):
    return {"messageId": f"{task['id']}-m{len(task['history']) + 1}", "role": "ROLE_AGENT",
            "contextId": task["contextId"], "taskId": task["id"], "parts": [{"text": text}]}


def user_message(message, task):
    """Keep the caller's message in the task history, in the 1.0 shape."""
    parts = [{k: v for k, v in part.items() if k != "kind"} for part in message.get("parts", [])]
    return {"messageId": message.get("messageId", f"{task['id']}-u"), "role": "ROLE_USER",
            "contextId": task["contextId"], "taskId": task["id"], "parts": parts}


def set_state(task, state, text):
    task["status"] = {"state": state, "message": agent_message(text, task)}
    task["history"].append(task["status"]["message"])


def run_skill(store, task, skill, order, text, caller):
    """The agent's work. It stays inside the caller's permissions."""
    task["metadata"].update({"skill": skill, "salesOrder": order, "client": caller["client"]})
    set_state(task, "TASK_STATE_WORKING", "Reading the order.")
    row = ORDERS.get(order or "")
    if row is None:
        return set_state(task, "TASK_STATE_REJECTED", f"No open order {order} in the course data.")
    if caller["customers"] is not None and row["customer"] not in caller["customers"]:
        return set_state(task, "TASK_STATE_REJECTED",
                         f"Order {order} belongs to another customer; {caller['acts_for']} may not read it.")
    if skill == "order_status":
        task["artifacts"].append({
            "artifactId": store.artifact_id(), "name": f"Status of order {order}",
            "parts": [{"text": f"Order {order} for {row['name']} is stuck on: {row['problem']}. "
                               f"Next step owner: {row['owner']}."},
                      {"data": {"salesOrder": order, "problem": row["problem"], "owner": row["owner"]},
                       "mediaType": "application/json"}]})
        return set_state(task, "TASK_STATE_COMPLETED", "Done.")
    if skill == "credit_release_draft":
        if row["problem"] != "credit block":
            return set_state(task, "TASK_STATE_REJECTED",
                             f"Order {order} is not on credit block ({row['problem']}); nothing to draft.")
        return set_state(task, "TASK_STATE_INPUT_REQUIRED",
                         f"Order {order}: {row['name']}, {row['amount']} USD. "
                         "Reply on this task with the business reason for the release.")
    return set_state(task, "TASK_STATE_REJECTED", f"Unknown skill {skill}.")


def continue_task(store, task, message, text):
    """Second turn of credit_release_draft: the reason arrives, the draft is written."""
    task["history"].append(user_message(message, task))
    order = task["metadata"]["salesOrder"]
    if len(text) < 10:
        return set_state(task, "TASK_STATE_INPUT_REQUIRED", "Please give a reason of at least 10 characters.")
    task["artifacts"].append({
        "artifactId": store.artifact_id(), "name": f"Credit release request CRR-{order}",
        "parts": [{"text": f"Draft CRR-{order} for order {order}. Reason: {text.rstrip('.')}. "
                           "Status: waiting for the credit analyst. Nothing was changed in the order."},
                  {"data": {"draft": f"CRR-{order}", "salesOrder": order, "reason": text,
                            "status": "awaiting credit analyst"}, "mediaType": "application/json"}]})
    set_state(task, "TASK_STATE_COMPLETED", f"Draft CRR-{order} written for review.")


def to_v03(obj):
    """Rewrite a 1.0-shaped object into the 0.3 shape (kind fields, lower-case states)."""
    if isinstance(obj, list):
        return [to_v03(x) for x in obj]
    if not isinstance(obj, dict):
        return obj
    out = {k: to_v03(v) for k, v in obj.items()}
    if "status" in out and "contextId" in out and "id" in out:
        out["kind"] = "task"
        out["status"]["state"] = STATES_03.get(out["status"]["state"], "unknown")
    if "role" in out:
        out["kind"] = "message"
        out["role"] = "agent" if out["role"] == "ROLE_AGENT" else "user"
    if "text" in out and "role" not in out and "kind" not in out:
        out["kind"] = "text"
    if "data" in out and isinstance(out["data"], dict) and "role" not in out:
        out["kind"] = "data"
        out.pop("mediaType", None)
    return out


def handle_rpc(store, version, caller, req):
    """Dispatch one JSON-RPC request. Returns (result, error_key, detail)."""
    names = METHODS[version]
    method, params = req.get("method"), req.get("params") or {}
    if method == names["send"]:
        message = params.get("message")
        if not isinstance(message, dict) or not message.get("parts"):
            return None, "params", "params.message with parts is required"
        skill, order, text = read_request(message)
        task_id = message.get("taskId")
        if task_id:                                   # a reply on an existing task
            task = store.tasks.get(task_id)
            if task is None:
                return None, "notfound", task_id
            if task["status"]["state"] in TERMINAL:
                return None, "unsupported", f"task {task_id} is already {task['status']['state']}"
            continue_task(store, task, message, text)
        else:
            if skill not in caller["skills"]:
                return {"_http": 403, "error": f"{caller['client']} may not use skill {skill}"}, None, None
            task = store.new_task(message.get("contextId"))
            task["history"].append(user_message(message, task))
            run_skill(store, task, skill, order, text, caller)
        return {"task": task} if version == "1.0" else task, None, None
    if method in (names["get"], names["cancel"]):
        task = store.tasks.get(params.get("id", ""))
        if task is None or task["metadata"].get("client") != caller["client"]:
            return None, "notfound", params.get("id", "")    # never reveal other clients' tasks
        if method == names["cancel"]:
            if task["status"]["state"] in TERMINAL:
                return None, "notcancelable", task["id"]
            set_state(task, "TASK_STATE_CANCELED", "Canceled by the caller.")
        return task, None, None
    return None, "method", f"{method} (A2A version {version})"


def make_handler(store, base_url):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            pass

        def send_json(self, status, body, extra=None):
            data = json.dumps(body, indent=2).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            for k, v in (extra or {}).items():
                self.send_header(k, v)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            if self.path in (CARD_PATH, OLD_CARD_PATH):
                return self.send_json(200, agent_card(base_url))
            self.send_json(404, {"error": "not found"})

        def do_POST(self):
            if self.path != RPC_PATH:
                return self.send_json(404, {"error": "not found"})
            auth = self.headers.get("Authorization", "")
            caller = CLIENTS.get(auth[7:]) if auth.startswith("Bearer ") else None
            if caller is None:   # authentication is HTTP's job, before any A2A logic runs
                return self.send_json(401, {"error": "missing or unknown bearer token"},
                                      {"WWW-Authenticate": "Bearer"})
            try:
                req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
            except json.JSONDecodeError:
                return self.send_json(200, rpc_error(None, "parse", ""))
            version = self.headers.get("A2A-Version", "").strip() or "0.3"   # no header means 0.3
            if version not in METHODS:
                return self.send_json(200, rpc_error(req.get("id"), "version", f"{version}; supported 1.0, 0.3"))
            result, err, detail = handle_rpc(store, version, caller, req)
            if err:
                return self.send_json(200, rpc_error(req.get("id"), err, detail))
            if isinstance(result, dict) and "_http" in result:
                return self.send_json(result["_http"], {"error": result["error"]})
            if version == "0.3":
                result = to_v03(json.loads(json.dumps(result)))
            self.send_json(200, {"jsonrpc": "2.0", "id": req.get("id"), "result": result})

    return Handler


def rpc_error(req_id, key, detail):
    code, msg = ERRORS[key]
    return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": f"{msg}: {detail}".rstrip(": ")}}


def start_server(port):
    base = f"http://{HOST}:{port}"
    server = ThreadingHTTPServer((HOST, port), make_handler(Store(), base))
    return server, base


# ---------------- the second agent: a client that discovers, then delegates ----------------

def http_json(url, body=None, headers=None):
    req = urllib.request.Request(url, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status, json.loads(resp.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"{}")


class Client:
    def __init__(self, base, token, version):
        self.base, self.token, self.version, self.n = base, token, version, 0
        self.endpoint = None

    def discover(self):
        status, card = http_json(self.base + CARD_PATH)
        if status != 200:
            raise SystemExit(f"No agent card at {self.base + CARD_PATH} (HTTP {status}).")
        for iface in card.get("supportedInterfaces", []):     # first match in the card's order wins
            if iface["protocolBinding"] == "JSONRPC" and iface["protocolVersion"] == self.version:
                self.endpoint = iface["url"]
                break
        if not self.endpoint:
            raise SystemExit(f"The card offers no JSON-RPC interface for A2A {self.version}.")
        return card

    def rpc(self, kind, params):
        self.n += 1
        headers = {"Authorization": f"Bearer {self.token}"}
        if self.version != "0.3":
            headers["A2A-Version"] = self.version
        body = {"jsonrpc": "2.0", "id": self.n, "method": METHODS.get(self.version, METHODS["1.0"])[kind],
                "params": params}
        return http_json(self.endpoint, body, headers)

    def message(self, text, data=None, task_id=None, context_id=None):
        self.n += 1
        parts = [{"text": text}]
        if data:
            parts.append({"data": data, "mediaType": "application/json"})
        msg = {"messageId": f"msg-{self.n:04d}", "role": "ROLE_USER", "parts": parts}
        if self.version == "0.3":
            msg = to_v03(msg)
            msg["role"] = "user"
        if task_id:
            msg["taskId"], msg["contextId"] = task_id, context_id
        return msg


def task_of(result):
    return result.get("task", result) if isinstance(result, dict) else {}


def show_task(task):
    state = task["status"]["state"]
    print(f"Task {task['id']} (context {task['contextId']}): {state}")
    note = task["status"].get("message", {}).get("parts", [{}])[0].get("text")
    if note:
        print(f"  agent says: {note}")
    for art in task.get("artifacts", []):
        print(f"  artifact {art['artifactId']} \"{art['name']}\"")
        for part in art["parts"]:
            print("    " + (part["text"] if "text" in part else "data " + json.dumps(part["data"])))


def report(status, body):
    if status != 200:
        print(f"HTTP {status}: {body.get('error', body)}")
        return None
    if "error" in body:
        print(f"A2A error {body['error']['code']}: {body['error']['message']}")
        return None
    return task_of(body["result"])


def cmd_call(args):
    token = os.environ.get(args.token_env, "")
    if not token:
        raise SystemExit(f"Set {args.token_env} in your .env file first (see Step 4).")
    client = Client(args.url, token, args.version)
    card = client.discover()
    skill_ids = [s["id"] for s in card["skills"]]
    print(f"Agent card: {card['name']} {card['version']}; skills: {', '.join(skill_ids)}")
    print(f"Chosen interface: JSONRPC {args.version} at {client.endpoint}")
    if args.skill not in skill_ids:
        raise SystemExit(f"The card lists no skill {args.skill}; not sending anything.")
    msg = client.message(f"{args.skill} {args.order}", {"skill": args.skill, "salesOrder": args.order})
    task = report(*client.rpc("send", {"message": msg}))
    if not task:
        return
    show_task(task)
    state = task["status"]["state"]
    if state in ("TASK_STATE_INPUT_REQUIRED", "input-required") and args.reason:
        print(f"Replying on {task['id']} with the reason.")
        msg = client.message(args.reason, task_id=task["id"], context_id=task["contextId"])
        task = report(*client.rpc("send", {"message": msg}))
        if task:
            show_task(task)


def cmd_get(args):
    token = os.environ.get(args.token_env, "")
    client = Client(args.url, token, args.version)
    client.discover()
    task = report(*client.rpc(args.cmd, {"id": args.task}))
    if task:
        show_task(task)


def cmd_selftest(_args):
    server, base = start_server(0)
    base = f"http://{HOST}:{server.server_address[1]}"
    server.RequestHandlerClass = make_handler(Store(), base)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    crm, portal = "calder-lab-token-crm", "calder-lab-token-portal"
    results = []

    def check(name, ok):
        results.append(ok)
        print(f"{'PASS' if ok else 'FAIL'}  {name}")

    def send(token, version, skill, order, task_id=None, ctx=None, text=None):
        c = Client(base, token, version)
        c.discover()
        msg = c.message(text or f"{skill} {order}", None if task_id else {"skill": skill, "salesOrder": order},
                        task_id, ctx)
        return c.rpc("send", {"message": msg})

    status, card = http_json(base + CARD_PATH)
    check("card is public and lists 2 skills", status == 200 and len(card["skills"]) == 2)
    s, b = send("wrong-token", "1.0", "order_status", "1000002")
    check("unknown token is refused with HTTP 401", s == 401)
    s, b = send(crm, "1.0", "order_status", "1000002")
    t = task_of(b.get("result", {}))
    check("1.0 SendMessage reads 1000002 -> TASK_STATE_COMPLETED", t.get("status", {}).get("state") == "TASK_STATE_COMPLETED")
    s, b = send(crm, "0.3", "order_status", "1000002")
    t = b.get("result", {})
    check("0.3 message/send answers in the 0.3 shape", t.get("kind") == "task" and t["status"]["state"] == "completed")
    s, b = send(crm, "1.0", "credit_release_draft", "1000002")
    t = task_of(b["result"])
    check("credit release asks for input first", t["status"]["state"] == "TASK_STATE_INPUT_REQUIRED")
    s, b = send(crm, "1.0", "credit_release_draft", "1000002", t["id"], t["contextId"],
                "Hallam paid invoice 90000003 today; balance back under limit.")
    t2 = task_of(b["result"])
    check("reply on the same task completes the draft CRR-1000002",
          t2["status"]["state"] == "TASK_STATE_COMPLETED" and "CRR-1000002" in json.dumps(t2["artifacts"]))
    s, b = send(crm, "1.0", "credit_release_draft", "1000002", t["id"], t["contextId"], "once more please, again")
    check("a message to a finished task is error -32004", b.get("error", {}).get("code") == -32004)
    s, b = send(portal, "1.0", "credit_release_draft", "1000002")
    check("portal client may not use credit_release_draft (HTTP 403)", s == 403)
    s, b = send(portal, "1.0", "order_status", "1000003")
    check("portal client cannot read Brennock's order (REJECTED)",
          task_of(b["result"])["status"]["state"] == "TASK_STATE_REJECTED")
    c = Client(base, portal, "1.0")
    c.discover()
    s, b = c.rpc("get", {"id": t["id"]})
    check("another client's task looks like 'not found' (-32001)", b.get("error", {}).get("code") == -32001)
    c = Client(base, crm, "2.0")
    c.endpoint = base + RPC_PATH
    s, b = c.rpc("send", {"message": {"parts": [{"text": "status 1000002"}]}})
    check("A2A-Version 2.0 is refused with -32009", b.get("error", {}).get("code") == -32009)
    server.shutdown()
    print(f"{sum(results)} of {len(results)} checks passed")
    sys.exit(0 if all(results) else 1)


def main():
    p = argparse.ArgumentParser(description="A2A lab for the Calder order exceptions agent")
    sub = p.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("serve")
    s.add_argument("--port", type=int, default=PORT)
    sub.add_parser("card")
    for name in ("call", "get", "cancel"):
        c = sub.add_parser(name)
        c.add_argument("--url", default=f"http://{HOST}:{PORT}")
        c.add_argument("--version", default="1.0", help="A2A version to speak: 1.0 or 0.3")
        c.add_argument("--token-env", default="CALDER_A2A_TOKEN")
        if name == "call":
            c.add_argument("--order", required=True)
            c.add_argument("--skill", default="order_status")
            c.add_argument("--reason", default="")
        else:
            c.add_argument("--task", required=True)
    sub.add_parser("selftest")
    args = p.parse_args()
    if args.cmd == "serve":
        server, base = start_server(args.port)
        print(f"Calder order exceptions agent on {base}")
        print(f"Agent card: {base}{CARD_PATH}  (Ctrl+C to stop)")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("Stopped.")
    elif args.cmd == "card":
        print(json.dumps(agent_card(f"http://{HOST}:{PORT}"), indent=2))
    elif args.cmd == "call":
        cmd_call(args)
    elif args.cmd in ("get", "cancel"):
        cmd_get(args)
    else:
        cmd_selftest(args)


if __name__ == "__main__":
    main()

Step 3: Run the self-test

The self-test starts a private copy of the server, runs eleven checks and stops it again.

python unit09/a2a_lab.py selftest

You should see:

PASS  card is public and lists 2 skills
PASS  unknown token is refused with HTTP 401
PASS  1.0 SendMessage reads 1000002 -> TASK_STATE_COMPLETED
PASS  0.3 message/send answers in the 0.3 shape
PASS  credit release asks for input first
PASS  reply on the same task completes the draft CRR-1000002
PASS  a message to a finished task is error -32004
PASS  portal client may not use credit_release_draft (HTTP 403)
PASS  portal client cannot read Brennock's order (REJECTED)
PASS  another client's task looks like 'not found' (-32001)
PASS  A2A-Version 2.0 is refused with -32009
11 of 11 checks passed

Any FAIL line means the file was not pasted completely; paste it again.

Step 4: Put the two course tokens in your .env file

The client reads its token from the environment, never from the code. Open .env in VS Code and add these two lines at the end:

CALDER_A2A_TOKEN=calder-lab-token-crm
CALDER_PORTAL_TOKEN=calder-lab-token-portal

Save the file. The first is the CRM assistant, acting for customer service clerk 00100265. The second is Hallam's distributor portal agent, which may only read Hallam's orders.

Step 5: Start the agent and read its card

  1. In the first terminal, start the server:
python unit09/a2a_lab.py serve
Calder order exceptions agent on http://127.0.0.1:8776
Agent card: http://127.0.0.1:8776/.well-known/agent-card.json  (Ctrl+C to stop)
  1. Leave it running. Open a browser at http://127.0.0.1:8776/.well-known/agent-card.json. You see the card as JSON, with no login: cards are public so clients can discover the agent. Look at supportedInterfaces: the same endpoint is offered for A2A 1.0 and 0.3.
  2. Open a second terminal and repeat Step 1 in it (folder and virtual environment). Use this terminal for every command below.

Step 6: Ask for an order's status

python unit09/a2a_lab.py call --order 1000002
Agent card: Calder order exceptions agent 2026.11; skills: order_status, credit_release_draft
Chosen interface: JSONRPC 1.0 at http://127.0.0.1:8776/a2a
Task task-0001 (context ctx-0001): TASK_STATE_COMPLETED
  agent says: Done.
  artifact art-0001 "Status of order 1000002"
    Order 1000002 for Hallam Fluid Systems is stuck on: credit block. Next step owner: Credit analyst.
    data {"salesOrder": "1000002", "problem": "credit block", "owner": "Credit analyst"}

The client read the card, picked the first interface it speaks, checked that the skill exists, and only then sent a message. The answer is an artifact with two parts: text for a person and data for a program.

Step 7: Start a task that needs input, then cancel it

  1. Ask for a credit release draft without giving a reason:
python unit09/a2a_lab.py call --order 1000002 --skill credit_release_draft
Task task-0002 (context ctx-0002): TASK_STATE_INPUT_REQUIRED
  agent says: Order 1000002: Hallam Fluid Systems, 24288.00 USD. Reply on this task with the business reason for the release.

(The first two lines, about the card and the interface, repeat in every call; they are left out from here on unless they matter.) The task is not finished: it waits for the caller.

  1. Cancel it, then try to cancel it again:
python unit09/a2a_lab.py cancel --task task-0002
python unit09/a2a_lab.py cancel --task task-0002
Task task-0002 (context ctx-0002): TASK_STATE_CANCELED
  agent says: Canceled by the caller.
A2A error -32002: Task cannot be canceled: task-0002

A canceled task is terminal, so the second cancel is refused with the specification's error code.

Step 8: Finish a task over two turns

Give the reason this time. The client sends it as a second message on the same task.

Windows (PowerShell) and macOS/Linux use the same command:

python unit09/a2a_lab.py call --order 1000002 --skill credit_release_draft --reason "Hallam paid invoice 90000003 today; balance back under limit."
Task task-0003 (context ctx-0003): TASK_STATE_INPUT_REQUIRED
  agent says: Order 1000002: Hallam Fluid Systems, 24288.00 USD. Reply on this task with the business reason for the release.
Replying on task-0003 with the reason.
Task task-0003 (context ctx-0003): TASK_STATE_COMPLETED
  agent says: Draft CRR-1000002 written for review.
  artifact art-0002 "Credit release request CRR-1000002"
    Draft CRR-1000002 for order 1000002. Reason: Hallam paid invoice 90000003 today; balance back under limit. Status: waiting for the credit analyst. Nothing was changed in the order.
    data {"draft": "CRR-1000002", "salesOrder": "1000002", "reason": "Hallam paid invoice 90000003 today; balance back under limit.", "status": "awaiting credit analyst"}

Then read the task again, as a client would after a restart:

python unit09/a2a_lab.py get --task task-0003

You see the same completed task. Note what the agent did not do: it changed nothing in the order. The credit analyst still decides, as in human approval in AI workflows.

Step 9: Call as a different client

The portal token belongs to Hallam's distributor portal agent. The course access list lets it use order_status only, and only for Hallam (customer 10000002).

python unit09/a2a_lab.py call --order 1000002 --skill credit_release_draft --token-env CALDER_PORTAL_TOKEN
python unit09/a2a_lab.py call --order 1000003 --token-env CALDER_PORTAL_TOKEN
python unit09/a2a_lab.py call --order 1000005 --token-env CALDER_PORTAL_TOKEN
python unit09/a2a_lab.py get --task task-0003 --token-env CALDER_PORTAL_TOKEN
HTTP 403: hallam-portal-agent may not use skill credit_release_draft
Task task-0004 (context ctx-0004): TASK_STATE_REJECTED
  agent says: Order 1000003 belongs to another customer; customer 10000002 may not read it.
Task task-0005 (context ctx-0005): TASK_STATE_COMPLETED
  agent says: Done.
  artifact art-0003 "Status of order 1000005"
    Order 1000005 for Hallam Fluid Systems is stuck on: price missing. Next step owner: Pricing team.
    data {"salesOrder": "1000005", "problem": "price missing", "owner": "Pricing team"}
A2A error -32001: Task not found: task-0003

Four layers of control, in order: the skill is refused before any task exists (403); Brennock's order is rejected because the caller acts for Hallam; Hallam's own order works; and another client's task is reported as "not found", so the portal can't even learn that it exists.

Step 10: Speak the older version, as Joule does today

python unit09/a2a_lab.py call --order 1000004 --version 0.3
Chosen interface: JSONRPC 0.3 at http://127.0.0.1:8776/a2a
Task task-0006 (context ctx-0006): completed

The client sent message/send without an A2A-Version header, and the server answered in the 0.3 shape: lower-case state, kind fields. That is the dialect SAP's pages describe for Joule, so a server you want Joule to call must accept it.

Step 11: Try a wrong token

Windows (PowerShell):

$env:CALDER_WRONG_TOKEN = "guess"
python unit09/a2a_lab.py call --order 1000002 --token-env CALDER_WRONG_TOKEN

macOS or Linux:

CALDER_WRONG_TOKEN=guess python unit09/a2a_lab.py call --order 1000002 --token-env CALDER_WRONG_TOKEN
HTTP 401: missing or unknown bearer token

The card was readable without a token (discovery), but the call was not (permission). Stop the server in the first terminal with Ctrl+C.

Step 12 (optional): Call your server with the official A2A SDK

To check that the lab speaks real A2A, call it with the official Python SDK. This step downloads the SDK and its dependencies.

  1. Add this line to requirements.txt and install it:
a2a-sdk==1.3.0
pip install -r requirements.txt
  1. Create unit09/a2a_sdk_client.py with this code:
"""Call the Calder A2A lab agent with the official A2A Python SDK (a2a-sdk 1.3.0).

Course: Orchestrate, Unit 9, "A2A for SAP agents". Optional step.
Start the lab agent first:  python unit09/a2a_lab.py serve
Then run:                   python unit09/a2a_sdk_client.py
"""

import asyncio
import os

import httpx
from a2a.client import ClientConfig, create_client
from a2a.types import a2a_pb2 as a2a

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass


async def main():
    token = os.environ.get("CALDER_A2A_TOKEN")
    if not token:
        raise SystemExit("Set CALDER_A2A_TOKEN in your .env file first (see Step 4).")
    http = httpx.AsyncClient(headers={"Authorization": f"Bearer {token}"})
    client = await create_client("http://127.0.0.1:8776", ClientConfig(httpx_client=http, streaming=False))
    first = a2a.Message(message_id="sdk-1", role=a2a.ROLE_USER,
                        parts=[a2a.Part(text="draft credit release 1000002")])
    async for event in client.send_message(a2a.SendMessageRequest(message=first)):
        task = event.task
        print(task.id, a2a.TaskState.Name(task.status.state))
    reply = a2a.Message(message_id="sdk-2", role=a2a.ROLE_USER, task_id=task.id, context_id=task.context_id,
                        parts=[a2a.Part(text="Hallam paid invoice 90000003 today; balance back under limit.")])
    async for event in client.send_message(a2a.SendMessageRequest(message=reply)):
        print(event.task.id, a2a.TaskState.Name(event.task.status.state), "-", event.task.artifacts[0].name)
    await http.aclose()


asyncio.run(main())
  1. Start the server again in the first terminal (python unit09/a2a_lab.py serve), then run:
python unit09/a2a_sdk_client.py
task-0001 TASK_STATE_INPUT_REQUIRED
task-0001 TASK_STATE_COMPLETED - Credit release request CRR-1000002

The SDK's client read the card, chose the JSON-RPC 1.0 interface, and drove the same two-turn task. This was tested with a2a-sdk 1.3.0 on Python 3.13 in November 2026.

Step 13: Save your work in Git

git add unit09/a2a_lab.py unit09/a2a_sdk_client.py requirements.txt
git commit -m "Unit 9: A2A lab for the order exceptions agent"

.env stays out of the commit because .gitignore lists it. If you skipped Step 12, leave out the last two file names.

How the code works

Part of the script What it does
ORDERS, CLIENTS, SKILLS Course data: the six open orders, the access list (token, who it acts for, allowed skills and customers) and the skills on the card
agent_card() Builds the public card with two interfaces (1.0 and 0.3), a bearer security scheme and the skills
Store Keeps tasks in memory with numbered IDs, so every run matches the expected output
read_request() Takes the skill and order from a data part if present, otherwise from the text
run_skill(), continue_task() The agent's work: reject outside the caller's customers, answer status, pause for a reason, write the draft
handle_rpc() Maps method names per version, refuses messages to finished tasks, hides other clients' tasks
to_v03() Rewrites 1.0-shaped answers into the 0.3 shape for older clients
Handler.do_POST() Authenticates the bearer token first (401), reads A2A-Version (no header means 0.3), then dispatches
Client The second agent: reads the card, picks an interface, sends messages, replies on a task
cmd_selftest() Starts a private server on a free port and runs the eleven checks

If something goes wrong

What you see What it means What to do
python: command not found or 'python' is not recognized Python is not on the path, or the environment is off Activate .venv (Step 1); see Set up your computer
ModuleNotFoundError: No module named 'a2a' The optional SDK is not installed Run Step 12's install, inside .venv
Set CALDER_A2A_TOKEN in your .env file first The token line is missing, or you ran from another folder Add the line (Step 4) and run from orchestrate-course
HTTP 401: missing or unknown bearer token The token value is wrong Check the spelling in .env; no spaces around =
ConnectionRefusedError or No agent card at ... The server isn't running Start it in the first terminal (Step 5)
OSError: [Errno 48] or address already in use Another program uses port 8776, or a second server is running Stop the other server, or run serve --port 8777 and add --url http://127.0.0.1:8777 to client commands
Task numbers differ from the text The server kept tasks from earlier runs Stop and restart the server, then repeat from Step 6
Calls hang or fail on a company laptop A proxy intercepts local traffic Set NO_PROXY=127.0.0.1,localhost, or ask IT; the lab never leaves your computer

The SAP way

Inbound: outside agents calling Joule agents

SAP's Architecture Center announced general availability of inbound A2A through the Agent Gateway on 27 October 2026. It covers SAP-delivered agents and custom Joule Studio agents, where supported. The setup, as described there:

  1. Register the client. A customer administrator registers the outside AI client in SAP for Me as an "Agent Gateway Consumer". Registration alone grants nothing.
  2. Run three formations, in order. Identity creates an OIDC agent identity in SAP Cloud Identity Services; Trust connects that identity to the gateway; Authorization creates the access list. Changing which agents a client may call means editing only the last formation.
  3. Discover. Agentic Resource Discovery (ARD), an open specification, returns matching agents with their agent card URLs. Discovery uses a technical token; the catalog is filtered by the access list.
  4. Invoke. Each call needs a user token. The gateway validates it, resolves the tenant and checks the access list. The SAP agent then works within that user's business authorizations.

The inbound reference page (updated 26 October 2026) adds that the gateway sits on an SAP-managed domain, that SAP Integration Suite can front it on a customer domain when you need API management or guaranteed delivery, that calls are audited in SAP Cloud ALM, and that long tasks can use an asynchronous callback. It describes A2A 0.3.0 over HTTP+JSON, and it still carries a not-yet-GA notice for some components.

The token is the hard part

SAP's token exchange page (updated 13 October 2026, parts "still in preparation") explains how a user's login on another platform becomes a token the gateway accepts. The outside runtime posts its token to SAP Cloud Identity Services with the jwt-bearer grant and a resource parameter naming the target. The reissued token's audience is the gateway, and its subject (the user) stays the same across every hop. When an agent acts for a user, the effective permission is the intersection of the user's and the agent's. Authorization is directional: agent A may call agent B without B being allowed to call A.

sequenceDiagram
  participant U as User in Copilot or AWS
  participant X as Outside runtime
  participant IAS as SAP Cloud Identity Services
  participant G as Agent Gateway
  participant J as Joule agent
  U->>X: signs in with the corporate IdP
  X->>IAS: token exchange (jwt-bearer, resource = gateway)
  IAS-->>X: token, audience gateway, same user
  X->>G: A2A message + token
  G->>G: validate token, tenant, access list
  G->>J: route, user context kept
  J-->>X: task result

Sketch: the Copilot Studio path

SAP's Microsoft Copilot page (updated 23 October 2026) puts Copilot Studio in charge of orchestration. Entra ID signs the user in and is federated with SAP Cloud Identity Services over OIDC. A Power Platform custom connector performs the token exchange and calls the Agent Gateway. SAP explains why it doesn't use Copilot Studio's built-in agent-to-agent connection: that path can't do the required exchange, and the gateway accepts only tokens minted for its own resource. Setup steps live in SAP's Agent Interoperability Cookbook on SAP-samples, which the page links.

Copilot Studio's native A2A connection still suits your own agents that accept an API key or plain OAuth. Microsoft's documentation describes it: on the agent's Agents page choose Add agent, then A2A agent, enter the agent's endpoint URL (not the card URL), pick None, API key or OAuth 2.0, and save. The page doesn't state a release status. Its browser check uses the older card path /.well-known/agent.json, which is why the lab serves the card at both paths.

Sketch: the AWS path through Bedrock AgentCore

AgentCore appears on both sides of A2A:

  • AgentCore calling Joule agents. SAP's Amazon Quick page (updated 23 October 2026) has Amazon Quick reach AgentCore Runtime over MCP, because Quick doesn't speak A2A itself. AgentCore Identity exchanges the user's token with SAP Cloud Identity Services on the user's behalf, signing with a key that stays in AWS KMS, and the runtime sends A2A message/send to the Agent Gateway.
  • AgentCore hosting your own A2A agent. AWS's A2A protocol contract expects an ARM64 container listening on port 9000, JSON-RPC at /, the card at /.well-known/agent-card.json, and OAuth bearer tokens or AWS SigV4. Its example card shows protocolVersion 0.3.0.

The lab's server would need three changes to fit that contract: listen on 0.0.0.0:9000, accept POST at /, and validate real OAuth tokens instead of course values.

Outbound: Joule calling your agent

For an agent your team builds, SAP's outbound page (updated 26 October 2026) lists the steps: expose an A2A endpoint, create a Joule scenario, add a dialog function of action type agent-request pointing at the endpoint, and set up an App2App trust in SAP Cloud Identity Services. Joule then acts as an A2A 0.3.0 client and sends message/send. Three limits shape your agent:

  • 60 seconds. Joule expects a synchronous answer within 60 seconds.
  • Long tasks use push notifications to a Joule-provided webhook. The lab's card says pushNotifications: false, so it would only suit short tasks.
  • Multi-turn works through task and context IDs that your server generates and Joule sends back, exactly what Step 8 did.

The same page says some components are not yet GA. Self-built agents also need a home: see Joule agents and agent orchestration and choosing an agent SDK.

Build vs. SAP

Need Your own A2A endpoint (as in the lab, hardened) SAP Agent Gateway (inbound) Joule scenario (outbound)
Who is called Your agent SAP-delivered or Joule Studio agents Your agent, from Joule
Who registers callers You (API gateway, OAuth server) Customer admin in SAP for Me and formations Joule scenario plus App2App trust
User identity into SAP You design the token flow SAP's token exchange, user kept end to end App2App trust; user context per SAP's guide
A2A version Your choice; offer 0.3 and 1.0 0.3.0 over HTTP+JSON, per SAP's page 0.3.0, message/send
Audit Your logging SAP Cloud ALM Joule and your logging
Status, November 2026 Depends on you GA announced 27 October 2026 Some components not yet GA

Architecture view

Where it sits. Calder's CRM assistant runs in the front office. SAP's agents and Calder's own order exceptions agent run on the SAP Business AI Platform, reading S/4HANA (CP10) through released APIs. A2A is the line between assistants and agents; MCP and APIs are the lines below it.

flowchart LR
  CRM[CRM assistant<br/>Copilot Studio] -- inbound A2A --> AG[Agent Gateway]
  AG --> JA[Joule agents<br/>SAP-delivered, Joule Studio]
  J[Joule] -- outbound A2A --> OE[Calder order exceptions agent<br/>BTP, pro-code]
  JA -- APIs, MCP --> S4[S/4HANA CP10]
  OE -- released APIs --> S4
  IAS[SAP Cloud Identity Services] -.token exchange.-> AG

Non-functional requirements.

Requirement Typical target What breaks if missed
Identity Named user from the first hop to SAP Actions run as a technical user; audit can't name who asked
Authorization Access list per client; user roles in SAP A portal agent reads another customer's orders
Latency Answer or task handle within Joule's 60 s window Joule times out; users retry and create duplicate drafts
Version compatibility Accept A2A 0.3 and 1.0 until SAP moves Calls fail with version errors after an SDK upgrade
Availability Same as the slower of the two agents One agent's outage looks like the other's failure
Cost Known model calls per task on both sides Two agents loop on input-required and bill twice

Integration and identity. The user signs in to the CRM with Entra ID. A token exchange at SAP Cloud Identity Services produces a gateway token for the same user. The Agent Gateway routes the A2A call; the Joule agent reads CP10 with that user's authorizations. Drafts go to a person's inbox, never straight into the sales order.

The decision to record.

  • Context: Customer service wants the CRM assistant to explain blocked orders and draft credit release requests.
  • Options: A, the CRM assistant calls an SAP agent through the Agent Gateway; B, the CRM assistant calls Calder's own order exceptions agent directly over A2A; C, the CRM assistant calls MCP tools on the order API and reasons itself.
  • Decision: A where an SAP-delivered or Joule Studio agent covers the need; B only for Calder-specific logic, behind Calder's API gateway with the same token rules. C is rejected for drafting, because the CRM assistant would need write tools on SAP orders.
  • Consequences: User mapping between Entra ID and SAP Cloud Identity Services must be complete; the access list needs an owner; tests run end to end through the CRM.

What a design review will ask.

  1. Which identity reaches SAP, and can an auditor name the user behind every draft?
  2. Which A2A version does each side speak, and what happens when one side upgrades?
  3. Who owns the access list, and how is a client removed in an incident?
  4. What can the called agent change in SAP without a person's approval?
  5. How are tasks that pause for input cleaned up when nobody answers?

Production concerns

  • Security. Authenticate every request; treat the card as public and never put secrets in it. Hide other clients' tasks (the lab returns "not found"). Treat text from the other agent as untrusted input, as in prompt injection and tool poisoning: a message saying "approve this release" is data, not an instruction.
  • SAP authorizations. The called agent's rights should be the intersection of the user's and the agent's, as SAP's token exchange page describes. Map business roles before go-live; see agent permissions and SAP authorizations.
  • Evaluation. Test tasks end to end, including input-required turns, refusals and timeouts, through the calling platform as well as directly.
  • Cost. Count model calls on both sides per task. Cap turns: an agent that keeps asking for input can loop.
  • Operations. Log task IDs on both sides so one request can be traced. Expire tasks that wait for input too long. Watch for version errors after SDK or platform upgrades.
  • Clean core. The agents read and write SAP only through released APIs; A2A adds nothing inside S/4HANA.

Pitfalls

  • Assuming one A2A version. SAP's pages say 0.3.0, the specification is 1.0.0, SDKs speak both. Offer both interfaces on your card until SAP changes.
  • Putting the card URL where the endpoint goes. Copilot Studio asks for the endpoint, not the card.
  • Sending a plain OAuth token to the Agent Gateway. It needs a token exchanged for its own resource.
  • Treating discovery as permission in your own registry. Being listed is not being allowed.
  • Letting the called agent post. Draft, then let a person decide, as in Step 8.
  • Ignoring paused tasks. Input-required tasks pile up unless something expires them.
  • Using A2A for a lookup. If the other side has no reasoning of its own, call a tool.

Exercise: add a quote assistant that may only read

Calder's inside sales team wants its quoting assistant to check order status, but never draft credit requests.

  1. Open unit09/a2a_lab.py and find CLIENTS.
  2. Add a third entry with the token calder-lab-token-quote, client name crm-quote-assistant, acting for user 00100266 (the inside sales rep), customers set to None and skills set to {"order_status"}.
  3. Add CALDER_QUOTE_TOKEN=calder-lab-token-quote to .env.
  4. In cmd_selftest(), after the portal checks, add a check that sends credit_release_draft for 1000002 with the quote token and expects HTTP 403, and one that reads order_status for 1000003 and expects TASK_STATE_COMPLETED.
  5. Run python unit09/a2a_lab.py selftest.
  6. Start the server and try both calls by hand with --token-env CALDER_QUOTE_TOKEN.

Done when the self-test prints 13 of 13 checks passed, and the quote assistant reads Brennock's order 1000003 but gets HTTP 403 for a credit release draft. Keep the file: the multi-agent topic later in Unit 9 puts a supervisor over agents like this one.

Going further

For readers who want the parts of A2A this lab left out.

  • Streaming and push notifications. SendStreamingMessage and SubscribeToTask send task updates as they happen; push notification configs let the server call a webhook instead. SAP's outbound page relies on push notifications for tasks longer than Joule's 60 seconds. The A2A specification defines both, gated by the card's capabilities.
  • Signed agent cards. A card may carry JSON Web Signatures computed over a canonical form of the card (RFC 8785), and clients should verify at least one signature before trusting it. This matters once cards come from registries rather than from the agent itself (A2A specification).
  • The extended agent card. GetExtendedAgentCard lets an authenticated client see more than the public card, for example skills only some callers may use.
  • Hosting contracts. AWS's AgentCore contract shows how a managed runtime constrains an A2A server: fixed port and path, a health check at /ping, a session header, and real HTTP status codes with JSON-RPC errors in the body.
  • SDKs. a2a-sdk 1.3.0 offers JSON-RPC, HTTP+JSON and gRPC on both client and server, with the 0.3 compatibility mode. Rebuilding the lab's server on it is a good next step.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1What is the job of the agent card?

Answer: C. The card is public discovery: name, skills, interfaces and security schemes. Permission is checked separately on every call, and secrets never go in the card.

2In the lab, the credit release task stops at TASK_STATE_INPUT_REQUIRED. How does the client finish it?

Answer: A. Input required pauses the task for the caller. The client replies with a message that names the task and context IDs, and the server continues the same task to completion.

3Joule calls your agent with message/send and no A2A-Version header. Your server only accepts SendMessage. What happens?

Answer: D. No header means 0.3, and SAP's outbound page says Joule sends message/send as an A2A 0.3.0 client. A 1.0-only server refuses it; offering both interfaces on the card keeps Joule working.

4Why does the lab return "task not found" when the portal agent asks for the CRM assistant's task?

Answer: A. Answering "forbidden" would confirm the task exists. Returning the specification's task-not-found error hides other clients' work, the same principle as SAP filtering its catalog by the access list.

5The portal agent asks for order 1000003 and gets a REJECTED task, not HTTP 403. What explains the difference?

Answer: A. HTTP 403 comes before any task, when the skill itself isn't on the client's access list. Here order_status is allowed, so a task starts, and the agent rejects it because the order belongs to Brennock while the caller acts for Hallam.

6In SAP's inbound design, what must an outside runtime send to the Agent Gateway?

Answer: C. SAP's pages say the gateway accepts only tokens minted for its own resource, obtained by a token exchange that keeps the user as subject. A plain token from the outside IdP has the wrong audience.

7Copilot Studio has a built-in A2A connection. Why does SAP's Copilot design use a custom connector to reach Joule agents?

Answer: C. SAP's page says the custom connector performs the token exchange with SAP Cloud Identity Services, which the native agent-to-agent path can't, and the gateway needs that exchanged token. The built-in connection still suits agents that accept API keys or plain OAuth.

8Your team wants Joule to call Calder's agent for a job that takes about five minutes. What must the agent support?

Answer: A. SAP's outbound page says Joule expects a synchronous answer within 60 seconds and uses push notifications to a Joule webhook for long-running tasks. The lab's card sets push notifications to false, so it would suit only short tasks.

Sources

  • Agent2Agent (A2A) Protocol Specification (a2a-protocol.org, latest released version 1.0.0) — opened 2026-11-16; latest released version 1.0.0 (earlier 0.3.0, 0.2.6, 0.1.0); agent card, task, message, part and artifact objects; nine TASK_STATE_ values; JSON-RPC methods SendMessage, SendStreamingMessage, GetTask, ListTasks, CancelTask, SubscribeToTask, push notification config methods, GetExtendedAgentCard; REST endpoints such as POST /message:send; error codes -32001 TaskNotFoundError to -32009 VersionNotSupportedError; clients send the A2A-Version header and an empty header is treated as 0.3; well-known path /.well-known/agent-card.json; identity handled by standard web security, not inside A2A messages; agent cards may be signed with JWS over an RFC 8785 canonical form
  • Agent Gateway enables A2A interoperability with SAP Agents (SAP Architecture Center news, 27 October 2026) — opened 2026-11-16; October 2026 GA of inbound A2A interoperability through the Agent Gateway; Agentic Resource Discovery (ARD) returns agents with AgentCard URLs; discovery does not grant permission (technical token for discovery, user token for invocation); consumer registered in SAP for Me as an Agent Gateway Consumer; Identity, Trust and Authorization formations in sequence; ACL checked on every call; SAP agent works within the signed-in user's authorizations; outbound A2A and outbound MCP are future direction
  • Integrating Joule Agents into Your Ecosystem (Inbound A2A) (SAP Architecture Center, updated 26 October 2026) — opened 2026-11-16; Agent Gateway on an SAP-managed domain; SAP Integration Suite A2A connectivity as a customer-managed alternative that delegates to the gateway; SAP Cloud Identity Services App2App tokens with a named user context; Cloud ALM audit logging; A2A 0.3.0 over HTTP+JSON; asynchronous callbacks for long tasks; names Google Vertex AI, Microsoft Copilot Studio and AWS Bedrock AgentCore as callers; some components not yet GA; bidirectional communication with third-party and self-hosted agents not yet supported
  • Integrating AI Agents with Joule (Outbound A2A) (SAP Architecture Center, updated 26 October 2026) — opened 2026-11-16; pro-code agents must be A2A servers; Joule scenario with a dialog function of action type agent-request; Joule as A2A client sends message/send (A2A 0.3.0); App2App trust in Cloud Identity Services; synchronous responses within 60 seconds; push notifications to a Joule webhook for long tasks; multi-turn through context and task IDs; some components not yet GA
  • Third-Party A2A Integration & Token Exchange (SAP Architecture Center, updated 13 October 2026) — opened 2026-11-16; jwt-bearer token exchange at SAP Cloud Identity Services with a resource parameter; token audience for the Agent Gateway; subject kept across hops; effective permission is the intersection of the user's and the agent's; access@agent policy; authorization is directional; parts still in preparation
  • Microsoft Copilot Integration with Joule Agents (SAP Architecture Center, updated 23 October 2026) — opened 2026-11-16; Copilot Studio as orchestration layer; Entra ID federated with SAP Cloud Identity Services over OIDC; a Power Platform custom connector exchanges the token and calls the Agent Gateway, because Copilot Studio's native agent-to-agent path cannot do the exchange; the gateway accepts only tokens minted for its resource; says the Agent Gateway is not yet GA
  • Amazon Quick Integration with Joule Agents (SAP Architecture Center, updated 23 October 2026) — opened 2026-11-16; Amazon Quick reaches AgentCore Runtime over MCP; AgentCore sends A2A message/send to the Agent Gateway; AgentCore Identity performs an on-behalf-of exchange with SAP Cloud Identity Services using a private_key_jwt assertion whose key stays in AWS KMS; says the Agent Gateway is not yet GA
  • A2A protocol contract (Amazon Bedrock AgentCore Developer Guide) — opened 2026-11-16; JSON-RPC 2.0 over HTTP on port 9000 at path /; agent card at /.well-known/agent-card.json; ARM64 container; OAuth 2.0 bearer tokens or SigV4; example card shows protocolVersion 0.3.0 and message/send
  • Connect an agent available over the Agent2Agent (A2A) protocol (Microsoft Copilot Studio documentation) — opened 2026-11-16; Agents page, Add agent, A2A agent; the endpoint URL is the agent's communication endpoint, not the card URL; authentication None, API key or OAuth 2.0; browser check at <endpoint>/.well-known/agent.json; release status not stated on the page
  • a2a-sdk (PyPI) — opened 2026-11-16; version 1.3.0 released 27 October 2026; implements A2A 1.0 with a compatibility mode for 0.3; JSON-RPC, HTTP+JSON and gRPC for client and server; Python 3.10 or later

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in