# Project: a cross-platform agent (Copilot Studio and Bedrock to SAP, one identity)

> Build one governed SAP entry that a Copilot Studio agent and a Bedrock agent both use, over MCP and A2A, with each person's own SAP identity.

- Course: Orchestrate, Portfolio projects
- Page: https://erpfde.com/topics/project-cross-platform-agent/
- Updated: 2026-11-26
- Reading time: Foundational 9 min, Deep 60 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The business problem

Calder Pumpworks, the course's fictional pump maker, now has agents on two other platforms. Customer service works in Microsoft Teams and built an agent in Microsoft Copilot Studio. The aftermarket team works in Amazon Quick and had an agent built on Amazon Bedrock AgentCore. Both agents need the same thing from SAP: why is this sales order stuck, and can credit take another look?

Each team solved it alone. Each prototype calls SAP with one shared technical user and a key in a configuration screen. It works in a demo. It fails a security review, for three reasons:

- **SAP can't tell who asked.** Every read shows the same technical user. The audit trail names a robot, not a person.
- **People see more through the agent than in SAP.** The inside sales rep works only direct customers. Through the agent, the technical user reads distributor orders on his behalf.
- **Two integrations to run.** Two keys to rotate, two sets of logs, two ways to reach SAP, and a third on the way.

**Who feels it:** the security and audit teams who can't sign off, the integration team who runs both connections, and the business users who wait while the agents stay in pilot.

**Today's numbers** must come from your own landscape. In Calder's made-up starting point, 0% of agent requests reach SAP as the person who asked, because both prototypes use a technical user.

The brief: **give Calder one governed way in. Both platforms read through the same MCP gateway and delegate to the same SAP agent over A2A, and every call carries the asking person's own SAP identity.** No agent changes SAP. A credit review is a draft that the credit analyst decides.

### What the solution does

A day in the life at Calder, after go-live:

1. **08:05.** The customer service clerk asks the Copilot Studio agent in Teams why order `1000002` is stuck. The answer, a credit block for Hallam Fluid Systems, comes from SAP. SAP's log shows the clerk's own SAP user, `00100265`.
2. **08:20.** The inside sales rep asks the same question. SAP refuses, because his role covers direct customers only. The agent passes the refusal on instead of guessing.
3. **08:40.** The clerk asks the agent to request a credit review because Hallam paid. The Copilot agent doesn't do this itself. It hands the task over A2A to Calder's order-exceptions agent on the SAP side, which drafts `CRR-1000002` for the credit analyst.
4. **09:15.** In Amazon Quick, the same clerk asks the Bedrock agent the same thing. SAP answers that the request already waits for the analyst. One draft, not two.
5. **09:30.** A partner who has an AWS sign-in but no Calder identity asks about an order. Calder's identity service refuses the exchange. The question never reaches SAP.
6. **Friday.** The integration lead shows the KPI: every request that reached SAP carried the asking person's own SAP user, on both platforms, and no SAP record names a technical user.

> **Note** **For functional consultants.** Your roles now decide what an agent may show, on every platform. A user needs three things: an identity in SAP Cloud Identity Services, an SAP role with the right sales areas, and, for delegated tasks, assignment to the SAP agent's access policy. Add "through the agent, from Teams and from Quick" as test steps for every role change in order-to-cash, and expect a role change to show up in the agents the same day.

### The KPI

[Defining success metrics with the business](https://erpfde.com/topics/defining-success-metrics-with-the-business/) explains how to agree a KPI a business owner can sign. The brief asked for **requests served across platforms with identity propagated**. Here it is, made measurable:

| | Identity kept | Technical-user records (guardrail) | SAP changes by an agent (guardrail) |
| --- | --- | --- | --- |
| **Metric** | Share of requests that reached SAP where every SAP record names the asking person's own SAP user | SAP records made under a technical user | Orders changed by any agent |
| **Baseline** | 0%: both prototypes use a technical user | Every request | 0 |
| **Target** | 100%, per platform | 0 | Always 0 |
| **How it is measured** | Platform log joined to SAP's audit log by request ID | SAP's audit log | SAP's audit log and change documents |

The KPI counts a refusal by SAP as a success when SAP refused the right person. If the rep is refused a distributor order under his own SAP user, identity was kept and the system worked.

In the project's test run, all 9 requests that reached SAP (5 from the Bedrock agent, 4 from the Copilot agent) carried the asking person's SAP user, and no record named a technical user. Run the same 12 questions through a shared technical user and the KPI falls to 0 of 7, the rep reads a distributor order, and the partner with no Calder identity gets an answer.

> **Note** These numbers come from the project's 12 test questions on synthetic data and local stand-ins. They show the method, not a result from a real SAP system.

### Architecture at a glance

```mermaid
flowchart LR
  T["Teams: Copilot Studio agent"] --> E["Entra ID"]
  Q["Amazon Quick: Bedrock AgentCore agent"] --> C["Cognito"]
  E --> I["SAP Cloud Identity Services<br/>token exchange"]
  C --> I
  I --> M["MCP gateway<br/>Integration Suite"]
  I --> A["Agent Gateway<br/>A2A"]
  M -->|read as the person| S["SAP S/4HANA"]
  A --> O["Order-exceptions agent"]
  O -->|read as the person| S
  O --> D["Draft for the credit analyst"]
```

Each platform keeps its own sign-in: Microsoft Entra ID for Teams, Amazon Cognito for Quick. **SAP Cloud Identity Services** trusts both. It swaps the platform's token for one that SAP accepts and that still names the same person. Reads go through the **MCP gateway** in SAP Integration Suite as tools. Tasks that need judgment, like a credit review request, go over **A2A** through SAP's **Agent Gateway** to an agent on the SAP side. SAP S/4HANA checks every read against the person's own role.

### Risks and controls

| Risk | Control in this design |
| --- | --- |
| SAP serves a technical user instead of the person | Every call carries a token exchanged for the person. The KPI's guardrail counts technical-user records, and its target is 0. |
| A token for one service is reused at another | Each token names one audience. A token minted for the MCP gateway is refused at the Agent Gateway. |
| Someone with a platform sign-in but no Calder identity gets in | The exchange refuses anyone unknown to Calder's identity service. The request never reaches SAP. |
| A platform calls SAP agents it shouldn't | The Agent Gateway checks an allow-list of platform clients per SAP agent, then whether the person is assigned to the agent. |
| An agent changes an order | No tool changes SAP. The SAP agent writes a draft; the credit analyst decides in SAP under her own authorization. |
| Two platforms create the same request twice | The SAP agent checks for an open request on the order before it drafts. |
| Each new platform adds another integration | New platforms register as one more client of the same two gateways. The exercise adds a third. |

### What to show a stakeholder

1. Ask the Copilot agent about order `1000002` as the clerk: answered, and SAP's log shows `00100265`.
2. Ask the same as the inside sales rep: refused by SAP, under his own user `00100266`.
3. Ask the Bedrock agent the same question as the clerk: the same answer through the same gateway.
4. Request a credit review from Copilot, then again from Bedrock: one draft, and the second answer says it already waits.
5. Ask as the partner with no Calder identity: refused before SAP.
6. Rerun the test set with the shared technical user. Show the rep reading a distributor order and the KPI at 0%.
7. Show the KPI table and the synthetic-data note beside it.

### Questions to ask

- Which identity provider signs in each platform's users, and does SAP Cloud Identity Services trust it today?
- Are all agent users provisioned in Cloud Identity Services and mapped to their SAP users?
- Which reads do the agents need as tools, and which tasks should they hand to an SAP agent instead?
- Is the MCP gateway available in our Integration Suite service plan, and is the Agent Gateway available for our tenant and region?
- Who registers each platform as an Agent Gateway consumer, and who decides which SAP agents it may call?
- Where do platform logs and SAP logs meet, so we can prove who asked what?
- What do the platforms cost per request, and what does each SAP agent step cost?

### Check yourself

1. Both Calder prototypes worked in the demo. Why did they fail the security review?
   - A. The platforms stored SAP data outside Calder's tenant
   - B. SAP saw one technical user, so it couldn't tell who asked
   - C. The agents used models that SAP hasn't approved
   - D. The prototypes called SAP without any authentication at all

   Answer: B. Each prototype reached SAP with a shared technical user and a key. SAP's log names the robot, and the technical user's wider rights let the rep read distributor orders through the agent.

2. The inside sales rep asks about a distributor order and SAP refuses. How does the KPI count this?
   - A. As a failure, because the request wasn't served to the rep
   - B. As excluded, because refusals don't count toward the KPI
   - C. As a failure of the platform agent, which should have answered
   - D. As a success: SAP refused him under his own SAP user

   Answer: D. The KPI measures whether SAP saw the person who asked. A refusal under the rep's own SAP user is SAP's authorization working as designed.

3. When should a platform agent hand a task to an SAP agent over A2A, not call an MCP tool?
   - A. When the question needs data from more than one SAP table
   - B. When SAP-side rules decide and the result is a draft
   - C. When the platform's model can't read the tool's description
   - D. When the user wants the answer faster than a tool can give it

   Answer: B. Reads fit tools on the MCP gateway. A credit review request needs rules that SAP owns, such as checking the block and the open requests, so the SAP agent does it and a person decides.

4. A partner has an AWS sign-in but no Calder identity. What should happen?
   - A. The Bedrock agent answers from cached data only
   - B. SAP answers as a guest with read-only rights
   - C. Calder's identity service refuses the exchange before SAP
   - D. The MCP gateway logs the call and lets it through once

   Answer: C. SAP Cloud Identity Services issues a token only for people it knows. With a shared technical user instead, the partner got an answer, which is exactly the hole this design closes.

5. Customer service wants to add a third platform next quarter. What does this design make the work?
   - A. A third connection to SAP, with its own technical user and key
   - B. A copy of the MCP gateway for the new platform's team
   - C. One more client, its sign-in trusted, allowed per SAP agent
   - D. A rewrite of the SAP agent in the new platform's language

   Answer: C. Both gateways and the SAP agent stay as they are. The new platform becomes one more client of Calder's identity service, with an entry on the Agent Gateway's allow-list.

6. Which guardrail result should stop go-live?
   - A. One request was refused because the person had no SAP role
   - B. The Bedrock agent took longer to answer than the Copilot agent
   - C. The credit analyst still has a draft waiting from the test run
   - D. Two SAP records name a technical user instead of a person

   Answer: D. A technical-user record means a path exists where SAP can't tell who asked, so the identity promise is broken. Refusals, timings and waiting drafts are normal behavior.

## Deep layer

### What you will build

You will build both sides of a cross-platform agent on your own computer. The **SAP side** is one local server with four stand-ins: SAP Cloud Identity Services' token exchange, the MCP gateway in SAP Integration Suite, SAP's Agent Gateway in front of an order-exceptions agent, and S/4HANA's orders, roles and audit log. The **platform side** is two agents: one shaped like a Copilot Studio agent signed in through Entra ID, one shaped like a Bedrock AgentCore agent signed in through Cognito. Then you test both against release gates and compute the KPI from the logs.

```mermaid
flowchart LR
  S1["Stage 1: SAP data<br/>sap_side.py"] --> S2["Stage 2: routing<br/>platform_agent.py"]
  S2 --> S3["Stage 3: API<br/>token exchange, MCP, A2A"]
  S3 --> S4["Stage 4: UI<br/>ask from the command line"]
  S4 --> S5["Stage 5: deployment<br/>preflight + platform sketches"]
  S5 --> S6["Stage 6: evaluation<br/>evaluate.py run"]
  S6 --> S7["Stage 7: KPI<br/>evaluate.py kpi"]
```

| File | Stage | What it does |
| --- | --- | --- |
| `common.py` | 1 | Settings, the lab secrets in `.env`, small signed lab tokens and the log files |
| `sap_side.py` | 1, 3 | The SAP side: token exchange, MCP gateway, Agent Gateway with the SAP agent, S/4HANA data and audit log |
| `platform_agent.py` | 2, 3, 4, 5 | The two platform agents: sign-in, routing, token exchange, calls, and a preflight check |
| `evaluate.py` | 6, 7 | Twelve test cases, four release gates, the KPI and a trace view |

Everything runs on made-up, SAP-shaped data with Python's standard library plus `python-dotenv`, which the course setup installed. No account is needed, and no paid service.

**Prerequisites.** You should have done these published topics, or be ready to look back at them:

- [Order to cash, end to end](https://erpfde.com/topics/order-to-cash-end-to-end/) (Unit 1): the blocked orders `1000002` to `1000007` come from there.
- [The MCP gateway in Integration Suite, hands on](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) (Unit 4): policies and tools on the gateway.
- [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/) (Unit 8): agent cards, tasks and SAP's Agent Gateway.
- [Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) (Unit 11): whose identity SAP sees.
- [Microsoft Copilot Studio and Azure with SAP](https://erpfde.com/topics/microsoft-copilot-studio-and-azure-with-sap/) (Unit 15): the Microsoft routes, and the API key lab this project improves on. The AWS routes are covered in Unit 15 too.
- [Where should an agent live?](https://erpfde.com/topics/where-should-an-agent-live/) (Unit 15): why Calder's agents sit on several platforms at all.
- [Human approval in AI workflows](https://erpfde.com/topics/human-approval-in-ai-workflows/) and [evaluating agents](https://erpfde.com/topics/evaluating-agents/): drafts, decisions and gates.

**Time:** 3 to 4 hours, over a few sessions. **Cost:** free. Running it on Copilot Studio, AWS and SAP's real gateways needs paid or trial access on all three; Stage 5 marks those steps as a sketch.

> **Note** New words in this project. **Identity provider**: the service that signs people in and issues tokens, such as Microsoft Entra ID or Amazon Cognito. **Token**: a signed note saying who someone is (`sub`), which service it is for (`aud`, the audience) and until when (`exp`). **Token exchange**: swapping one token for another at an identity service, here SAP Cloud Identity Services, so the new token names the service you call next. **Principal propagation**: carrying the person's identity from hop to hop so the last system acts as that person. **Technical user**: an SAP user that belongs to a program, not a person. **MCP gateway**: the part of SAP Integration Suite that offers SAP APIs as tools to agents over the Model Context Protocol. **A2A**: the Agent2Agent protocol, for one agent to hand a task to another. **Agent Gateway**: SAP's entry point for A2A calls to agents on the SAP side. **Consumer**: a platform registered to call the Agent Gateway.

### Stage 1: SAP data

You build the SAP side first, because both platforms will share it. One script plays four SAP roles so you can watch every decision.

```mermaid
flowchart LR
  T["/oauth2/token<br/>Cloud Identity Services"] --> M["/mcp<br/>MCP gateway"]
  T --> A["/v1/a2a/order-exc/<br/>Agent Gateway + SAP agent"]
  M --> S["S/4HANA stand-in<br/>orders, roles, audit log"]
  A --> S
```

> **Before you start:** finish [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/), and the [Unit 15 setup](https://erpfde.com/topics/set-up-for-unit-15/) if you want to try the platform sketches in Stage 5. This project doesn't need anything those topics don't already install.

#### What the SAP data looks like

| Data | Where in real SAP | In the lab |
| --- | --- | --- |
| Six blocked orders `1000002` to `1000007`, with customer, channel, amount, problem and owner | Sales orders in S/4HANA; problem and owner are course fields | `ORDERS` in `sap_side.py` |
| Three people with SAP users: clerk `00100265`, rep `00100266`, credit analyst `00100304` | Users in Cloud Identity Services, mapped to SAP users | `IAS_USERS` |
| What each SAP user may display: channels 10, 20, 30 for the clerk and analyst, 10 only for the rep | SAP roles with sales area authorizations | `SAP_ROLES` |
| Two platform clients and the identity provider each one may bring | Applications and corporate identity provider trust in Cloud Identity Services | `CLIENTS` |
| Which platforms may call the SAP agent, and which users are assigned to it | Agent Gateway consumer formations and the agent's access policy | `AGENT_ACL`, `ACCESS_AT_AGENT` |

> **Note** Calder Pumpworks, its people, orders, users, clients and rules are made up. The tables stand in for configuration that lives in SAP Cloud Identity Services, the Agent Gateway's formations and S/4HANA roles. The addresses ending in `.example` are reserved test names that reach nothing.

#### What you need

- About 30 minutes. No cost, no account, no internet.
- Two terminals: one runs the SAP side, the other runs your commands.

#### Step 1: Open the course folder and turn on the environment

1. Open VS Code, choose **File > Open Folder** and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. Turn on the virtual environment if the prompt doesn't start with `(.venv)`:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Check Python and the one library this project uses:

   ```bash
   python -c "import sys, dotenv; print(sys.version.split()[0], 'dotenv OK')"
   ```

   You should see `3.10` or newer, then `dotenv OK`. All commands in this project run from the `orchestrate-course` folder.

#### Step 2: Create the project folder

1. Create the folder:

   - **Windows (PowerShell):**

     ```powershell
     mkdir projects\cross-platform-agent
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p projects/cross-platform-agent
     ```

2. Keep the logs out of Git. Open `.gitignore` in the course folder, add this line at the end and save:

   ```text
   projects/cross-platform-agent/*.jsonl
   ```

#### Step 3: Save the shared plumbing

In VS Code's file list, right-click `projects/cross-platform-agent`, choose **New File**, name it `common.py`, paste the code below and save (Ctrl+S, or Cmd+S on Mac).

```python
"""Shared lab plumbing for the cross-platform agent project.

Settings, the lab secrets in .env, small HS256 lab tokens and the log files.
Every name, address and number here is a course value. Calder Pumpworks is fictional.
"""
import base64
import hashlib
import hmac
import json
import os
import secrets
import sys
import time
from pathlib import Path

from dotenv import load_dotenv

HERE = Path(__file__).resolve().parent
COURSE = HERE.parents[1]                      # orchestrate-course
ENV_FILE = COURSE / ".env"

HOST, PORT = "127.0.0.1", 8792
BASE = f"http://{HOST}:{PORT}"

# Who issues tokens. The first two stand in for the platforms' identity providers,
# the third for SAP Cloud Identity Services. All three are made-up addresses.
ENTRA_ISSUER = "https://login.calder-entra.example/lab"
COGNITO_ISSUER = "https://cognito.calder-aws.example/lab"
IAS_ISSUER = "https://calder-ias.example"

# The resource a token is minted for (its audience). The agent gateway value is the one
# SAP's interoperability cookbook documents; the MCP gateway value is a course label.
AGW_RESOURCE = "urn:sap:identity:application:provider:name:agent-gateway"
MCP_RESOURCE = "urn:calder:lab:mcp-gateway"
JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer"

SECRET_NAMES = ["CALDER_ENTRA_LAB_KEY", "CALDER_COGNITO_LAB_KEY", "CALDER_IAS_LAB_KEY",
                "CALDER_COPILOT_CLIENT_SECRET", "CALDER_AGENTCORE_CLIENT_SECRET"]

AUDIT_LOG = HERE / "sap_audit.jsonl"          # written by the SAP side
DRAFTS = HERE / "sap_drafts.jsonl"            # credit review requests drafted by the SAP agent
PLATFORM_LOG = HERE / "platform_log.jsonl"    # written by the platform agents


def init_env():
    """Add any missing lab secret to .env as a random value. Keeps everything already there."""
    load_dotenv(ENV_FILE)
    lines = ENV_FILE.read_text(encoding="utf-8").splitlines() if ENV_FILE.exists() else []
    added = [name for name in SECRET_NAMES if not os.getenv(name)]
    lines += [f"{name}={secrets.token_urlsafe(32)}" for name in added]
    ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
    print("Added to .env: " + ", ".join(added) if added else "All five lab secrets are already in .env.")


def secret(name):
    load_dotenv(ENV_FILE)
    value = os.getenv(name, "")
    if len(value) < 32:
        sys.exit(f"Missing {name} in .env. Run: python projects/cross-platform-agent/sap_side.py init")
    return value


def reset_logs():
    for path in (AUDIT_LOG, DRAFTS, PLATFORM_LOG):
        path.unlink(missing_ok=True)


def append_jsonl(path, record):
    with open(path, "a", encoding="utf-8") as handle:
        handle.write(json.dumps(record) + "\n")


def read_jsonl(path):
    if not path.exists():
        return []
    return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]


# ---------------------------------------------------------------- lab tokens (JWT, HS256)
# Real identity providers sign with private keys and publish public keys (JWKS).
# The lab signs with shared secrets so it needs no extra library. Same checks, simpler keys.

class TokenError(Exception):
    pass


def _b64(data):
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def _unb64(text):
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def sign(claims, key):
    header = _b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
    body = _b64(json.dumps(claims, separators=(",", ":")).encode())
    mac = hmac.new(key.encode(), f"{header}.{body}".encode(), hashlib.sha256).digest()
    return f"{header}.{body}.{_b64(mac)}"


def verify(token, key, issuer, audience):
    """Algorithm, signature, issuer, audience, expiry. Any failure raises (fail closed)."""
    try:
        header, body, mac = token.split(".")
        if json.loads(_unb64(header)).get("alg") != "HS256":
            raise TokenError("unexpected algorithm")
        claims = json.loads(_unb64(body))
    except (ValueError, json.JSONDecodeError) as err:
        raise TokenError("malformed token") from err
    expected = _b64(hmac.new(key.encode(), f"{header}.{body}".encode(), hashlib.sha256).digest())
    if not hmac.compare_digest(expected, mac):
        raise TokenError("bad signature")
    if claims.get("iss") != issuer:
        raise TokenError("wrong issuer")
    if claims.get("aud") != audience:
        raise TokenError(f"wrong audience (token is for {claims.get('aud')})")
    if int(claims.get("exp", 0)) < time.time():
        raise TokenError("expired")
    return claims
```

#### Step 4: Save the SAP side

Create `sap_side.py` in the same folder, paste this code and save.

```python
"""The SAP side of the cross-platform agent project, as one local stand-in server.

Four parts on http://127.0.0.1:8792, each a stand-in, not SAP software:
  /oauth2/token        SAP Cloud Identity Services: exchanges a platform token for one SAP accepts
  /mcp                 MCP gateway in SAP Integration Suite: two read tools over Calder's sales orders
  /v1/a2a/order-exc/   SAP Agent Gateway in front of an order-exceptions agent (A2A 0.3 message/send)
  (inside)             SAP S/4HANA: orders, roles and the audit log of who read what

Usage:
  python sap_side.py init     add the lab secrets to .env
  python sap_side.py serve    run the server (Ctrl+C to stop)
  python sap_side.py reset    clear the audit log, the drafts and the platform log
Calder Pumpworks, its people, orders, users, clients and rules are fictional course values.
"""
import argparse
import hmac
import json
import re
import threading
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from common import (AGW_RESOURCE, AUDIT_LOG, BASE, COGNITO_ISSUER, DRAFTS, ENTRA_ISSUER, HOST,
                    IAS_ISSUER, JWT_BEARER, MCP_RESOURCE, PORT, TokenError, append_jsonl, init_env,
                    read_jsonl, reset_logs, secret, sign, verify)

# ---------------------------------------------------------------- SAP Cloud Identity Services (stand-in)
# Users known to Cloud Identity Services, matched by email, and the SAP user each one is.
# Real landscapes resolve this in Cloud Identity Services and the SAP user master; here it's a table.
IAS_USERS = {
    "cs.clerk@calder-pumpworks.example": "00100265",        # customer service clerk
    "inside.sales@calder-pumpworks.example": "00100266",    # inside sales rep
    "credit.analyst@calder-pumpworks.example": "00100304",  # credit analyst
}
TECH_USER = "TU_XPLAT_AGENT"   # what SAP sees when a platform uses client credentials

# The two platform clients registered with Cloud Identity Services, and the identity provider
# each one may bring tokens from (the trust set up between the providers).
CLIENTS = {
    "calder-copilot-connector": {"secret": "CALDER_COPILOT_CLIENT_SECRET", "issuer": ENTRA_ISSUER,
                                 "issuer_key": "CALDER_ENTRA_LAB_KEY", "user_claim": "upn"},
    "calder-agentcore-identity": {"secret": "CALDER_AGENTCORE_CLIENT_SECRET", "issuer": COGNITO_ISSUER,
                                  "issuer_key": "CALDER_COGNITO_LAB_KEY", "user_claim": "email"},
}
TOKEN_MINUTES = 10

# ---------------------------------------------------------------- SAP S/4HANA (stand-in)
# Distribution channels each SAP user's role allows: 10 direct, 20 distributors, 30 spare parts.
SAP_ROLES = {
    "00100265": {"role": "customer service clerk", "channels": ["10", "20", "30"]},
    "00100266": {"role": "inside sales rep", "channels": ["10"]},
    "00100304": {"role": "credit analyst", "channels": ["10", "20", "30"]},
    TECH_USER: {"role": "technical user", "channels": ["10", "20", "30"]},
}
# Calder's open orders from the order-to-cash topic. Problem and Owner are course fields.
ORDERS = {
    "1000002": {"Customer": "10000002", "CustomerName": "Hallam Fluid Systems", "DistributionChannel": "20",
                "TotalNetAmount": "24288.00", "Problem": "credit block", "Owner": "Credit analyst"},
    "1000003": {"Customer": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "TotalNetAmount": "12300.00", "Problem": "billing data incomplete", "Owner": "Sales order team"},
    "1000004": {"Customer": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "TotalNetAmount": "24600.00", "Problem": "partly confirmed", "Owner": "Order fulfillment"},
    "1000005": {"Customer": "10000002", "CustomerName": "Hallam Fluid Systems", "DistributionChannel": "30",
                "TotalNetAmount": "", "Problem": "price missing", "Owner": "Pricing team"},
    "1000006": {"Customer": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "TotalNetAmount": "4200.00", "Problem": "billing block", "Owner": "Billing clerk"},
    "1000007": {"Customer": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "TotalNetAmount": "8400.00", "Problem": "delivery block", "Owner": "Customer service"},
}

# ---------------------------------------------------------------- Agent Gateway (stand-in)
AGENT_ACL = {"order-exc": ["calder-copilot-connector", "calder-agentcore-identity"]}  # consumers allowed
ACCESS_AT_AGENT = {"order-exc": ["00100265", "00100304"]}   # SAP users assigned the agent's access policy
CREDIT_OWNER = "00100304"
DRAFT_LOCK = threading.Lock()   # the server is threaded: check and write a draft as one step

TOOLS = [
    {"name": "list_blocked_orders",
     "description": "List Calder's open sales orders that are stopped, with the problem and the owning team. "
                    "Optional: customer (8 digits). Read only.",
     "inputSchema": {"type": "object", "properties": {"customer": {"type": "string", "pattern": "^[0-9]{8}$"}},
                     "additionalProperties": False}},
    {"name": "get_sales_order",
     "description": "Read one Calder sales order by its 7-digit number, for example 1000002, "
                    "and say what stops it. Read only.",
     "inputSchema": {"type": "object", "properties": {"sales_order": {"type": "string", "pattern": "^[0-9]{7}$"}},
                     "required": ["sales_order"], "additionalProperties": False}},
]


def audit(trace, door, event, **fields):
    """One line per decision on the SAP side. Never a token or a secret."""
    append_jsonl(AUDIT_LOG, {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "trace": trace, "door": door,
                             "event": event, **fields})


# ---------------------------------------------------------------- S/4HANA reads
def s4_read(trace, who, number):
    order = ORDERS.get(number)
    if order is None:
        audit(trace, "s4", "not_found", sap_user=who["sap_user"], user_type=who["user_type"], order=number)
        return False, f"order {number} doesn't exist"
    if order["DistributionChannel"] not in SAP_ROLES[who["sap_user"]]["channels"]:
        audit(trace, "s4", "refused", sap_user=who["sap_user"], user_type=who["user_type"], order=number)
        return False, (f"SAP user {who['sap_user']} may not display orders in channel "
                       f"{order['DistributionChannel']}")
    audit(trace, "s4", "read", sap_user=who["sap_user"], user_type=who["user_type"], order=number)
    return True, {"SalesOrder": number, **order, "read_as_sap_user": who["sap_user"]}


def s4_list(trace, who, customer=None):
    channels = SAP_ROLES[who["sap_user"]]["channels"]
    rows = [{"SalesOrder": n, **o} for n, o in ORDERS.items()
            if o["DistributionChannel"] in channels and (customer is None or o["Customer"] == customer)]
    audit(trace, "s4", "list", sap_user=who["sap_user"], user_type=who["user_type"], rows=len(rows))
    return {"orders": rows, "read_as_sap_user": who["sap_user"]}


# ---------------------------------------------------------------- token endpoint
def token_endpoint(form, trace):
    client_id = form.get("client_id", "")
    client = CLIENTS.get(client_id)
    if client is None or not hmac.compare_digest(form.get("client_secret", ""), secret(client["secret"])):
        audit(trace, "ias", "client_refused", client=client_id)
        return 401, {"error": "invalid_client"}
    resource = form.get("resource", "")
    if resource not in (MCP_RESOURCE, AGW_RESOURCE):
        audit(trace, "ias", "target_refused", client=client_id, resource=resource)
        return 400, {"error": "invalid_target"}
    now = int(time.time())
    grant = form.get("grant_type", "")
    if grant == JWT_BEARER:
        try:
            # The platform token was minted for the platform's own client (aud = client_id).
            incoming = verify(form.get("assertion", ""), secret(client["issuer_key"]), client["issuer"], client_id)
        except TokenError as err:
            audit(trace, "ias", "assertion_refused", client=client_id, reason=str(err))
            return 400, {"error": "invalid_grant", "error_description": f"assertion refused: {err}"}
        email = str(incoming.get(client["user_claim"], "")).lower()
        sap_user = IAS_USERS.get(email)
        if sap_user is None:
            audit(trace, "ias", "user_refused", client=client_id, person=email)
            return 400, {"error": "invalid_grant", "error_description": "User is not authorized for access"}
        claims = {"iss": IAS_ISSUER, "sub": email, "sap_user": sap_user, "sap_id_type": "user",
                  "sap_user_type": "user", "azp": client_id, "aud": resource, "iat": now,
                  "exp": now + TOKEN_MINUTES * 60}
    elif grant == "client_credentials":
        claims = {"iss": IAS_ISSUER, "sub": TECH_USER, "sap_user": TECH_USER, "sap_id_type": "user",
                  "sap_user_type": "techUser", "azp": client_id, "aud": resource, "iat": now,
                  "exp": now + TOKEN_MINUTES * 60}
    else:
        return 400, {"error": "unsupported_grant_type"}
    audit(trace, "ias", "token_issued", client=client_id, sap_user=claims["sap_user"],
          user_type=claims["sap_user_type"], resource=resource)
    return 200, {"access_token": sign(claims, secret("CALDER_IAS_LAB_KEY")), "token_type": "Bearer",
                 "expires_in": TOKEN_MINUTES * 60}


def caller(claims):
    return {"sap_user": claims["sap_user"], "user_type": claims["sap_user_type"], "client": claims["azp"]}


# ---------------------------------------------------------------- MCP gateway
def mcp_endpoint(body, claims, trace):
    rpc_id, method, params = body.get("id"), body.get("method"), body.get("params") or {}
    who = caller(claims)
    if method == "initialize":
        result = {"protocolVersion": "2025-11-25", "capabilities": {"tools": {}},
                  "serverInfo": {"name": "calder-sales-orders", "version": "1.0.0"}}
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "tools/call":
        name, args = params.get("name"), params.get("arguments") or {}
        if name == "get_sales_order" and re.fullmatch(r"[0-9]{7}", str(args.get("sales_order", ""))):
            ok, data = s4_read(trace, who, args["sales_order"])
        elif name == "list_blocked_orders" and re.fullmatch(r"([0-9]{8})?", str(args.get("customer", ""))):
            ok, data = True, s4_list(trace, who, args.get("customer") or None)
        else:
            ok, data = False, f"unknown tool or bad arguments: {name}"
        text = json.dumps(data) if ok else data
        result = {"content": [{"type": "text", "text": text}], "isError": not ok}
    else:
        return {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": -32601, "message": "method not found"}}
    audit(trace, "mcp", method, sap_user=who["sap_user"], user_type=who["user_type"], client=who["client"])
    return {"jsonrpc": "2.0", "id": rpc_id, "result": result}


# ---------------------------------------------------------------- Agent Gateway and the agent
AGENT_CARD = {
    "name": "Calder order exceptions agent (lab stand-in)",
    "description": "Explains a blocked Calder sales order and drafts a credit review request for the credit "
                   "analyst. Never changes an order.",
    "url": f"{BASE}/v1/a2a/order-exc/jsonrpc", "preferredTransport": "JSONRPC", "protocolVersion": "0.3.0",
    "version": "1.0.0", "capabilities": {"streaming": False},
    "defaultInputModes": ["text/plain"], "defaultOutputModes": ["text/plain"],
    "securitySchemes": {"sapBearer": {"type": "http", "scheme": "bearer"}}, "security": [{"sapBearer": []}],
    "skills": [{"id": "credit_review_request", "name": "Credit review request",
                "description": "Given an order number and a reason, drafts a credit review request "
                               "for the credit analyst if the order has a credit block.",
                "tags": ["order-to-cash", "credit"]}],
}


def run_agent(text, who, trace):
    """The SAP agent: reads the order as the user, drafts only for credit blocks. Returns (state, text)."""
    match = re.search(r"\b(\d{7})\b", text)
    if not match:
        return "rejected", "Name a 7-digit sales order number."
    ok, order = s4_read(trace, who, match.group(1))
    if not ok:
        return "rejected", order
    number = order["SalesOrder"]
    if order["Problem"] != "credit block":
        return "completed", (f"Order {number} is stopped by '{order['Problem']}', not a credit block. "
                             f"Its owner is {order['Owner']}. No credit review drafted.")
    draft_id = f"CRR-{number}"
    with DRAFT_LOCK:
        existing = [d for d in read_jsonl(DRAFTS) if d["draft"] == draft_id]
        if existing:
            first = existing[0]
            return "completed", (f"{draft_id} already waits for the credit analyst ({CREDIT_OWNER}), requested "
                                 f"by SAP user {first['requested_by']} at {first['at']}. Nothing new drafted.")
        append_jsonl(DRAFTS, {"draft": draft_id, "order": number, "requested_by": who["sap_user"],
                              "consumer": who["client"], "owner": CREDIT_OWNER, "request": text[:300],
                              "status": "waiting", "at": time.strftime("%Y-%m-%dT%H:%M:%S"), "trace": trace})
    audit(trace, "agent", "draft_created", sap_user=who["sap_user"], user_type=who["user_type"], draft=draft_id)
    return "completed", (f"Drafted {draft_id} for the credit analyst ({CREDIT_OWNER}): {order['CustomerName']}, "
                         f"{order['TotalNetAmount']} USD. The order is unchanged until the analyst decides.")


def a2a_endpoint(body, claims, trace):
    rpc_id = body.get("id")
    who = caller(claims)
    if who["client"] not in AGENT_ACL["order-exc"]:
        audit(trace, "agw", "consumer_refused", **who)
        return 403, {"error": "consumer is not allowed to invoke this agent"}
    if who["sap_user"] not in ACCESS_AT_AGENT["order-exc"]:
        audit(trace, "agw", "user_refused", **who)
        return 403, {"error": "RBAC: access denied"}
    if body.get("method") != "message/send":
        return 200, {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": -32601, "message": "method not found"}}
    message = (body.get("params") or {}).get("message") or {}
    text = " ".join(p.get("text", "") for p in message.get("parts", []) if p.get("kind") == "text")
    audit(trace, "agw", "routed", **who)
    state, answer = run_agent(text, who, trace)
    task = {"kind": "task", "id": f"task-{trace}", "contextId": message.get("contextId") or f"ctx-{trace}",
            "status": {"state": state},
            "artifacts": [{"artifactId": f"art-{trace}", "parts": [{"kind": "text", "text": answer}]}],
            "metadata": {"served_as_sap_user": who["sap_user"]}}
    return 200, {"jsonrpc": "2.0", "id": rpc_id, "result": task}


# ---------------------------------------------------------------- HTTP plumbing
class Handler(BaseHTTPRequestHandler):
    server_version = "CalderSapSide/1.0"

    def log_message(self, *args):   # keep the terminal quiet; the audit log is the record
        pass

    def reply(self, status, payload, extra_headers=None):
        data = json.dumps(payload).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        for key, value in (extra_headers or {}).items():
            self.send_header(key, value)
        self.end_headers()
        self.wfile.write(data)

    def trace(self):
        value = self.headers.get("X-Request-ID", "")
        return value if re.fullmatch(r"[0-9a-f]{12}", value) else "none"

    def bearer(self, resource, door):
        auth = self.headers.get("Authorization", "")
        token = auth[7:] if auth.startswith("Bearer ") else ""
        try:
            return verify(token, secret("CALDER_IAS_LAB_KEY"), IAS_ISSUER, resource)
        except TokenError as err:
            audit(self.trace(), door, "token_refused", reason=str(err))
            self.reply(401, {"error": "invalid_token", "error_description": str(err)},
                       {"WWW-Authenticate": 'Bearer error="invalid_token"'})
            return None

    def body(self):
        length = int(self.headers.get("Content-Length", "0") or 0)
        if length > 64 * 1024:
            raise ValueError("body too large")
        return self.rfile.read(length).decode("utf-8")

    def do_GET(self):
        if self.path == "/health":
            self.reply(200, {"status": "up"})
        elif self.path == "/v1/a2a/order-exc/.well-known/agent-card.json":
            self.reply(200, AGENT_CARD)
        else:
            self.reply(404, {"error": "not found"})

    def do_POST(self):
        trace = self.trace()
        try:
            raw = self.body()
        except ValueError:
            self.reply(413, {"error": "body too large"})
            return
        if self.path == "/oauth2/token":
            form = {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()}
            self.reply(*token_endpoint(form, trace))
            return
        if self.path not in ("/mcp", "/v1/a2a/order-exc/jsonrpc"):
            self.reply(404, {"error": "not found"})
            return
        is_mcp = self.path == "/mcp"
        claims = self.bearer(MCP_RESOURCE if is_mcp else AGW_RESOURCE, "mcp" if is_mcp else "agw")
        if claims is None:
            return
        try:
            body = json.loads(raw)
        except json.JSONDecodeError:
            self.reply(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}})
            return
        if is_mcp:
            self.reply(200, mcp_endpoint(body, claims, trace))
        else:
            self.reply(*a2a_endpoint(body, claims, trace))


def main():
    parser = argparse.ArgumentParser(description="SAP side of the cross-platform agent lab (stand-ins).")
    parser.add_argument("command", choices=["init", "serve", "reset"])
    args = parser.parse_args()
    if args.command == "init":
        init_env()
    elif args.command == "reset":
        reset_logs()
        print("Cleared the audit log, the drafts and the platform log.")
    else:
        for name in ("CALDER_IAS_LAB_KEY", "CALDER_ENTRA_LAB_KEY", "CALDER_COGNITO_LAB_KEY",
                     "CALDER_COPILOT_CLIENT_SECRET", "CALDER_AGENTCORE_CLIENT_SECRET"):
            secret(name)
        server = ThreadingHTTPServer((HOST, PORT), Handler)
        print(f"SAP side (stand-ins) on {BASE}")
        print(f"  token endpoint  {BASE}/oauth2/token")
        print(f"  MCP gateway     {BASE}/mcp")
        print(f"  agent card      {BASE}/v1/a2a/order-exc/.well-known/agent-card.json")
        print("Press Ctrl+C to stop.")
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print("\nStopped.")


if __name__ == "__main__":
    main()
```

#### Step 5: Create the lab secrets

The SAP side and the platforms sign their tokens with secrets. This step writes five random ones into your `.env` file.

```bash
python projects/cross-platform-agent/sap_side.py init
```

You should see:

```text
Added to .env: CALDER_ENTRA_LAB_KEY, CALDER_COGNITO_LAB_KEY, CALDER_IAS_LAB_KEY, CALDER_COPILOT_CLIENT_SECRET, CALDER_AGENTCORE_CLIENT_SECRET
```

Run it again and it says all five are already there; it never overwrites a secret.

> **Warning** Secrets belong in `.env`, never in code or in Git. In the lab one `.env` holds the secrets of three parties (Microsoft, AWS and SAP) because all three run on your computer. In real life each party keeps its own, and identity providers sign with private keys whose public half SAP checks.

#### Step 6: Start the SAP side

1. Open a second terminal (**Terminal > New Terminal**), turn on the environment there too, and start the server:

   ```bash
   python projects/cross-platform-agent/sap_side.py serve
   ```

2. You should see:

   ```text
   SAP side (stand-ins) on http://127.0.0.1:8792
     token endpoint  http://127.0.0.1:8792/oauth2/token
     MCP gateway     http://127.0.0.1:8792/mcp
     agent card      http://127.0.0.1:8792/v1/a2a/order-exc/.well-known/agent-card.json
   Press Ctrl+C to stop.
   ```

3. Leave this terminal running. In a browser, open `http://127.0.0.1:8792/v1/a2a/order-exc/.well-known/agent-card.json`. You see the SAP agent's card: its name, its one skill and that it wants a bearer token.

#### What the code does

| Part | What it does |
| --- | --- |
| `IAS_USERS`, `CLIENTS` | Who Cloud Identity Services knows, and which platform client may bring tokens from which identity provider |
| `token_endpoint()` | Checks the client's secret and the target, verifies the platform token (issuer, signature, audience = the platform's own client, expiry), finds the person and issues a new token for the target with the same person in it. Unknown people get `invalid_grant`. `client_credentials` gives a technical-user token, the shortcut this project measures against |
| `mcp_endpoint()` | Answers `initialize`, `tools/list` and `tools/call` for two read tools, as the SAP user in the token |
| `a2a_endpoint()` | Checks the platform client against the agent's allow-list, then the person against the agent's access policy, then runs `message/send` |
| `run_agent()` | The SAP agent: reads the order as the person, drafts `CRR-<order>` only for a credit block, and never twice (a lock makes the check and the write one step, because the server handles requests in parallel) |
| `s4_read()`, `s4_list()` | The S/4HANA stand-in: checks the SAP user's channels and writes the audit line that the KPI reads |
| `Handler` | The HTTP plumbing: bearer tokens, the `X-Request-ID` header that ties both sides' logs together, a 64 KB body limit |

The MCP part is a small subset of the protocol's JSON-RPC methods, enough to show tools and identity. Real MCP servers also handle sessions, notifications and protocol version negotiation; SAP's gateway supports the MCP specifications of 2025-11-25 and 2026-07-28 as of its October 2026 release notes ([SAP-docs](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/what-s-new-for-sap-api-management-cloud-foundry-d9d60be.md)).

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't on your path, or the environment is off | Turn on `.venv` (Step 1); see [Set up your computer](https://erpfde.com/topics/set-up-your-computer/) |
| `ModuleNotFoundError: No module named 'dotenv'` | The library isn't installed in this environment | `pip install python-dotenv==1.2.4` |
| `Missing CALDER_... in .env` | Step 5 didn't run, or `.env` is in another folder | Run Step 5 from the `orchestrate-course` folder |
| `OSError: [Errno 98] Address already in use` (Windows: `10048`) | Something already uses port 8792, often an earlier run | Stop the other terminal with Ctrl+C, or change `PORT` in `common.py` |
| A corporate proxy or firewall blocks the page | The lab only uses `127.0.0.1`, your own computer | Ask IT to allow local loopback traffic; no internet access is needed |

### Stage 2: Model: routing between tools and agents

A platform agent's model decides, for each question, which tool or agent to call. This project replaces that model with a few fixed rules, so every run gives the same result and needs no model account. The rules carry the design decision that matters: **reads go to MCP tools; a task that ends in a draft goes to the SAP agent over A2A.**

```mermaid
flowchart TD
  Q["Question"] --> R{"Order number and<br/>'credit review' or 'release'?"}
  R -->|yes| A["A2A: SAP order-exceptions agent<br/>drafts or explains"]
  R -->|no| O{"Order number?"}
  O -->|yes| G["MCP tool get_sales_order"]
  O -->|no| L{"'list', 'blocked', 'stuck'?"}
  L -->|yes| T["MCP tool list_blocked_orders"]
  L -->|no| N["No SAP route: say so"]
```

Why not a tool that drafts the credit review? Because the check behind it belongs to SAP: is it really a credit block, is a request already open, who owns it? If each platform implemented that, Calder would have two versions of the rule to keep in step. SAP's reference architecture for Copilot Studio draws the same line: use MCP when the agent calls SAP capabilities as tools, and A2A when it delegates a task to a specialized SAP agent ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/d2e34e)).

> **Note** On a real platform the model picks the route from the tool descriptions and the agent card's skills. SAP's guidance for the gateway asks for precise, action-oriented tool descriptions for that reason. The two descriptions in `TOOLS` and the skill in `AGENT_CARD` are written for a model, even though this lab's router ignores them.

#### What you need

- About 30 minutes. The SAP side from Stage 1 running in the other terminal.

#### Step 1: Save the platform agents

Create `platform_agent.py` in `projects/cross-platform-agent`, paste this code and save.

```python
"""Two platform agents that reach Calder's SAP side: a Copilot Studio stand-in and a Bedrock AgentCore stand-in.

Each one signs the person in with its own identity provider, picks a route for the question
(MCP gateway for reads, A2A to SAP's agent for a credit review request), exchanges the
person's token at SAP Cloud Identity Services for one minted for that route, and calls it.

Usage:
  python platform_agent.py ask --platform copilot --user cs.clerk@calder-pumpworks.example "What is wrong with order 1000002?"
  python platform_agent.py ask ... --auth technical      (the shortcut this project exists to replace)
  python platform_agent.py preflight                       (checks the SAP side before go-live)
The routing rules stand in for the platform's model. Everything is a course value; Calder is fictional.
"""
import argparse
import json
import re
import sys
import time
import urllib.error
import urllib.parse
import uuid

from common import (AGW_RESOURCE, BASE, COGNITO_ISSUER, ENTRA_ISSUER, JWT_BEARER, MCP_RESOURCE,
                    PLATFORM_LOG, append_jsonl, secret, sign)
import urllib.request

PEOPLE = ["cs.clerk@calder-pumpworks.example", "inside.sales@calder-pumpworks.example",
          "credit.analyst@calder-pumpworks.example"]
PLATFORMS = {
    "copilot": {"label": "Copilot Studio agent (stand-in)", "issuer": ENTRA_ISSUER,
                "key": "CALDER_ENTRA_LAB_KEY", "claim": "upn", "client": "calder-copilot-connector",
                "client_secret": "CALDER_COPILOT_CLIENT_SECRET", "accounts": PEOPLE},
    "bedrock": {"label": "Bedrock AgentCore agent (stand-in)", "issuer": COGNITO_ISSUER,
                "key": "CALDER_COGNITO_LAB_KEY", "claim": "email", "client": "calder-agentcore-identity",
                "client_secret": "CALDER_AGENTCORE_CLIENT_SECRET",
                "accounts": PEOPLE + ["visitor@partner.example"]},
}
CUSTOMERS = {"brennock": "10000001", "hallam": "10000002"}
A2A_URL = f"{BASE}/v1/a2a/order-exc/jsonrpc"


class Stop(Exception):
    """A refusal somewhere on the way. where = idp, ias, mcp, agw, sap."""

    def __init__(self, where, detail):
        super().__init__(detail)
        self.where, self.detail = where, detail


# ---------------------------------------------------------------- HTTP
def post(url, trace, data, token=None, form=False):
    body = urllib.parse.urlencode(data).encode() if form else json.dumps(data).encode()
    headers = {"Content-Type": "application/x-www-form-urlencoded" if form else "application/json",
               "X-Request-ID": trace}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    request = urllib.request.Request(url, data=body, headers=headers, method="POST")
    try:
        with urllib.request.urlopen(request, timeout=10) as response:
            return response.status, json.loads(response.read())
    except urllib.error.HTTPError as err:
        try:
            return err.code, json.loads(err.read())
        except json.JSONDecodeError:
            return err.code, {"error": f"HTTP {err.code}"}
    except urllib.error.URLError as err:
        sys.exit(f"Can't reach the SAP side at {BASE} ({err.reason}). Start it: python sap_side.py serve")


# ---------------------------------------------------------------- identity
def sign_in(platform, person):
    """The platform's identity provider signs the person in. The token is for the platform's own client."""
    p = PLATFORMS[platform]
    if person not in p["accounts"]:
        raise Stop("idp", f"{person} has no account in the {platform} identity provider")
    now = int(time.time())
    claims = {"iss": p["issuer"], "sub": "lab-" + person.split("@")[0], p["claim"]: person,
              "aud": p["client"], "iat": now, "exp": now + 600}
    return sign(claims, secret(p["key"]))


def sap_token(platform, trace, resource, user_token=None):
    """Exchange at SAP Cloud Identity Services. With no user token: client credentials (technical user)."""
    p = PLATFORMS[platform]
    form = {"client_id": p["client"], "client_secret": secret(p["client_secret"]), "resource": resource}
    if user_token:
        form.update({"grant_type": JWT_BEARER, "assertion": user_token})
    else:
        form["grant_type"] = "client_credentials"
    status, payload = post(f"{BASE}/oauth2/token", trace, form, form=True)
    if status != 200:
        raise Stop("ias", f"{payload.get('error')}: {payload.get('error_description', '')}".rstrip(": "))
    return payload["access_token"]


# ---------------------------------------------------------------- routing (stands in for the model)
def route(question):
    """Return (route, argument). Reads go to MCP tools; a credit review request goes to SAP's agent."""
    q = question.lower()
    order = re.search(r"\b(\d{7})\b", q)
    if order and re.search(r"\b(credit review|review the credit|ask credit|release)\b", q):
        return "a2a_credit_review", order.group(1)
    if order:
        return "mcp_get_sales_order", order.group(1)
    if re.search(r"\b(list|which|blocked|stuck)\b", q):
        customer = next((num for name, num in CUSTOMERS.items() if name in q), None)
        return "mcp_list_blocked_orders", customer
    return "none", None


def call_tool(token, trace, name, arguments):
    status, payload = post(f"{BASE}/mcp", trace, {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
                                                  "params": {"name": name, "arguments": arguments}}, token)
    if status != 200:
        raise Stop("mcp", payload.get("error_description") or payload.get("error", f"HTTP {status}"))
    result = payload["result"]
    text = result["content"][0]["text"]
    if result.get("isError"):
        raise Stop("sap", text)
    return json.loads(text)


def send_task(token, trace, text):
    message = {"kind": "message", "role": "user", "messageId": f"msg-{trace}",
               "parts": [{"kind": "text", "text": text}]}
    status, payload = post(A2A_URL, trace, {"jsonrpc": "2.0", "id": 1, "method": "message/send",
                                            "params": {"message": message}}, token)
    if status != 200:
        raise Stop("agw", payload.get("error_description") or payload.get("error", f"HTTP {status}"))
    task = payload["result"]
    answer = task["artifacts"][0]["parts"][0]["text"]
    if task["status"]["state"] != "completed":
        raise Stop("sap", answer)
    return answer, task["metadata"]["served_as_sap_user"]


# ---------------------------------------------------------------- one request
def ask(platform, person, question, auth="user", fault=None):
    trace = uuid.uuid4().hex[:12]
    kind, arg = route(question)
    record = {"request": trace, "at": time.strftime("%Y-%m-%dT%H:%M:%S"), "platform": platform,
              "person": person, "question": question, "route": kind, "auth": auth}
    try:
        if kind == "none":
            raise Stop("platform", "no SAP route for this question")
        user_token = sign_in(platform, person)
        resource = AGW_RESOURCE if kind.startswith("a2a") else MCP_RESOURCE
        if fault == "reuse-token":          # a token minted for the MCP gateway, sent to the agent gateway
            resource = MCP_RESOURCE
        token = sap_token(platform, trace, resource, user_token if auth == "user" else None)
        if kind == "mcp_get_sales_order":
            order = call_tool(token, trace, "get_sales_order", {"sales_order": arg})
            served = order["read_as_sap_user"]
            answer = (f"Order {arg} ({order['CustomerName']}, channel {order['DistributionChannel']}) is stopped "
                      f"by: {order['Problem']}. Owner: {order['Owner']}.")
        elif kind == "mcp_list_blocked_orders":
            data = call_tool(token, trace, "list_blocked_orders", {"customer": arg} if arg else {})
            served = data["read_as_sap_user"]
            rows = data["orders"]
            answer = f"{len(rows)} blocked orders: " + ", ".join(f"{r['SalesOrder']} {r['Problem']}" for r in rows)
        else:
            answer, served = send_task(token, trace, question)
        record.update(outcome="answered", served_as=served, answer=answer)
    except Stop as stop:
        outcome = {"sap": "refused_by_sap", "platform": "no_route"}.get(stop.where, "refused_at_door")
        record.update(outcome=outcome,
                      where=stop.where, served_as=None, answer=stop.detail)
    append_jsonl(PLATFORM_LOG, record)
    return record


def preflight():
    """What an operator checks before go-live: up, card readable, no token no entry, tools listed."""
    checks = []
    try:
        with urllib.request.urlopen(f"{BASE}/health", timeout=5) as r:
            checks.append(("SAP side reachable", r.status == 200))
    except urllib.error.URLError:
        sys.exit(f"Can't reach {BASE}. Start it: python sap_side.py serve")
    with urllib.request.urlopen(f"{BASE}/v1/a2a/order-exc/.well-known/agent-card.json", timeout=5) as r:
        card = json.loads(r.read())
    checks.append(("Agent card names skill credit_review_request",
                   any(s["id"] == "credit_review_request" for s in card["skills"])))
    status, _ = post(f"{BASE}/mcp", "000000000000", {"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
    checks.append(("MCP gateway refuses a call without a token", status == 401))
    status, _ = post(A2A_URL, "000000000000", {"jsonrpc": "2.0", "id": 1, "method": "message/send"})
    checks.append(("Agent gateway refuses a call without a token", status == 401))
    for platform in PLATFORMS:
        token = sap_token(platform, "000000000000", MCP_RESOURCE, sign_in(platform, PEOPLE[0]))
        status, payload = post(f"{BASE}/mcp", "000000000000",
                               {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, token)
        names = sorted(t["name"] for t in payload.get("result", {}).get("tools", []))
        checks.append((f"{platform}: exchange works and lists {', '.join(names)}", len(names) == 2))
    for label, ok in checks:
        print(f"{'OK  ' if ok else 'FAIL'}  {label}")
    return all(ok for _, ok in checks)


def main():
    parser = argparse.ArgumentParser(description="Platform agents for the cross-platform agent lab.")
    sub = parser.add_subparsers(dest="command", required=True)
    a = sub.add_parser("ask", help="ask one question as one person on one platform")
    a.add_argument("question")
    a.add_argument("--platform", choices=sorted(PLATFORMS), required=True)
    a.add_argument("--user", required=True, help="the person's sign-in name, for example cs.clerk@calder-pumpworks.example")
    a.add_argument("--auth", choices=["user", "technical"], default="user")
    a.add_argument("--fault", choices=["reuse-token"], default=None)
    sub.add_parser("preflight", help="check the SAP side before go-live")
    args = parser.parse_args()
    if args.command == "preflight":
        sys.exit(0 if preflight() else 1)
    record = ask(args.platform, args.user.lower(), args.question, args.auth, args.fault)
    print(f"{PLATFORMS[args.platform]['label']} for {args.user}")
    print(f"  route:     {record['route']}")
    door = record.get("where") if record["outcome"] == "refused_at_door" else None
    print(f"  outcome:   {record['outcome']}" + (f" (at {door})" if door else ""))
    print(f"  SAP user:  {record['served_as'] or '-'}")
    print(f"  answer:    {record['answer']}")
    print(f"  request:   {record['request']}")


if __name__ == "__main__":
    main()
```

#### Step 2: Try the router on three questions

1. In your first terminal, run:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user cs.clerk@calder-pumpworks.example "What is wrong with order 1000002?"
   ```

   You should see (your request ID differs):

   ```text
   Copilot Studio agent (stand-in) for cs.clerk@calder-pumpworks.example
     route:     mcp_get_sales_order
     outcome:   answered
     SAP user:  00100265
     answer:    Order 1000002 (Hallam Fluid Systems, channel 20) is stopped by: credit block. Owner: Credit analyst.
     request:   2d984d44c0a3
   ```

2. Ask for a credit review:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user cs.clerk@calder-pumpworks.example "Ask credit to review order 1000002 because Hallam paid its overdue invoice"
   ```

   The route is `a2a_credit_review`, and the answer starts `Drafted CRR-1000002 for the credit analyst (00100304)`.

3. Ask something with no SAP route:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user cs.clerk@calder-pumpworks.example "Can you help me?"
   ```

   The outcome is `no_route`. Saying so is better than guessing.

4. Try "Release the credit block on order 1000002 now". The router sends it to the SAP agent, which has no way to release anything: it answers that `CRR-1000002` already waits for the analyst.

#### What the code does

| Part | What it does |
| --- | --- |
| `PLATFORMS` | Each platform's identity provider, the claim that carries the person (`upn` for Entra, `email` for Cognito) and its client at Cloud Identity Services |
| `sign_in()` | Stands in for the platform's sign-in: a token whose audience is the platform's own client, as a platform token would be |
| `route()` | The fixed rules above, standing in for the model |
| `sap_token()` | The exchange at Cloud Identity Services: `jwt-bearer` with the person's token, or `client_credentials` with `--auth technical` |
| `call_tool()`, `send_task()` | One MCP `tools/call`, or one A2A `message/send`, with the exchanged token as bearer |
| `ask()` | One request end to end, logged to `platform_log.jsonl` with its request ID |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `Can't reach the SAP side at http://127.0.0.1:8792` | The server isn't running | Start it in the second terminal (Stage 1, Step 6) |
| `ModuleNotFoundError: No module named 'common'` | The file isn't in the same folder as `common.py` | Save all files in `projects/cross-platform-agent` |
| `invalid_client` in the answer | The client secret in `.env` changed after the server started | Restart the server with Ctrl+C and `serve` |
| PowerShell splits the question | Quotes were lost in copying | Put the whole question in straight double quotes |

### Stage 3: API: one exchange per hop

This stage looks at the calls themselves. The key fact comes from SAP's token exchange architecture: a platform's own token names the platform as its audience, so SAP's gateway rejects it. Before each call, the platform exchanges it at SAP Cloud Identity Services for a token whose audience is the gateway, while the subject stays the same ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/f4a2c8)).

```mermaid
sequenceDiagram
  participant P as Person
  participant A as Platform agent
  participant I as Cloud Identity Services
  participant G as MCP gateway or Agent Gateway
  participant S as S/4HANA
  P->>A: question
  A->>A: sign in: token with aud = platform client
  A->>I: jwt-bearer exchange, resource = the gateway
  I-->>A: new token: same person, aud = the gateway
  A->>G: tools/call or message/send, Bearer token
  G->>S: read as the person's SAP user
  S-->>G: data or refusal, audit line
  G-->>A: result
  A-->>P: answer
```

| Hop | Copilot Studio (stand-in) | Bedrock AgentCore (stand-in) |
| --- | --- | --- |
| Sign-in | Entra ID, person in `upn` | Cognito, person in `email` |
| Exchange client | `calder-copilot-connector` | `calder-agentcore-identity` |
| Real-world piece that exchanges | A Power Platform custom connector, for the A2A route | AgentCore Identity, on behalf of the user |
| What SAP receives | A Cloud Identity Services token for the gateway, `sub` = the person | The same |

On AWS, SAP's reference architecture names three tokens: Cognito's access token, a workload access token that AgentCore Runtime mints, and the Cloud Identity Services token that AgentCore Identity gets on the user's behalf, proving itself with a signed assertion whose key stays in AWS KMS ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/b4d7e2)). The lab folds the middle token into one step and uses a client secret instead of a signed assertion; the shape of the exchange is the same.

#### What you need

- About 30 minutes. The SAP side running.

#### Step 1: Read one request on both sides

1. Copy the request ID from your credit review in Stage 2.
2. Run:

   ```bash
   python projects/cross-platform-agent/evaluate.py trace 66744fdb0361
   ```

   Use your own ID. `evaluate.py` comes in Stage 6; if you haven't saved it yet, open `projects/cross-platform-agent/sap_audit.jsonl` in VS Code and search for the ID instead.

3. You should see four SAP-side records under one ID:

   ```text
   platform  copilot, cs.clerk@calder-pumpworks.example, route a2a_credit_review, answered
   ias       token_issued       client=calder-copilot-connector, sap_user=00100265, user_type=user, resource=urn:sap:identity:application:provider:name:agent-gateway
   agw       routed             sap_user=00100265, user_type=user, client=calder-copilot-connector
   s4        read               sap_user=00100265, user_type=user, order=1000002
   agent     draft_created      sap_user=00100265, user_type=user, draft=CRR-1000002
   ```

   The same person appears at every hop. That is principal propagation, and it is what the KPI checks.

#### Step 2: Send a token to the wrong door

1. Run:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user cs.clerk@calder-pumpworks.example "Ask credit to review order 1000002 because Hallam paid" --fault reuse-token
   ```

2. The outcome is `refused_at_door (at agw)` with `wrong audience (token is for urn:calder:lab:mcp-gateway)`. A token minted for the MCP gateway doesn't open the Agent Gateway.

#### Step 3: Ask as someone the SAP agent doesn't serve

1. Run:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user inside.sales@calder-pumpworks.example "Ask credit to review order 1000003 because Brennock called"
   ```

2. The outcome is `refused_at_door (at agw)` with `RBAC: access denied`. The rep has a valid identity and may read order `1000003`, but he isn't assigned to the SAP agent's access policy. SAP's Microsoft cookbook shows the same answer for a user outside the agent's group ([SAP-samples](https://github.com/SAP-samples/agent-interoperability/tree/main/03-microsoft-azure-integration)).

#### Step 4: Take the shortcut, once

1. Run the rep's distributor question with a technical user:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user inside.sales@calder-pumpworks.example "What is wrong with order 1000002?" --auth technical
   ```

2. It answers, with `SAP user: TU_XPLAT_AGENT`. Run it without `--auth technical` and SAP refuses: `SAP user 00100266 may not display orders in channel 20`. Same person, same question, different identity at SAP.

#### What the code does

The exchange in `sap_side.py` mirrors the request SAP documents: the `urn:ietf:params:oauth:grant-type:jwt-bearer` grant, the incoming token as `assertion`, and a `resource` naming the target. The agent gateway resource `urn:sap:identity:application:provider:name:agent-gateway` is the value SAP's cookbook gives; `urn:calder:lab:mcp-gateway` is a course label. The issued token keeps `sub`, `sap_id_type` and `sap_user_type` as SAP's architecture describes; `sap_user` is a course claim that stands in for the mapping SAP does from the person to their SAP user.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `trace` prints only the `platform` line | The request never reached SAP, or the log was cleared | Check the outcome: refusals at `ias` or `idp` stop before SAP |
| `wrong audience` on a normal request | A token was cached or reused across routes | The lab exchanges per request; check you didn't add `--fault` |
| `expired` | More than 10 minutes passed between exchange and call | Ask again; tokens in the lab live 10 minutes |

### Stage 4: UI: ask from either platform

The simplest UI is the command line, one question per command. On a real platform the person types the same question in Teams or Quick. What you test here is that **the same person gets the same answer and the same SAP identity on both platforms.**

#### What you need

- About 20 minutes. The SAP side running.

#### Step 1: The same question on both platforms

1. On the Bedrock stand-in:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform bedrock --user cs.clerk@calder-pumpworks.example "What is wrong with order 1000005?"
   ```

   The answer: `Order 1000005 (Hallam Fluid Systems, channel 30) is stopped by: price missing. Owner: Pricing team.` with `SAP user: 00100265`.

2. Run the same command with `--platform copilot`. Same answer, same SAP user.

#### Step 2: The same person, two roles

1. Ask as the rep on both platforms:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform bedrock --user inside.sales@calder-pumpworks.example "What is wrong with order 1000005?"
   ```

2. Both platforms give `refused_by_sap` with `SAP user 00100266 may not display orders in channel 30`.

3. List Brennock's blocked orders as the rep:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform copilot --user inside.sales@calder-pumpworks.example "List Brennock's blocked orders"
   ```

   You should see `4 blocked orders: 1000003 billing data incomplete, 1000004 partly confirmed, 1000006 billing block, 1000007 delivery block`. As the clerk, without a customer name, you see all six.

#### Step 3: One request from two platforms

1. Request the credit review from the Bedrock stand-in:

   ```bash
   python projects/cross-platform-agent/platform_agent.py ask --platform bedrock --user cs.clerk@calder-pumpworks.example "Ask credit to review order 1000002 because the dispute is settled"
   ```

2. If you ran Stage 2, the answer is `CRR-1000002 already waits for the credit analyst (00100304), requested by SAP user 00100265 at ...`. The SAP agent keeps one request per order, whichever platform asks.

3. Open `projects/cross-platform-agent/sap_drafts.jsonl`. One line, with the platform client that asked first in `consumer`.

#### Step 4: Someone with no Calder identity

```bash
python projects/cross-platform-agent/platform_agent.py ask --platform bedrock --user visitor@partner.example "What is wrong with order 1000002?"
```

The outcome is `refused_at_door (at ias)` with `invalid_grant: User is not authorized for access`, the error SAP's cookbook lists for a user that isn't provisioned. The visitor has an account in the Cognito stand-in, but not in Calder's identity service.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `has no account in the copilot identity provider` | The visitor only exists on the Bedrock side in this lab | Use `--platform bedrock` for the visitor |
| A draft appears twice | You ran `reset` between the two requests | `reset` clears drafts; run Step 3 without resetting |
| Different answers on the two platforms | One of the files differs from the listing | Compare your `PLATFORMS` with the code in Stage 2 |

### Stage 5: Deployment

Locally, deployment is two processes and a preflight check. For real, it is configuration on three platforms. The local part runs now; the platform parts are a **sketch** because each needs paid or trial access.

#### What you need

- About 15 minutes for the local part.
- For the sketch: an SAP BTP subaccount with SAP Integration Suite and the MCP Gateway capability, access to SAP for Me and Cloud Identity Services administration, a Copilot Studio environment, and an AWS account with Bedrock AgentCore. [Set up for Unit 15](https://erpfde.com/topics/set-up-for-unit-15/) covers the free tiers and trials on the platform side.

#### Step 1: Run the preflight

```bash
python projects/cross-platform-agent/platform_agent.py preflight
```

You should see:

```text
OK    SAP side reachable
OK    Agent card names skill credit_review_request
OK    MCP gateway refuses a call without a token
OK    Agent gateway refuses a call without a token
OK    copilot: exchange works and lists get_sales_order, list_blocked_orders
OK    bedrock: exchange works and lists get_sales_order, list_blocked_orders
```

The two "refuses without a token" lines matter as much as the others. A gateway that answers without a token is open to anyone on the network.

#### Step 2: The SAP side for real (sketch)

> **Note** This step needs SAP BTP, SAP Integration Suite with the MCP Gateway capability, SAP Cloud Identity Services and SAP for Me with the cloud administrator role. The MCP server feature depends on your Integration Suite service plan (SAP Note 2903776). Unit 4's setup topic and the MCP gateway hands-on topic cover the Integration Suite side. Don't run these steps on a customer system without its owners.

1. **Trust.** In SAP Cloud Identity Services, federate Microsoft Entra ID over OIDC as a corporate identity provider, as SAP's Copilot Studio architecture describes. Do the same for the identity provider behind Quick; SAP's AWS cookbook uses Cognito and says any OIDC provider works.
2. **Users.** Provision every agent user in Cloud Identity Services, matched by email to the SAP user. A missing user fails at the exchange.
3. **MCP gateway.** Create an MCP server from the released sales order API in Integration Suite, keep two read tools and write their descriptions for a model. Secure it with Cloud Identity Services as the identity provider. SAP's documentation notes that with Entra ID configured directly on the MCP server, user propagation through the authorization code flow isn't directly supported ([SAP-docs](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/configure-mcp-server-access-using-an-external-identity-provider-fbea412.md)), which is one more reason to federate Entra into Cloud Identity Services.
4. **Agent Gateway consumers.** In SAP for Me, create one system of type *Agent Gateway Consumer* per platform, then assign each to three formations in this order: integration with Cloud Identity Services, integration with the Agent Gateway, and integration with the Agent Gateway consumer, which holds the list of SAP agents it may call. SAP's cookbook warns that out-of-order formations can sit in `CONFIG_PENDING` or `ERROR` for up to sixty minutes ([SAP-samples](https://github.com/SAP-samples/agent-interoperability)).
5. **Access policy.** Assign the clerk and the credit analyst, not the rep, to the SAP agent's access group.

Status, as read on 25 November 2026: SAP's Architecture Center announced general availability of inbound A2A through the Agent Gateway in October 2026 ([SAP Architecture Center news](https://architecture.learning.sap.com/news/2026/10/27/a2a-agent-gateway-interoperability)). The reference architectures for Copilot Studio and AWS, updated a few days earlier, still carry a note that the Agent Gateway is not yet GA, and the token exchange page says some capabilities are still in preparation. Confirm the status for your tenant and region with SAP before you plan a date.

#### Step 3: The Copilot Studio side (sketch)

> **Note** This step needs a Copilot Studio environment where custom connectors are allowed, and the SAP side from Step 2. [Microsoft Copilot Studio and Azure with SAP](https://erpfde.com/topics/microsoft-copilot-studio-and-azure-with-sap/) walks through adding an MCP server in Copilot Studio.

1. **Reads.** Add the MCP gateway's endpoint to the Copilot Studio agent as an MCP tool with OAuth 2.0. SAP's architecture uses the authorization code flow, so each user signs in on first use and gets a user-delegated token, and it requires the Streamable HTTP transport.
2. **Credit review.** Add the SAP agent as a tool through a Power Platform custom connector that does the token exchange. SAP's cookbook recommends its Approach B: the connector signs the user in at Cloud Identity Services and does one exchange with the `agent-gateway` resource. Copilot Studio's native agent-to-agent connection can't do that exchange, so it reaches the Agent Gateway only through a middleware that does.
3. **Test** in the Copilot Studio test chat as the clerk and as the rep, and compare SAP's logs with Stage 4.

#### Step 4: The Bedrock AgentCore side (sketch)

> **Note** This step needs an AWS account with Amazon Bedrock AgentCore and a Cognito user pool, and the SAP side from Step 2. SAP's AWS cookbook has the full setup, including a deploy script.

1. **Sign-in.** A Cognito user pool, with a pre-token-generation Lambda that adds `email` to the access token, because SAP resolves the user by it.
2. **Runtime.** An AgentCore Runtime with a JWT authorizer for Cognito tokens, hosting the agent and its routing.
3. **Identity.** An AgentCore Identity credential provider set up with Cloud Identity Services' endpoints, the Agent Gateway resource and a signing key in AWS KMS. It performs the on-behalf-of exchange, so the runtime never holds a secret.
4. **Reads.** Point the agent's MCP client at the MCP gateway with a token exchanged for it. SAP's Copilot Studio architecture says tools on the gateway are usable by any MCP-compliant agent, naming Bedrock among them.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `FAIL  MCP gateway refuses a call without a token` | Someone changed `bearer()` to let calls through | Restore `sap_side.py` from the listing |
| `invalid_grant` at the real exchange | The user isn't provisioned in Cloud Identity Services | Add the user with the same email (Step 2.2) |
| `403 RBAC: access denied` on the real gateway | The user isn't in the SAP agent's access group | Assign the group, or accept the refusal if it's right |
| Formation stuck in `CONFIG_PENDING` | Formations created out of order | Wait for the retry window, then recreate them in order |

### Stage 6: Evaluation

The test set holds twelve questions, six per platform: reads that should pass, reads SAP should refuse, a credit review that drafts, one that finds the existing draft, one that isn't a credit block, a reused token, a user outside the agent's access policy, and a visitor with no Calder identity. Four gates decide the release.

#### What you need

- About 30 minutes. The SAP side running.

#### Step 1: Save the evaluation script

Create `evaluate.py` in `projects/cross-platform-agent`, paste this code and save.

```python
"""Evaluate the cross-platform agent and compute its KPI from the two logs.

Usage:
  python evaluate.py run                    clear the logs, run the 12 test cases, check the release gates
  python evaluate.py run --auth technical   the same cases with a shared technical user (gates fail)
  python evaluate.py kpi                    the KPI from platform_log.jsonl and sap_audit.jsonl as they are
  python evaluate.py trace <request>        every SAP-side record of one request
Cases, gates and the KPI rule are course values. Calder Pumpworks is fictional.
"""
import argparse
import sys

from common import AUDIT_LOG, DRAFTS, PLATFORM_LOG, read_jsonl, reset_logs
from platform_agent import ask
from sap_side import IAS_USERS

CLERK = "cs.clerk@calder-pumpworks.example"
REP = "inside.sales@calder-pumpworks.example"
VISITOR = "visitor@partner.example"

# id, platform, person, question, fault, expected outcome, expected SAP user, text the answer must hold
CASES = [
    ("T01", "copilot", CLERK, "What is wrong with order 1000002?", None, "answered", "00100265", "credit block"),
    ("T02", "copilot", REP, "What is wrong with order 1000002?", None, "refused_by_sap", "00100266", "channel 20"),
    ("T03", "copilot", REP, "List Brennock's blocked orders", None, "answered", "00100266", "4 blocked orders"),
    ("T04", "copilot", CLERK, "Ask credit to review order 1000002 because Hallam paid its overdue invoice",
     None, "answered", "00100265", "Drafted CRR-1000002"),
    ("T05", "copilot", REP, "Ask credit to review order 1000003 because Brennock called",
     None, "refused_at_door", None, "RBAC: access denied"),
    ("T06", "copilot", CLERK, "Ask credit to review order 1000002 because Hallam paid",
     "reuse-token", "refused_at_door", None, "wrong audience"),
    ("T07", "bedrock", CLERK, "What is wrong with order 1000005?", None, "answered", "00100265", "price missing"),
    ("T08", "bedrock", REP, "What is wrong with order 1000005?", None, "refused_by_sap", "00100266", "channel 30"),
    ("T09", "bedrock", CLERK, "List the blocked orders", None, "answered", "00100265", "6 blocked orders"),
    ("T10", "bedrock", CLERK, "Ask credit to review order 1000002 because the dispute is settled",
     None, "answered", "00100265", "already waits"),
    ("T11", "bedrock", CLERK, "Ask credit to review order 1000006 because Brennock accepted the work",
     None, "answered", "00100265", "not a credit block"),
    ("T12", "bedrock", VISITOR, "What is wrong with order 1000002?", None, "refused_at_door", None,
     "User is not authorized"),
]


def kpi(quiet=False):
    """Requests that reached SAP, and how many SAP served as the asking person's own SAP user."""
    requests = read_jsonl(PLATFORM_LOG)
    audit = read_jsonl(AUDIT_LOG)
    by_trace = {}
    for event in audit:
        if event["door"] in ("s4", "agent"):          # records made where the data lives
            by_trace.setdefault(event["trace"], []).append(event)
    table, totals = {}, {"requests": 0, "reached": 0, "propagated": 0}
    for req in requests:
        row = table.setdefault(req["platform"], {"requests": 0, "reached": 0, "propagated": 0})
        records = by_trace.get(req["request"], [])
        own = IAS_USERS.get(req["person"])
        reached = bool(records)
        propagated = reached and all(r["sap_user"] == own and r["user_type"] == "user" for r in records)
        for bucket in (row, totals):
            bucket["requests"] += 1
            bucket["reached"] += reached
            bucket["propagated"] += propagated
    tech_calls = sum(1 for e in audit if e["door"] in ("s4", "agent") and e.get("user_type") != "user")
    changes = sum(1 for e in audit if e["door"] == "s4" and e["event"] not in ("read", "list", "refused", "not_found"))
    if not quiet:
        print("KPI: requests that reached SAP, served as the asking person's own SAP user")
        print(f"{'platform':10} {'requests':>9} {'reached SAP':>12} {'identity kept':>14} {'share':>7}")
        for platform, row in sorted(table.items()) + [("all", totals)]:
            share = f"{100 * row['propagated'] / row['reached']:.0f}%" if row["reached"] else "-"
            print(f"{platform:10} {row['requests']:>9} {row['reached']:>12} {row['propagated']:>14} {share:>7}")
        print(f"Guardrails: SAP records under a technical user: {tech_calls} (target 0); "
              f"changes to orders: {changes} (target 0); "
              f"credit review drafts waiting for a person: {len(read_jsonl(DRAFTS))}")
    return totals, tech_calls, changes


def trace(request):
    """Join one platform request to the SAP side's records through its request ID."""
    for req in read_jsonl(PLATFORM_LOG):
        if req["request"] == request:
            print(f"platform  {req['platform']}, {req['person']}, route {req['route']}, {req['outcome']}")
    for e in read_jsonl(AUDIT_LOG):
        if e["trace"] == request:
            extra = {k: v for k, v in e.items() if k not in ("at", "trace", "door", "event")}
            print(f"{e['door']:9} {e['event']:18} " + ", ".join(f"{k}={v}" for k, v in extra.items()))


def run(auth):
    reset_logs()
    right = 0
    print(f"{'id':4} {'platform':8} {'person':38} {'expected':16} {'got':16} {'SAP user':14} result")
    for cid, platform, person, question, fault, outcome, sap_user, text in CASES:
        rec = ask(platform, person, question, auth=auth, fault=fault)
        seen = {e["sap_user"] for e in read_jsonl(AUDIT_LOG)
                if e["trace"] == rec["request"] and e["door"] in ("s4", "agent")}
        ok = (rec["outcome"] == outcome and text.lower() in rec["answer"].lower()
              and (seen == {sap_user} if sap_user else not seen))
        right += ok
        shown = ",".join(sorted(seen)) or "-"
        print(f"{cid:4} {platform:8} {person:38} {outcome:16} {rec['outcome']:16} {shown:14} "
              f"{'PASS' if ok else 'FAIL'}")
        if not ok:
            print(f"     answer: {rec['answer']}")
    print()
    totals, tech_calls, changes = kpi()
    gates = [
        ("G1 every case behaves as expected", right == len(CASES), f"{right} of {len(CASES)}"),
        ("G2 identity kept on every request that reached SAP",
         totals["reached"] > 0 and totals["propagated"] == totals["reached"],
         f"{totals['propagated']} of {totals['reached']}"),
        ("G3 no SAP record under a technical user", tech_calls == 0, str(tech_calls)),
        ("G4 no order changed by an agent", changes == 0, str(changes)),
    ]
    print()
    for label, ok, value in gates:
        print(f"{'PASS' if ok else 'FAIL'}  {label}: {value}")
    verdict = all(ok for _, ok, _ in gates)
    print("Release:", "READY" if verdict else "NOT READY")
    return verdict


def main():
    parser = argparse.ArgumentParser(description="Evaluation and KPI for the cross-platform agent lab.")
    parser.add_argument("command", choices=["run", "kpi", "trace"])
    parser.add_argument("request", nargs="?", help="a request ID, for trace")
    parser.add_argument("--auth", choices=["user", "technical"], default="user")
    args = parser.parse_args()
    if args.command == "kpi":
        kpi()
    elif args.command == "trace":
        if not args.request:
            sys.exit("Name a request ID, for example: python evaluate.py trace 2d984d44c0a3")
        trace(args.request)
    else:
        sys.exit(0 if run(args.auth) else 1)


if __name__ == "__main__":
    main()
```

#### Step 2: Run the test set

```bash
python projects/cross-platform-agent/evaluate.py run
```

It clears the three logs, asks the twelve questions and checks the gates. You should see:

```text
id   platform person                                 expected         got              SAP user       result
T01  copilot  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T02  copilot  inside.sales@calder-pumpworks.example  refused_by_sap   refused_by_sap   00100266       PASS
T03  copilot  inside.sales@calder-pumpworks.example  answered         answered         00100266       PASS
T04  copilot  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T05  copilot  inside.sales@calder-pumpworks.example  refused_at_door  refused_at_door  -              PASS
T06  copilot  cs.clerk@calder-pumpworks.example      refused_at_door  refused_at_door  -              PASS
T07  bedrock  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T08  bedrock  inside.sales@calder-pumpworks.example  refused_by_sap   refused_by_sap   00100266       PASS
T09  bedrock  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T10  bedrock  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T11  bedrock  cs.clerk@calder-pumpworks.example      answered         answered         00100265       PASS
T12  bedrock  visitor@partner.example                refused_at_door  refused_at_door  -              PASS

KPI: requests that reached SAP, served as the asking person's own SAP user
platform    requests  reached SAP  identity kept   share
bedrock            6            5              5    100%
copilot            6            4              4    100%
all               12            9              9    100%
Guardrails: SAP records under a technical user: 0 (target 0); changes to orders: 0 (target 0); credit review drafts waiting for a person: 1

PASS  G1 every case behaves as expected: 12 of 12
PASS  G2 identity kept on every request that reached SAP: 9 of 9
PASS  G3 no SAP record under a technical user: 0
PASS  G4 no order changed by an agent: 0
Release: READY
```

> **Note** This KPI table and the gate results come from twelve test questions on synthetic data and local stand-ins. They show the method, not a result from a real SAP system.

The run is deterministic: no model and no randomness, so your table matches line for line.

#### Step 3: Make the gates fail

```bash
python projects/cross-platform-agent/evaluate.py run --auth technical
```

Every platform call now uses client credentials, so SAP sees `TU_XPLAT_AGENT`. The end of the output:

```text
KPI: requests that reached SAP, served as the asking person's own SAP user
platform    requests  reached SAP  identity kept   share
bedrock            6            4              0      0%
copilot            6            3              0      0%
all               12            7              0      0%
Guardrails: SAP records under a technical user: 7 (target 0); changes to orders: 0 (target 0); credit review drafts waiting for a person: 0

FAIL  G1 every case behaves as expected: 2 of 12
FAIL  G2 identity kept on every request that reached SAP: 0 of 7
FAIL  G3 no SAP record under a technical user: 7
PASS  G4 no order changed by an agent: 0
Release: NOT READY
```

Read three rows. `T02` and `T08`: the rep reads distributor and spare-parts orders his role forbids. `T12`: the visitor with no Calder identity gets an answer. `T04`, `T10` and `T11`: the technical user isn't assigned to the SAP agent, so even the clerk loses the credit review. The shortcut is both less safe and less useful.

#### What the gates mean

| Gate | What it protects | Fails when |
| --- | --- | --- |
| `G1` | Behavior: answers, refusals and drafts as designed | Any case differs in outcome, SAP user or answer text |
| `G2` | Identity: every request that reached SAP named the asking person | Any SAP record under another user |
| `G3` | No hidden path: no technical user anywhere | Any SAP record with `user_type` other than `user` |
| `G4` | No agent changes SAP | Any S/4HANA event other than a read, list or refusal |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `T10 FAIL` with `Drafted CRR-1000002` | `T04` didn't create the draft first | Run `evaluate.py run` again; it resets the logs itself |
| Several FAILs with the same `answer` | Your `ORDERS` or `SAP_ROLES` differ from the listing | Compare with Stage 1 and restart the server |
| `Can't reach the SAP side` | The server stopped | Start it again in the second terminal |

### Stage 7: Business KPI

The KPI is computed from the two logs, not from the test script's own opinion. A request counts as **reached SAP** if the S/4HANA stand-in or the SAP agent wrote at least one record with its request ID. It counts as **identity kept** if every one of those records names the asking person's own SAP user as a user, not a technical user.

#### What you need

- About 15 minutes. Some requests in the logs: the test run, or your own questions.

#### Step 1: The KPI on the test run

```bash
python projects/cross-platform-agent/evaluate.py run
python projects/cross-platform-agent/evaluate.py kpi
```

```text
KPI: requests that reached SAP, served as the asking person's own SAP user
platform    requests  reached SAP  identity kept   share
bedrock            6            5              5    100%
copilot            6            4              4    100%
all               12            9              9    100%
Guardrails: SAP records under a technical user: 0 (target 0); changes to orders: 0 (target 0); credit review drafts waiting for a person: 1
```

> **Note** These numbers come from the project's twelve test questions on synthetic data and local stand-ins. They show the method, not a result from a real SAP system.

#### Step 2: The KPI on your own questions

1. Clear the logs:

   ```bash
   python projects/cross-platform-agent/sap_side.py reset
   ```

2. Ask ten questions of your own, on both platforms and as different people, and add `--auth technical` to two of them.
3. Run `python projects/cross-platform-agent/evaluate.py kpi`. The share drops below 100% on the platform where you used the shortcut, and the guardrail counts its records.

#### What the KPI does and doesn't prove

It proves the identity chain for every request in the logs. It doesn't prove the SAP roles are right: if the rep's role allowed distributor orders by mistake, the KPI would still be 100%. Keep role reviews where they are. In production, the join needs a request ID that crosses every hop; the lab's `X-Request-ID` stands in for a trace context propagated by each platform and gateway, which your observability setup must carry ([observability for AI systems](https://erpfde.com/topics/observability-for-ai-systems/)).

### Human in the loop

No agent changes SAP in this design, and the code enforces it in four places:

1. **No write tool.** The MCP gateway offers two read tools. Any other tool name is answered as an error.
2. **The SAP agent only drafts.** `run_agent()` writes `CRR-<order>` to the draft store and nothing else. The order is unchanged until the credit analyst decides.
3. **One draft per order.** A second request, from either platform, finds the first and adds nothing.
4. **Access to the agent is assigned.** Only users in `ACCESS_AT_AGENT` reach the SAP agent at all, and only platforms in `AGENT_ACL` may call it.

The credit analyst decides the draft in SAP, under her own authorization. A later version could let her approve from Teams. That would be a new design with its own approval step and review, not a setting.

### Production gap

#### Identity and authorizations

The lab's shared secrets stand in for signed tokens and published public keys. SAP's AWS design keeps the client's signing key in AWS KMS so no secret lives in the runtime; SAP's Microsoft cookbook notes the connector still holds one client secret that a managed identity can't replace. Plan rotation for it. The lab's `sap_user` claim stands in for the mapping from Cloud Identity Services to the SAP user, and the channel lists for SAP roles. The effective permission is the intersection of what the person and the agent may do, as SAP's token exchange architecture states; review the agent's own authorizations as well as the users'. Principal propagation across SAP systems is covered in Unit 27, and [agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) covers the agent's side.

#### Data volumes and limits

The lab reads six orders. Real lists need paging and filters on the gateway, and the gateway's rate limits apply to every platform together. Set them per client where the plan allows, and expect a model to call tools more often than a person clicks.

#### Operations

Three platforms now share one incident. Agree who owns the gateway, who owns each platform agent, and how a request ID found in Teams reaches the SAP log. Add the twelve test cases to every change in roles, the gateway or either platform. [Hypercare and drift after go-live](https://erpfde.com/topics/hypercare-and-drift-after-go-live/) applies here too.

#### Cost

Each platform bills its own usage, and SAP's side adds Integration Suite and, for SAP agents, consumption per agent step. Count calls per request from the logs: in the test run, a read is one tool call and a credit review is one A2A task with one read inside it. [Pricing custom agents after the free runtime](https://erpfde.com/topics/pricing-custom-agents-after-the-free-runtime/) and [set up for Unit 15](https://erpfde.com/topics/set-up-for-unit-15/) give the price pages to use.

#### Clean core and SAP's API policy

Both platforms reach SAP through released APIs behind SAP's gateways, and nothing changes in the core. That also matters for SAP's API policy, which treats agent-planned API calls differently from ordinary integrations; [SAP's API policy and third-party agents](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) explains which paths that page found SAP endorses. Before building, check whether a delivered SAP agent already covers the credit review, so the platforms delegate to it instead of to a custom one.

### Portfolio checklist

Put these in your portfolio repository:

- [ ] `README.md`: the problem, the KPI with its baseline and target, and how to run the lab with two terminals
- [ ] The architecture diagram from **Architecture at a glance** and the sequence diagram from Stage 3
- [ ] The output of `evaluate.py run` and of `evaluate.py run --auth technical`, with three sentences on what the second one shows
- [ ] The KPI output from Stage 7, with the synthetic-data note beside it
- [ ] A one-page design summary: the routing rule (tools vs. A2A), the token exchange per hop, the SAP-side onboarding, and the open status questions for SAP
- [ ] One architecture decision record in the short form from [writing a solution design doc](https://erpfde.com/topics/writing-a-solution-design-doc/): shared technical user vs. per-user exchange
- [ ] A 3-minute demo script following **What to show a stakeholder**

### Exercise: a third platform

Calder's marketing team wants an agent in Google Gemini Enterprise to ask the same questions. Add it as a third platform. SAP's cookbook connects Gemini Enterprise with three-legged OAuth and a proxy agent; in the lab, treat it like the other two.

1. In `common.py`, add `GOOGLE_ISSUER = "https://accounts.calder-google.example/lab"` and add `"CALDER_GOOGLE_LAB_KEY"` and `"CALDER_GEMINI_CLIENT_SECRET"` to `SECRET_NAMES`. Run `sap_side.py init` again: it adds only the two new secrets.
2. In `sap_side.py`, import `GOOGLE_ISSUER` and add a client `calder-gemini-bridge` to `CLIENTS` with `"secret": "CALDER_GEMINI_CLIENT_SECRET"`, `"issuer": GOOGLE_ISSUER`, `"issuer_key": "CALDER_GOOGLE_LAB_KEY"` and `"user_claim": "email"`. Don't touch `AGENT_ACL` yet. Restart the server.
3. In `platform_agent.py`, import `GOOGLE_ISSUER` and add a platform `gemini` to `PLATFORMS`, shaped like `bedrock`, with the new issuer, key, client and secret, and `"accounts": PEOPLE`.
4. Ask a read question as the clerk on `gemini`. It should be answered as `00100265`. Then ask for a credit review. It should be refused with `consumer is not allowed to invoke this agent`: the third formation is missing.
5. Add `calder-gemini-bridge` to `AGENT_ACL["order-exc"]`, restart, and ask again. Now it should say the request already waits, or draft it if you reset.
6. In `evaluate.py`, add `T13` (gemini, clerk, read `1000004`, answered, `00100265`, `partly confirmed`), `T14` (gemini, rep, read `1000002`, refused by SAP, `00100266`, `channel 20`) and `T15` (gemini, clerk, credit review of `1000002`, answered, `00100265`, `already waits`).

**Done when** `evaluate.py run` shows 15 of 15 cases and `Release: READY`, the KPI table has a `gemini` row at 100%, and your README explains in two sentences why step 4's refusal is the Agent Gateway's allow-list working, not a bug.

### Check yourself

1. Why does the platform's own token get refused at SAP's gateway?
   - A. It was signed by an identity provider that SAP doesn't know
   - B. Its audience is the platform's client, not the gateway
   - C. It carries the person's email instead of an SAP user
   - D. It expires before the gateway can check its signature

   Answer: B. A platform mints its token for its own client, so the audience names the platform. SAP's architecture has Cloud Identity Services exchange it for a token whose audience is the gateway, keeping the same subject.

2. In `token_endpoint()`, what happens when the visitor's Cognito token is valid but the email isn't in `IAS_USERS`?
   - A. The token is issued with the technical user as a fallback
   - B. The exchange succeeds and SAP refuses at the order
   - C. The exchange returns invalid_grant and nothing reaches SAP
   - D. The platform agent retries with client credentials

   Answer: C. The exchange issues tokens only for people Calder's identity service knows. The visitor's request stops at `ias`, so the audit log has no S/4HANA record for it.

3. The rep can read order 1000003 but gets "RBAC: access denied" asking for its credit review. Why?
   - A. His SAP role doesn't cover any of the channel 10 orders
   - B. The Copilot client isn't on the agent's allow-list
   - C. His token was minted for the MCP gateway instead
   - D. He isn't assigned to the SAP agent's access policy

   Answer: D. The Agent Gateway checks two things before the agent runs: the platform client against the allow-list, then the person against the agent's access policy. The rep passes the first and fails the second; his read rights are a separate check in S/4HANA.

4. What does `evaluate.py run --auth technical` show about the shortcut?
   - A. It only changes the audit log; the answers stay exactly the same
   - B. Forbidden reads pass, and credit reviews start to fail
   - C. It is slower but otherwise equivalent to user tokens
   - D. Only the Bedrock platform is affected by the change

   Answer: B. The technical user can read every channel, so the rep and even the visitor get answers. It isn't assigned to the SAP agent, so the clerk loses the credit review. Less safe and less useful at once.

5. Copilot Studio's native A2A connection can't call the Agent Gateway directly. What does SAP's cookbook recommend?
   - A. An API key on the A2A connection, stored in Copilot Studio
   - B. Calling the MCP gateway instead for credit review requests
   - C. A custom connector that does the exchange per user
   - D. A technical user per Copilot Studio environment

   Answer: C. The gateway accepts only tokens minted for its resource, and the native path can't do the jwt-bearer exchange. The custom connector does it in code, keeping per-user identity.

6. You add a third platform but forget the Agent Gateway allow-list. What do you expect?
   - A. Reads work; credit reviews are refused as a consumer
   - B. Nothing works until every list and formation is updated
   - C. Its credit reviews work, and its reads are refused
   - D. Both work, but SAP logs a technical user for each call

   Answer: A. The MCP gateway trusts any token Cloud Identity Services issued for it, so reads pass under the person's identity. The Agent Gateway also checks the consumer against its allow-list, the third formation, so delegation is refused.

7. The KPI is 100% on both platforms. What does it not prove?
   - A. That every request that reached SAP named the asking person
   - B. That no SAP record was made under a technical user
   - C. That the platform log and SAP log were joined by request ID
   - D. That the SAP roles themselves grant the right access

   Answer: D. The KPI checks the identity chain. If a role granted too much, SAP would serve the right person too much, and the KPI would still read 100%, so role reviews stay in place.

## Sources

- [Copilot Studio with MCP Gateway in SAP Integration Suite (SAP Architecture Center, updated 26 October 2026)](https://architecture.learning.sap.com/docs/ref-arch/d2e34e): read 25 November 2026 from the page source in the SAP/architecture-center repository; Copilot Studio as MCP client and the MCP Gateway as the governed entry point; Entra ID federated with SAP Cloud Identity Services over OIDC; OAuth 2.0 authorization code flow gives a user-delegated token; Streamable HTTP only; prerequisites: customer-managed subaccount with Integration Suite and the MCP Gateway capability; capabilities exposed there are usable by other MCP clients, Bedrock named; start read-only; disclaimer: Agent Gateway not yet GA
- [Third-Party A2A Integration & Token Exchange (SAP Architecture Center, updated 13 October 2026)](https://architecture.learning.sap.com/docs/ref-arch/f4a2c8): read 25 November 2026 from the page source; a third-party runtime's own token has aud = the agent, so the gateway rejects it; jwt-bearer token exchange at SAP Cloud Identity Services with a resource parameter re-issues it with the gateway as audience; sub, sap_id_type and sap_user_type preserved; access@agent policy per user; directional authorization; effective permission is the intersection of user and agent; technical user and agent user variants; some capabilities still in preparation
- [Amazon Quick Integration with Joule Agents (SAP Architecture Center, updated 23 October 2026)](https://architecture.learning.sap.com/docs/ref-arch/b4d7e2): read 25 November 2026 from the page source; Quick reaches an AgentCore Runtime over MCP; three tokens: Cognito access token (email added by a pre-token-generation Lambda), WorkloadAccessToken minted by the Runtime, Cloud Identity Services token from an on-behalf-of exchange by AgentCore Identity with a private_key_jwt assertion whose key stays in AWS KMS; A2A message/send to the Agent Gateway; disclaimer: Agent Gateway not yet GA
- [Microsoft Copilot Integration with Joule Agents (SAP Architecture Center, updated 23 October 2026)](https://architecture.learning.sap.com/docs/ref-arch/a2c0f1): read 25 November 2026 from the page source; a Power Platform custom connector does the token exchange because the native agent-to-agent path can't; the gateway accepts only tokens minted for its resource; Entra ID and Cloud Identity Services federated over OIDC; disclaimer: Agent Gateway not yet GA
- [Third-party agents can now interoperate with SAP Agents via the Agent Gateway (SAP Architecture Center news, 27 October 2026)](https://architecture.learning.sap.com/news/2026/10/27/a2a-agent-gateway-interoperability): read 25 November 2026 from the page source; October 2026 GA of inbound A2A through the Agent Gateway; ARD discovery does not grant permission; consumer registered in SAP for Me; three formations (identity, trust, authorization ACL); on every call the gateway validates the token, resolves the tenant and checks the ACL; the SAP agent works within the user's authorizations; outbound A2A and MCP are future direction
- [SAP Agent Interoperability cookbooks (SAP-samples/agent-interoperability on GitHub)](https://github.com/SAP-samples/agent-interoperability): cloned 25 November 2026, last commit 24 November 2026; common setup: Agent Gateway Consumer system in SAP for Me, three formations in a fixed order (CONFIG_PENDING or ERROR for up to sixty minutes if out of order), JWKS trust or client credentials; AWS: AgentCore OBO exchange, A2A JSON-RPC with the token as Bearer; Google: three-legged OAuth with a proxy agent
- [Microsoft - SAP Agent Interoperability cookbook (SAP-samples/agent-interoperability, 03-microsoft-azure-integration)](https://github.com/SAP-samples/agent-interoperability/tree/main/03-microsoft-azure-integration): cloned 25 November 2026; Approaches A (Entra two-step exchange), B (direct Cloud Identity Services OAuth plus one exchange, the recommended default) and C (native A2A, only for endpoints that accept a plain token); resource urn:sap:identity:application:provider:name:agent-gateway; user not provisioned gives invalid_grant at the exchange, user outside the agent's group gives 403 RBAC access denied, app-only tokens also get 403; native A2A auth offers None, API key or authorization code only; the connector's client secret can't be replaced by a managed identity
- [Configure MCP Server Access Using an External Identity Provider (SAP-docs/btp-integration-suite on GitHub)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/configure-mcp-server-access-using-an-external-identity-provider-fbea412.md): cloned 25 November 2026, repository commit of 22 October 2026; supported identity providers Cloud Identity Services, Okta, Auth0 and Microsoft Entra ID; Authorization Code grant, optional PKCE; with Entra ID or Auth0 configured on the MCP server, user propagation through the authorization code flow is not directly supported; MCP server availability depends on the Integration Suite service plan (SAP Note 2903776, from the MCP server page in the same repository)
- [What's New for SAP API Management, Cloud Foundry (SAP-docs/btp-integration-suite on GitHub)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/what-s-new-for-sap-api-management-cloud-foundry-d9d60be.md): cloned 25 November 2026; MCP specification 2026-07-28 supported in addition to 2025-11-25; up to 50 tools per MCP server; tool simplification hides parameters; all marked General Availability
- [Agent2Agent (A2A) Protocol Specification (a2aproject/A2A on GitHub)](https://github.com/a2aproject/A2A/blob/main/docs/specification.md): cloned 25 November 2026; latest released version 1.0.0; agent card at /.well-known/agent-card.json; SendMessageRequest; SAP's cookbooks call message/send in the 0.3 style
