# AWS Bedrock and AgentCore with SAP: three routes, and where the data is processed

> Compare the AWS routes from an agent to SAP, choose a data residency setting for Bedrock, and run the shared SAP tool through Bedrock's Converse tool loop.

- Course: Orchestrate, Unit 15 · SAP AI next to other platforms
- Page: https://erpfde.com/topics/aws-bedrock-agentcore-with-sap/
- Updated: 2026-11-24
- Reading time: Foundational 9 min, Deep 35 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 60-second version

Many SAP customers run their data platforms and new applications on AWS. When those teams build agents, the agents want SAP data. AWS now offers three routes for that:

1. **An AWS agent calls SAP's APIs through an MCP server.** AWS ships its own, the AWS for SAP MCP Server, which runs on AgentCore (AWS's family of services for running agents) and reaches SAP through SAP BTP.
2. **An AWS agent hands the job to a Joule agent.** The AWS agent sends the request over A2A, the agent-to-agent protocol, to SAP's Agent Gateway, and Joule does the SAP work.
3. **An agent you code yourself.** It calls a model on Amazon Bedrock and calls SAP's APIs with your own code.

Two questions decide whether any route is safe. The first is the same as on Microsoft: **whose identity does SAP see?** The second matters more on AWS than anywhere else in this unit: **in which regions are prompts and answers processed?** Bedrock can send a request to other regions to find capacity, and the model ID you choose decides how far it may travel.

### Why it matters to the business

Calder Pumpworks, the course's fictional pump maker, has two companies. Calder Pumpworks Inc. (`CP10`) sits in the US. Calder Pumpworks GmbH (`CP20`) sits in Augsburg, Germany. Calder's data team runs on AWS and wants an agent that explains the six blocked sales orders from [order to cash](https://erpfde.com/topics/order-to-cash-end-to-end/) each morning, and later Augsburg's orders too.

- **Data residency.** Augsburg's customer and order data may be bound by rules that keep its processing in the EU. A model call that quietly runs in another part of the world breaks that rule even if nothing is stored there.
- **Price against place.** AWS says its global setting is about 10% cheaper than staying in one geography ([AWS](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html)). That saving is tempting, so it needs a written decision, not a default.
- **Identity and audit.** If the agent reads SAP as one shared technical user, every person who can chat with it gets that user's access, and the log names the bot.
- **Write access.** AWS's MCP server can create, update and delete SAP records when an operator turns that on ([AWS](https://aws.amazon.com/about-aws/whats-new/2026/05/aws-sap-mcp-amazon-bedrock/)). Who decides that, and who approves each change, belongs in the design, not in a setting someone flips later.
- **Ownership.** With the Joule route SAP owns the SAP side of the answer. With the other two, Calder owns the tools, the tests and the mistakes.

### How SAP does it

As of 24 November 2026, here is what each route rests on. Check the linked pages on the day you decide, because statuses move.

- **AWS for SAP MCP Server (an AWS offering).** AWS announced it as generally available on 1 May 2026. It exposes SAP's OData services as MCP tools for agents, runs on AgentCore Runtime, and AWS provides the container image at no cost ([AWS](https://aws.amazon.com/about-aws/whats-new/2026/05/aws-sap-mcp-amazon-bedrock/)). AWS's documentation says it covers OData V2 and V4 services of S/4HANA, ECC and SuccessFactors, and reaches SAP through SAP BTP Integration Suite API Management with OAuth 2.0 ([AWS docs](https://docs.aws.amazon.com/mcp-sap/latest/awsforsapmcp/introduction.html)). On 13 November 2026 AWS added on-behalf-of token exchange, so SAP applies each user's own authorizations, and support for Microsoft Entra ID as the sign-in provider ([AWS for SAP blog](https://aws.amazon.com/blogs/awsforsap/bringing-ai-agents-closer-to-sap-whats-new-in-aws-for-sap-mcp-server/)).
- **Joule Agents over A2A.** SAP's Architecture Center describes Amazon Quick reaching AgentCore, which calls Joule Agents over A2A through SAP's Agent Gateway, with the user's identity exchanged in SAP Cloud Identity Services. SAP states that some components, including the Agent Gateway, are not yet generally available ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/b4d7e2), updated 23 October 2026). [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/) teaches the protocol.
- **SAP's own MCP route.** The MCP Gateway in SAP Integration Suite exposes SAP APIs as MCP tools to any client. [The MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) builds a local stand-in.
- **Policy.** Whichever route you pick, check it against SAP's API policy, which limits AI and bulk use of SAP APIs to the paths SAP endorses. [SAP's API policy and third-party agents](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) covers what that means for your contract.

### Three routes and the residency switch

| | AWS for SAP MCP Server | A2A to a Joule agent | Your own agent on Bedrock |
| --- | --- | --- | --- |
| Who builds the SAP side | AWS ships the server; you deploy and scope it | SAP (Joule's skills and agents) | Your developers |
| What it can do in SAP | OData services you allow; writes only if switched on | What the Joule agent covers | Any released API you wire up |
| Whose identity SAP sees | The user, with on-behalf-of exchange; otherwise the configured SAP user | The user, through SAP Cloud Identity Services | Whatever your code sends |
| Status on 24 Nov 2026 | Generally available (AWS) | Agent Gateway not yet GA (SAP) | Bedrock and AgentCore are AWS services; your build has no status |
| Fits Calder when | Several AWS agents need governed SAP reads | The task is already a Joule skill | A narrow agent with custom logic |

The residency switch sits under all three, wherever a Bedrock model is called. A Bedrock model ID carries a prefix that sets how far a request may travel:

| Model ID shape | Where processing may happen | Price (AWS's wording) | Fits Calder's data |
| --- | --- | --- | --- |
| No prefix (one region) | The region you call | Standard | Yes, if the region is in the right geography |
| `us.`, `eu.`, `apac.` (geographic) | Regions inside that geography | Standard pricing | `CP10` with `us.`, `CP20` with `eu.` |
| `global.` | Supported commercial regions worldwide | About 10% savings | Only with a written exception |

AWS says geographic profiles keep processing inside the geography, while prompts and answers may leave the calling region ([AWS](https://docs.aws.amazon.com/bedrock/latest/userguide/geographic-cross-region-inference.html)); global profiles route worldwide ([AWS](https://docs.aws.amazon.com/bedrock/latest/userguide/global-cross-region-inference.html)). The decision for a leader: write the residency rule per company before the first pilot, and make "global" an exception someone signs.

> **Note** **For functional consultants:** these routes don't change SAP configuration, but they change your test cases and your scoping. Test the agent as two users from different company codes and check that SAP refuses what each role refuses. If the AWS MCP server is used, ask for the list of OData services it is allowed to reach, and check that no write service is on it unless a process owner signed for it.

### Questions to ask

- Which SAP user appears in the SAP log when the agent reads an order: the person, or a technical user?
- Which Bedrock model IDs may each company's data go to, and who approved that list?
- Is a `global.` model ID used anywhere, and is the saving worth the exception?
- If we use the AWS for SAP MCP Server, which OData services are allowlisted, and are create, update and delete switched off?
- For the Joule route: is the Agent Gateway generally available for our landscape, and what does each call cost in SAP AI Units?
- Does our route use a path SAP's API policy endorses, and who confirmed it with SAP?
- Who retests the agent when AWS updates the server or the model, or when SAP releases a new version?

### Common misconceptions

- **"We picked an EU region, so the data stays in the EU."** Only if the model ID keeps it there. A `global.` ID can route a call made from an EU region to any supported commercial region.
- **"Nothing is stored abroad, so residency doesn't apply."** AWS says data at rest stays in the source region, but processing still happens wherever the request is routed. Many residency rules cover processing.
- **"The AWS MCP server is SAP's product."** It is AWS's. It reaches SAP through SAP BTP, and SAP's API policy still applies to how it is used.
- **"Read-only is a property of the server."** On AWS's server, writes are a setting the operator controls ([AWS docs](https://docs.aws.amazon.com/mcp-sap/latest/awsforsapmcp/introduction.html)). Read-only is a decision you record and check.
- **"The model won't call a tool we didn't mean it to."** Models ask for whatever the prompt nudges them toward. The code that runs tools must refuse anything not offered.

### Key terms

- **Amazon Bedrock:** AWS's managed service for calling models from several providers.
- **AgentCore:** AWS's family of services for running agents, including Runtime (hosting), Gateway (tools as MCP) and Identity (sign-in and credentials).
- **AWS for SAP MCP Server:** AWS's MCP server that exposes SAP OData services to agents; it runs on AgentCore Runtime.
- **Inference profile:** a Bedrock model ID that lets requests run in more than one region; its prefix (`us.`, `eu.`, `global.`) sets which.
- **Data residency:** a rule about where data may be stored or processed, often per country or region.
- **On-behalf-of exchange:** swapping a user's sign-in token for a token the next service accepts, so the user's identity reaches SAP.

### Check yourself

1. Calder's team calls Bedrock from eu-central-1 with a global. model ID for Augsburg's orders. What is the residency problem?
   - A. None, because the call itself is made from an EU region
   - B. The request may be processed in a region outside the EU
   - C. Augsburg's orders will be stored in a US region
   - D. The call fails, because global IDs need a US region

   Answer: B. The model ID's prefix decides how far a request may travel, not the region you call from. A global profile can route to supported commercial regions worldwide, while AWS says data at rest stays in the source region.

2. Why should a global model ID need a signed exception rather than being a default?
   - A. It costs about 10% more than a geographic profile
   - B. It stores prompts permanently in every region that it uses
   - C. It saves money but gives up control over where processing runs
   - D. It turns off the logs in the region you called from

   Answer: C. AWS prices global profiles about 10% lower, which makes them tempting. The price of that saving is processing in any supported commercial region, which a residency rule may not allow.

3. A data team wants several AWS agents to read SAP orders under one governed setup. Which route fits best?
   - A. Each agent's developer calls SAP's APIs with a shared password
   - B. A Joule agent, because AWS agents can't call SAP APIs
   - C. Bedrock's global profile, because it is closest to SAP
   - D. The AWS for SAP MCP Server with an allowlist of OData services

   Answer: D. The MCP server gives all agents one place to scope which SAP services they reach, with identity handled by AgentCore Identity. Shared passwords lose the person, and the inference profile is about model calls, not SAP access.

4. The AWS for SAP MCP Server can create, update and delete SAP records. What should a leader require?
   - A. Writes stay off unless a process owner signs for them
   - B. Writes stay on, because the model checks its own changes
   - C. Writes are allowed for any record the shared user can see
   - D. Writes are fine as long as the server runs in the EU

   Answer: A. AWS's documentation says writes happen only when the operator enables them, so this is a decision to record. The server's region has nothing to do with whether an agent should change SAP data.

5. Which question best tests whether an AWS agent design protects SAP data?
   - A. Which Bedrock model gives the most fluent and fastest answers?
   - B. Which SAP user appears in the log when the agent reads?
   - C. How many tools the AgentCore Gateway can hold?
   - D. Whether the agent runs on Lambda or a container?

   Answer: B. If SAP sees the real person, SAP's roles decide what they may read and the audit names them. A shared technical user gives everyone who chats its access.

6. Calder wants an AWS agent that hands order questions to a Joule agent over A2A. What should it check first?
   - A. That Joule and the AWS agent use the same model
   - B. That the A2A call is routed through a global inference profile
   - C. That AWS stores Joule's answers for SAP's audit
   - D. Whether SAP's Agent Gateway is generally available for it

   Answer: D. SAP's reference architecture for this flow says some components, including the Agent Gateway, are not yet generally available. Status decides whether this is a pilot or a production route.

## Deep layer

### Mental model

Every AWS route to SAP has two separate trips, and they have separate controls:

1. **The model trip.** The prompt, including any SAP data already in it, goes to a model on Bedrock. The **model ID** decides where that trip may be processed: one region, one geography, or anywhere.
2. **The SAP trip.** A tool call goes to SAP. The **identity** carried on that trip decides what SAP lets the agent read.

Data residency lives on the model trip; authorization lives on the SAP trip. A design review that checks only one of them is half a review. Note the order too: SAP data leaves SAP on the SAP trip, then rides along on every later model trip in the same conversation. So the residency rule that matters is the one for the strictest company code the agent can read.

### How it works

#### The Converse tool loop

Bedrock's Converse API is the plain way to give a model tools. You send the messages and a `toolConfig`; if the model wants a tool, the answer stops with `stopReason` `tool_use` and holds a `toolUse` block with a `toolUseId`, a tool `name` and an `input`. Your code runs the tool and sends back a `toolResult` block with the same `toolUseId`, the `content` (JSON or text) and a `status` of `success` or `error`. The loop ends when the stop reason is `end_turn`. These field names come from the request and response shapes inside boto3 1.44.10, the library the lab uses, which checks every request against them before sending.

```mermaid
sequenceDiagram
  participant U as Clerk
  participant A as Your code
  participant B as Bedrock (model)
  participant T as Tool (SAP)
  U->>A: Why is 1000002 stuck?
  A->>A: Residency check: company, region, model ID
  A->>B: converse(messages, toolConfig)
  B-->>A: stopReason tool_use, get_sales_order(1000002)
  A->>A: Is the tool offered? Is the input valid?
  A->>T: get_sales_order(1000002)
  T-->>A: credit block, owner credit analyst
  A->>B: converse(... toolResult)
  B-->>A: stopReason end_turn, answer
  A-->>U: Answer
```

Since February 2026 Bedrock can also run the loop for you: through the Responses API you pass an AgentCore Gateway as a tool connector, and Bedrock finds the gateway's tools and executes the calls itself ([AWS](https://aws.amazon.com/about-aws/whats-new/2026/02/amazon-bedrock-server-side-tool-execution-agentcore-gateway)). That removes your code from the middle, so the checks in the diagram must then live in the gateway and its IAM permissions.

#### AgentCore Gateway: tools as one MCP server

AgentCore Gateway turns OpenAPI descriptions, Smithy models and Lambda functions into MCP tools, and gives agents one entry point with inbound and outbound authentication ([AWS](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html)). In boto3 1.44.10, a gateway's inbound authorizer can be a custom JWT authorizer or IAM, and each target's outbound credentials can be an OAuth provider with grant type `CLIENT_CREDENTIALS`, `AUTHORIZATION_CODE` or `TOKEN_EXCHANGE`, an API key, or IAM. Those three grant types are the identity decision in miniature: client credentials means one technical identity; the other two can carry the user.

A Lambda target describes its tools in a smaller schema language than JSON Schema. In boto3 1.44.10 its `inputSchema` accepts `type`, `properties`, `required`, `items` and `description`, and nothing else. The lab shows what that costs: the shared tool's `pattern` (1 to 10 digits) and `additionalProperties: false` don't survive the translation, so the tool itself must check its input.

#### AWS for SAP MCP Server

AWS's server runs in AgentCore Runtime and speaks Streamable HTTP at `/mcp`. An AgentCore Identity authorizer checks the token the user's identity provider issued; the server then calls SAP BTP Integration Suite API Management over OAuth 2.0, and the SAP BTP Destination Service routes the call to S/4HANA or ECC ([AWS docs](https://docs.aws.amazon.com/mcp-sap/latest/awsforsapmcp/introduction.html)). AWS's November update adds an on-behalf-of exchange (RFC 8693), so SAP applies the user's own authorizations and records actions against that user ([AWS for SAP blog](https://aws.amazon.com/blogs/awsforsap/bringing-ai-agents-closer-to-sap-whats-new-in-aws-for-sap-mcp-server/)). The same post advises keeping write tools off unless needed, scoping the catalog of services, and using a least-privilege SAP user.

#### Where the model trip runs

| Choice | What AWS says | What you set in IAM or SCPs |
| --- | --- | --- |
| In-region model ID | Processed in the region you call | Allow the model in that region |
| Geographic profile (`us.`, `eu.`, `apac.`, ...) | Processing stays inside the geography; prompts and outputs may leave the source region; data at rest stays where it is | Allow the profile, the model in the source region and in every destination region, using `bedrock:InferenceProfileArn`; a region allowlist in an SCP must include every destination region |
| Global profile (`global.`) | Routes to supported commercial regions worldwide; about 10% cheaper | Global calls show `aws:RequestedRegion` as `unspecified`; allow or deny them with that value and `bedrock:InferenceProfileArn` |

Sources: [overview](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html), [geographic](https://docs.aws.amazon.com/bedrock/latest/userguide/geographic-cross-region-inference.html), [global](https://docs.aws.amazon.com/bedrock/latest/userguide/global-cross-region-inference.html). Two operational facts help audits: CloudTrail logs the call in the source region, and its `additionalEventData.inferenceRegion` field shows where the request was processed ([AWS](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html)).

### Build it yourself: the shared tool on Bedrock, behind a residency gate

You will translate the Unit 15 tool contract into AWS's two tool formats, write Calder's residency policy, and run Bedrock's Converse tool loop on the shared SAP tool. A scripted stand-in model answers inside boto3, so the whole lab runs with no AWS account. One optional step calls real Bedrock for a small charge.

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 15](https://erpfde.com/topics/set-up-for-unit-15/), which installed `boto3==1.44.10` and wrote `unit15/calder_tool.py` and `unit15/tool_contract.json`.

```mermaid
flowchart LR
  C[tool_contract.json] --> T[translate]
  T --> BC[Converse toolConfig]
  T --> GW[AgentCore Gateway<br/>Lambda tool schema]
  P[residency policy] --> R{residency gate}
  R -- allow --> L[Converse loop]
  R -- refuse --> X[stop, log]
  L --> M[scripted model<br/>or Bedrock]
  L --> S[get_sales_order]
```

> **Note** New words in this walkthrough:
> - **boto3:** AWS's Python library. It holds a description of every AWS API and checks each request against it before sending.
> - **Converse API:** Bedrock's one request shape for chatting with any supported model, including tools.
> - **toolConfig:** the part of a Converse request that lists the tools a model may ask for.
> - **Inference profile:** a model ID with a prefix (`us.`, `eu.`, `global.`) that lets Bedrock run the request in other regions.
> - **Residency gate:** a check in your code that refuses a model call when the data's company may not be processed where the call would run.
> - **Stand-in model:** made-up model answers produced by the lab, so you can see the loop without an account.

#### What you need

- Your course folder with `unit15/calder_tool.py` and `unit15/tool_contract.json`.
- About 30 minutes.
- Cost: free. Step 7 is optional and uses an AWS account; each Bedrock call there is a small per-request charge.

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

#### Step 2: Check the libraries

1. Run the Unit 15 check from the setup:

   ```bash
   python check_unit15.py
   ```

2. Look for `OK       boto3 1.44.10` and the `tool contract` line. If `boto3` is `MISSING`, add `boto3==1.44.10` to `requirements.txt` and run `pip install -r requirements.txt`.

**What success looks like:** the library and tool lines are `OK`. `LATER` lines for accounts are fine; this lab needs no account.

#### Step 3: Save the lab

1. In VS Code, right-click the `unit15` folder, choose **New File**, name it `aws_bedrock_lab.py`, paste the code below and save.

```python
"""Unit 15: the shared SAP tool on AWS, with a data residency gate in front of every model call.

What it does:
    translate   turn unit15/tool_contract.json into AWS's two tool formats and check both against the
                request shapes inside boto3: Bedrock's Converse toolConfig, and the tool schema of an
                AgentCore Gateway Lambda target. Shows what each format can't express.
    residency   decide whether an agent may send a company's data to a model in a region, by the model ID's
                prefix: in-Region, a geography (us., eu., ...) or global.
    run         run the Converse tool loop: question, model asks for get_sales_order, the lab runs the
                shared tool, the model answers. Without --bedrock a scripted stand-in model answers, through
                boto3's own client, so no AWS account is needed.
    check       run the 10 scenarios and print PASS or FAIL for each.

Commands (from your course folder, with .venv turned on):
    python unit15/aws_bedrock_lab.py translate
    python unit15/aws_bedrock_lab.py residency --company CP20 --region us-east-1 --model global.anthropic.claude-sonnet-4-5-20250929-v1:0
    python unit15/aws_bedrock_lab.py run "Why is order 1000002 stuck?"
    python unit15/aws_bedrock_lab.py run "Why is order 1000002 stuck?" --bedrock     (needs an AWS account, small charge)
    python unit15/aws_bedrock_lab.py check

Calder Pumpworks is the course's fictional company. The residency policy, the region-to-geography table and
the scripted model are course values. Model IDs are examples from AWS's documentation; check what your
account offers.
"""
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path

import boto3
import botocore.session
from botocore.awsrequest import AWSResponse
from botocore.exceptions import BotoCoreError, ClientError, ParamValidationError
from botocore.validate import validate_parameters
from dotenv import load_dotenv

HERE = Path(__file__).resolve().parent
COURSE = HERE.parent
OUT = HERE / "aws"
AUDIT_LOG = OUT / "aws_lab_audit.jsonl"
POLICY_FILE = HERE / "aws_residency_policy.json"
sys.path.insert(0, str(HERE))
import calder_tool  # noqa: E402  the shared tool from the Unit 15 setup

DEFAULT_REGION = "us-east-1"
DEFAULT_MODEL = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"   # example ID from AWS's documentation
MAX_TURNS = 4                                                      # course value: model calls per question
SYSTEM = ("You help Calder's customer service team. Use get_sales_order to read an order before you "
          "answer. You can only read; never promise to change anything in SAP.")

# Course policy: whose data may be processed where. Written to unit15/aws_residency_policy.json on first use.
DEFAULT_POLICY = {
    "note": "Course policy for Calder Pumpworks (fictional). Geographies a company's data may be processed in.",
    "company_codes": {"CP10": {"geographies": ["us"]}, "CP20": {"geographies": ["eu"]}},
    "allow_global": False,
}
# Course table: region name prefix -> geography. AWS's documentation names the profile prefixes us, eu, apac
# and in (and blog posts jp and au); this lab only needs the first two and treats the rest as "other".
REGION_GEOGRAPHY = {"us": "us", "eu": "eu", "ap": "apac"}
GEO_PREFIXES = ("us", "eu", "apac", "in", "jp", "au")


def log_event(event, **fields):
    OUT.mkdir(exist_ok=True)
    record = {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "event": event, **fields}
    with open(AUDIT_LOG, "a", encoding="utf-8") as handle:
        handle.write(json.dumps(record) + "\n")


# ---------------------------------------------------------------- 1. translate the contract

def load_contract():
    path = HERE / "tool_contract.json"
    if not path.exists():
        sys.exit("Missing unit15/tool_contract.json. Run: python unit15/calder_tool.py contract")
    return json.loads(path.read_text(encoding="utf-8"))


def to_converse(contract):
    """Bedrock Converse: toolConfig.tools[].toolSpec with name, description and inputSchema.json."""
    return {"tools": [{"toolSpec": {"name": t["name"], "description": t["description"],
                                    "inputSchema": {"json": t["parameters"]}}}
                      for t in contract["tools"]]}


GATEWAY_KEYS = {"type", "properties", "required", "items", "description"}   # what boto3 1.44.10 accepts


def to_gateway(schema, path="", dropped=None):
    """AgentCore Gateway Lambda target: a smaller schema language. Returns (schema, dropped keywords)."""
    dropped = [] if dropped is None else dropped
    result = {}
    for key, value in schema.items():
        if key not in GATEWAY_KEYS:
            dropped.append(f"{path or '(top)'}.{key}")
        elif key == "properties":
            result[key] = {name: to_gateway(sub, f"{path}.{name}".lstrip("."), dropped)[0]
                           for name, sub in value.items()}
        elif key == "items":
            result[key] = to_gateway(value, f"{path}[]", dropped)[0]
        else:
            result[key] = value
    return result, dropped


def translate(write=True):
    contract = load_contract()
    tool_config = to_converse(contract)
    gateway_tools, dropped = [], []
    for tool in contract["tools"]:
        schema, lost = to_gateway(tool["parameters"])
        gateway_tools.append({"name": tool["name"], "description": tool["description"], "inputSchema": schema})
        dropped += [f"{tool['name']}: {item}" for item in lost]

    # Check both against the request shapes in boto3's service models. No network, no account.
    models = botocore.session.get_session()
    runtime = models.get_service_model("bedrock-runtime")
    control = models.get_service_model("bedrock-agentcore-control")
    validate_parameters({"modelId": DEFAULT_MODEL, "messages": [{"role": "user", "content": [{"text": "hi"}]}],
                         "toolConfig": tool_config}, runtime.operation_model("Converse").input_shape)
    validate_parameters({"gatewayIdentifier": "lab-gateway", "name": "calder-orders",
                         "targetConfiguration": {"mcp": {"lambda": {
                             "lambdaArn": "arn:aws:lambda:us-east-1:111122223333:function:calder-orders",
                             "toolSchema": {"inlinePayload": gateway_tools}}}}},
                        control.operation_model("CreateGatewayTarget").input_shape)
    if write:
        OUT.mkdir(exist_ok=True)
        (OUT / "bedrock_tool_config.json").write_text(json.dumps(tool_config, indent=2) + "\n", encoding="utf-8")
        (OUT / "agentcore_lambda_tool_schema.json").write_text(json.dumps(gateway_tools, indent=2) + "\n",
                                                               encoding="utf-8")
    return tool_config, gateway_tools, dropped


# ---------------------------------------------------------------- 2. residency gate

def load_policy():
    if not POLICY_FILE.exists():
        POLICY_FILE.write_text(json.dumps(DEFAULT_POLICY, indent=2) + "\n", encoding="utf-8")
    return json.loads(POLICY_FILE.read_text(encoding="utf-8"))


def model_scope(model_id, region):
    """Where a call may be processed, read from the model ID's prefix and the calling region."""
    prefix = model_id.split(".", 1)[0]
    region_geo = REGION_GEOGRAPHY.get(region.split("-", 1)[0], "other")
    if prefix == "global":
        return "global", "worldwide"
    if prefix in GEO_PREFIXES:
        return "geographic", prefix
    return "in-region", region_geo


def residency(company, region, model_id, policy=None):
    """Return (allowed, reason). Refuse anything the policy doesn't clearly allow."""
    policy = policy or load_policy()
    rule = policy["company_codes"].get(company)
    if rule is None:
        return False, f"no residency rule for company code {company}"
    kind, geo = model_scope(model_id, region)
    region_geo = REGION_GEOGRAPHY.get(region.split("-", 1)[0], "other")
    if kind == "global":
        return (True, "global allowed by policy") if policy.get("allow_global") else \
            (False, "global profile may route to any commercial region; policy says no")
    if kind == "geographic" and geo != region_geo:
        return False, f"a {geo}. profile is called from a {geo} region, not {region}"
    if geo not in rule["geographies"]:
        return False, f"{company} data must stay in {', '.join(rule['geographies'])}; {kind} call runs in {geo}"
    return True, f"{kind} call stays in {geo}, allowed for {company}"


# ---------------------------------------------------------------- 3. the tool, run by the lab

def run_tool(name, tool_input, offered, sandbox=False):
    """Run one tool call the model asked for. Returns (toolResult content, status)."""
    if name not in offered:
        log_event("tool_refused", tool=name, reason="not offered")
        return [{"text": f"Tool {name} is not available to this agent."}], "error"
    try:
        if name == "get_sales_order":
            result = calder_tool.get_sales_order(str(tool_input.get("sales_order", "")), sandbox=sandbox)
        elif name == "list_problem_orders" and hasattr(calder_tool, "list_problem_orders"):
            result = calder_tool.list_problem_orders(tool_input.get("sold_to_party"))
        else:
            return [{"text": f"Tool {name} has no implementation in this lab."}], "error"
    except calder_tool.ToolError as error:
        log_event("tool_error", tool=name, error=str(error))
        return [{"text": f"Tool error: {error}"}], "error"
    log_event("tool_ok", tool=name, input=tool_input)
    return [{"json": result if isinstance(result, dict) else {"orders": result}}], "success"


# ---------------------------------------------------------------- 4. a scripted stand-in model

class ScriptedModel:
    """Answers Converse calls inside boto3, before anything is signed or sent.

    It reads the same JSON body Bedrock would receive and returns a response that the lab checks against
    boto3's own output shape. Behaviors: normal, rogue (asks for a write tool) and loop (never stops).
    """

    def __init__(self, behavior="normal"):
        self.behavior, self.calls = behavior, 0

    def attach(self, client):
        client.meta.events.register("before-call.bedrock-runtime.Converse", self.answer)
        self.output_shape = client.meta.service_model.operation_model("Converse").output_shape

    def answer(self, params, **kwargs):
        self.calls += 1
        body = json.loads(params["body"])
        last = body["messages"][-1]["content"]
        results = [block["toolResult"] for block in last if "toolResult" in block]
        if results and self.behavior != "loop":
            content = self.reply_from(results[0])
            response = {"output": {"message": {"role": "assistant", "content": [{"text": content}]}},
                        "stopReason": "end_turn"}
        else:
            question = " ".join(block.get("text", "") for block in last)
            offered = {t["toolSpec"]["name"] for t in body.get("toolConfig", {}).get("tools", [])}
            numbers = re.findall(r"\b\d{1,10}\b", question) or ["1000002"]
            name, tool_input = "get_sales_order", {"sales_order": numbers[0]}
            customer = re.search(r"\bcustomer (\d{8})\b", question)
            if customer and "list_problem_orders" in offered:   # the model only uses tools it was given
                name, tool_input = "list_problem_orders", {"sold_to_party": customer.group(1)}
            if self.behavior == "rogue":
                name = "release_credit_block"
            if "10000-02" in question:
                tool_input = {"sales_order": "10000-02"}
            response = {"output": {"message": {"role": "assistant", "content": [
                {"text": "I'll read the order first."},
                {"toolUse": {"toolUseId": f"tooluse_lab_{self.calls:03d}", "name": name, "input": tool_input}}]}},
                "stopReason": "tool_use"}
        response.update({"usage": {"inputTokens": 400 + 150 * self.calls, "outputTokens": 60,
                                   "totalTokens": 460 + 150 * self.calls},
                         "metrics": {"latencyMs": 0}})
        validate_parameters(response, self.output_shape)   # same shape a real answer has
        return AWSResponse(None, 200, {}, None), response

    @staticmethod
    def reply_from(result):
        block = result["content"][0]
        if result.get("status") == "error":
            return f"I couldn't read that: {block['text']}"
        order = block["json"]
        if "orders" in order:
            found = [o["sales_order"] for o in order["orders"]]
            return f"{len(found)} open orders have a problem: {', '.join(found)}."
        return (f"Order {order['sales_order']} for {order['customer_name'] or order['sold_to_party']} is "
                f"stuck: {order['problem']}. Next step is with: {order['owner'] or 'not known'}.")


# ---------------------------------------------------------------- 5. the Converse loop

def make_client(region, live):
    if live:
        load_dotenv(COURSE / ".env")   # AWS_BEARER_TOKEN_BEDROCK or AWS keys, read by boto3
        return boto3.client("bedrock-runtime", region_name=region)
    # No account: fake credentials, and the scripted model answers before anything is signed or sent.
    return boto3.client("bedrock-runtime", region_name=region, aws_access_key_id="lab",
                        aws_secret_access_key="lab-not-a-secret")


def ask(question, company="CP10", region=None, model_id=None, live=False, behavior="normal", sandbox=False,
        quiet=False):
    load_dotenv(COURSE / ".env")
    region = region or os.getenv("AWS_REGION", DEFAULT_REGION)
    model_id = model_id or os.getenv("BEDROCK_MODEL_ID", DEFAULT_MODEL)
    say = (lambda *a: None) if quiet else print

    allowed, reason = residency(company, region, model_id)
    log_event("residency", company=company, region=region, model=model_id, allowed=allowed, reason=reason)
    say(f"Residency: {'ALLOW' if allowed else 'REFUSE'} ({reason})")
    if not allowed:
        return {"answer": None, "refused": reason, "model_calls": 0, "tool_calls": 0}

    tool_config, _, _ = translate(write=False)
    offered = {t["toolSpec"]["name"] for t in tool_config["tools"]}
    client = make_client(region, live)
    model = None
    if not live:
        model = ScriptedModel(behavior)
        model.attach(client)

    messages = [{"role": "user", "content": [{"text": question}]}]
    tool_calls, tokens = 0, 0
    for turn in range(1, MAX_TURNS + 1):
        response = client.converse(modelId=model_id, messages=messages, system=[{"text": SYSTEM}],
                                   toolConfig=tool_config, inferenceConfig={"maxTokens": 400})
        tokens += response["usage"]["totalTokens"]
        message = response["output"]["message"]
        messages.append(message)
        if response["stopReason"] != "tool_use":
            answer = " ".join(b["text"] for b in message["content"] if "text" in b)
            say(f"Answer after {turn} model call(s), {tool_calls} tool call(s), {tokens} tokens: {answer}")
            return {"answer": answer, "refused": None, "model_calls": turn, "tool_calls": tool_calls}
        results = []
        for block in message["content"]:
            if "toolUse" in block:
                use = block["toolUse"]
                tool_calls += 1
                say(f"  model asks for {use['name']}({json.dumps(use['input'])})")
                content, status = run_tool(use["name"], use["input"], offered, sandbox)
                results.append({"toolResult": {"toolUseId": use["toolUseId"], "content": content,
                                               "status": status}})
        messages.append({"role": "user", "content": results})
    log_event("turn_cap", turns=MAX_TURNS, question=question)
    say(f"Stopped after {MAX_TURNS} model calls without an answer.")
    return {"answer": None, "refused": "turn cap", "model_calls": MAX_TURNS, "tool_calls": tool_calls}


# ---------------------------------------------------------------- 6. the scenarios

def check():
    _, gateway_tools, dropped = translate()
    us, eu = "us.anthropic.claude-sonnet-4-5-20250929-v1:0", "eu.anthropic.claude-sonnet-4-5-20250929-v1:0"
    glob, plain = "global.anthropic.claude-sonnet-4-5-20250929-v1:0", "anthropic.claude-sonnet-4-5-20250929-v1:0"
    q = lambda text, **kw: ask(text, quiet=True, **kw)   # noqa: E731
    scenarios = [
        ("S01 contract fits both AWS tool shapes; gateway drops pattern and additionalProperties",
         lambda: any("pattern" in d for d in dropped) and any("additionalProperties" in d for d in dropped)),
        ("S02 order 1000002: one tool call, answer names the credit block",
         lambda: (r := q("Why is order 1000002 stuck?")) and r["tool_calls"] == 1 and "credit block" in r["answer"]),
        ("S03 order 1009999 doesn't exist: tool error goes back to the model",
         lambda: "not found" in q("What about order 1009999?")["answer"]),
        ("S04 model asks for release_credit_block: refused, not offered",
         lambda: "not available" in q("Release order 1000002", behavior="rogue")["answer"]),
        ("S05 input 10000-02 is refused by the tool's own check",
         lambda: "1 to 10 digits" in q("Check order 10000-02")["answer"]),
        ("S06 model never stops: loop ends at the turn cap",
         lambda: q("Why is order 1000003 stuck?", behavior="loop")["refused"] == "turn cap"),
        ("S07 CP10 data, us-east-1, us. profile: allowed",
         lambda: residency("CP10", "us-east-1", us)[0]),
        ("S08 CP10 data, global. profile: refused",
         lambda: q("Why is order 1000002 stuck?", model_id=glob)["refused"] is not None),
        ("S09 CP20 data, us-east-1, in-region model: refused",
         lambda: not residency("CP20", "us-east-1", plain)[0]),
        ("S10 CP20 data, eu-central-1, eu. profile: allowed",
         lambda: residency("CP20", "eu-central-1", eu)[0]),
    ]
    passed = 0
    for name, test in scenarios:
        try:
            ok = bool(test())
        except Exception as error:   # a failing scenario shouldn't hide the others
            ok, name = False, f"{name}  [{type(error).__name__}: {error}]"
        passed += ok
        print(f"{'PASS' if ok else 'FAIL'}  {name}")
    print(f"{passed} of {len(scenarios)} scenarios passed. Tool files in unit15/aws/, log in {AUDIT_LOG.name}.")
    return passed == len(scenarios)


def main():
    parser = argparse.ArgumentParser(description="Calder's shared SAP tool on AWS Bedrock.")
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("translate", help="write the Converse and AgentCore Gateway tool files")
    res = sub.add_parser("residency", help="may this company's data go to this model in this region?")
    res.add_argument("--company", default="CP10")
    res.add_argument("--region", default=DEFAULT_REGION)
    res.add_argument("--model", default=DEFAULT_MODEL)
    run = sub.add_parser("run", help="ask a question through the Converse tool loop")
    run.add_argument("question")
    run.add_argument("--company", default="CP10")
    run.add_argument("--bedrock", action="store_true", help="call Amazon Bedrock (needs an account)")
    run.add_argument("--sandbox", action="store_true", help="the tool reads SAP's sandbox (SAP_API_KEY)")
    run.add_argument("--model", help="model or inference profile ID (default: BEDROCK_MODEL_ID in .env)")
    run.add_argument("--region", help="AWS region (default: AWS_REGION in .env, else us-east-1)")
    sub.add_parser("check", help="run the 10 scenarios")
    args = parser.parse_args()

    try:
        if args.command == "translate":
            _, gateway_tools, dropped = translate()
            print(f"Wrote aws/bedrock_tool_config.json and aws/agentcore_lambda_tool_schema.json "
                  f"({len(gateway_tools)} tool(s)); both match boto3's request shapes.")
            for item in dropped:
                print(f"  not expressible in the gateway's Lambda schema: {item}")
        elif args.command == "residency":
            allowed, reason = residency(args.company, args.region, args.model)
            print(f"{'ALLOW' if allowed else 'REFUSE'}: {reason}")
        elif args.command == "run":
            ask(args.question, company=args.company, region=args.region, model_id=args.model,
                live=args.bedrock, sandbox=args.sandbox)
        else:
            sys.exit(0 if check() else 1)
    except ParamValidationError as error:
        sys.exit(f"Shape error (boto3 refused the request before sending it): {error}")
    except ClientError as error:
        code = error.response.get("Error", {}).get("Code", "")
        sys.exit(f"AWS refused the call: {code}: {error.response.get('Error', {}).get('Message', '')}")
    except BotoCoreError as error:
        sys.exit(f"Could not call AWS ({type(error).__name__}): {error}")


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

> **Note** Calder Pumpworks is fictional. The residency policy (US data for `CP10`, EU data for `CP20`), the region-to-geography table, the turn cap and the scripted model's answers are course values. The model ID is the example AWS's documentation uses; your account may offer others.

#### Step 4: Translate the contract

1. Run:

   ```bash
   python unit15/aws_bedrock_lab.py translate
   ```

**What success looks like:**

```text
Wrote aws/bedrock_tool_config.json and aws/agentcore_lambda_tool_schema.json (1 tool(s)); both match boto3's request shapes.
  not expressible in the gateway's Lambda schema: get_sales_order: sales_order.pattern
  not expressible in the gateway's Lambda schema: get_sales_order: (top).additionalProperties
```

2. Open `unit15/aws/bedrock_tool_config.json`. It is the contract wrapped as `tools` → `toolSpec` → `inputSchema` → `json`, with the full JSON Schema kept.
3. Open `unit15/aws/agentcore_lambda_tool_schema.json`. The same tool, but without `pattern` and `additionalProperties`. A gateway agent could send `"10000-02"` and the gateway's schema would not stop it; the tool's own check does.

#### Step 5: Try the residency gate

1. Ask whether Augsburg's data may go to a global model from a US region:

   ```bash
   python unit15/aws_bedrock_lab.py residency --company CP20 --region us-east-1 --model global.anthropic.claude-sonnet-4-5-20250929-v1:0
   ```

   ```text
   REFUSE: global profile may route to any commercial region; policy says no
   ```

2. Ask again with an EU region and an EU profile:

   ```bash
   python unit15/aws_bedrock_lab.py residency --company CP20 --region eu-central-1 --model eu.anthropic.claude-sonnet-4-5-20250929-v1:0
   ```

   ```text
   ALLOW: geographic call stays in eu, allowed for CP20
   ```

3. Open `unit15/aws_residency_policy.json`, which the first run wrote. This is the decision in a file that a reviewer can read and that change control can track.

#### Step 6: Run the tool loop and the scenarios

1. Ask about one order:

   ```bash
   python unit15/aws_bedrock_lab.py run "What about order 1000005?"
   ```

   ```text
   Residency: ALLOW (geographic call stays in us, allowed for CP10)
     model asks for get_sales_order({"sales_order": "1000005"})
   Answer after 2 model call(s), 1 tool call(s), 1370 tokens: Order 1000005 for Hallam Fluid Systems is stuck: price missing. Next step is with: Pricing team.
   ```

2. Run all ten scenarios:

   ```bash
   python unit15/aws_bedrock_lab.py check
   ```

**What success looks like:**

```text
PASS  S01 contract fits both AWS tool shapes; gateway drops pattern and additionalProperties
PASS  S02 order 1000002: one tool call, answer names the credit block
PASS  S03 order 1009999 doesn't exist: tool error goes back to the model
PASS  S04 model asks for release_credit_block: refused, not offered
PASS  S05 input 10000-02 is refused by the tool's own check
PASS  S06 model never stops: loop ends at the turn cap
PASS  S07 CP10 data, us-east-1, us. profile: allowed
PASS  S08 CP10 data, global. profile: refused
PASS  S09 CP20 data, us-east-1, in-region model: refused
PASS  S10 CP20 data, eu-central-1, eu. profile: allowed
10 of 10 scenarios passed. Tool files in unit15/aws/, log in aws_lab_audit.jsonl.
```

> **Note** These results come from made-up data and a scripted stand-in model, including the token counts. They show the method (shapes, gate, loop), not how a real model behaves. The output is the same on every run; only the timestamps in the log change.

3. Open `unit15/aws/aws_lab_audit.jsonl`. Each line is one decision: a residency check, a tool call, a refused tool, a turn cap. No key or prompt text is logged.

#### Step 7 (optional, small charge): the same loop on Amazon Bedrock

This step wasn't run against AWS when the topic was written; the code path was tested up to the network call.

1. Start your AWS free plan only now, as the [Unit 15 setup](https://erpfde.com/topics/set-up-for-unit-15/) explains, and add the start date to `.env`, for example `AWS_FREE_START=2026-11-24`.
2. Sign in to the AWS console, switch the region selector at the top right to **US East (N. Virginia)**, and open **Amazon Bedrock**.
3. Create a Bedrock API key on the console's API keys page and copy it. If the console asks you to request access to the model or fill in a use-case form first, do that.
4. Add three lines to `.env`:

   ```text
   AWS_BEARER_TOKEN_BEDROCK=paste-your-key-here
   AWS_REGION=us-east-1
   BEDROCK_MODEL_ID=us.anthropic.claude-sonnet-4-5-20250929-v1:0
   ```

   boto3 reads `AWS_BEARER_TOKEN_BEDROCK` by itself when it calls Bedrock; the lab only loads `.env`.

> **Warning** The key goes in `.env`, never in code or Git. The setup's `.gitignore` keeps `.env` out of your repository. Delete the key in the console when you finish the unit.

5. Run:

   ```bash
   python unit15/aws_bedrock_lab.py run "Why is order 1000002 stuck?" --bedrock
   ```

**What success looks like:** the same three lines as Step 6, with a model-written answer that names the credit block. The wording, the number of model calls and the tokens vary between runs. If you get `AWS refused the call: AccessDeniedException`, your account doesn't have access to that model in that region yet.

#### Step 8: Save your work in Git

```bash
git add unit15/aws_bedrock_lab.py unit15/aws_residency_policy.json unit15/aws
git commit -m "Unit 15: shared SAP tool on Bedrock with a residency gate"
```

The audit log is in `unit15/aws`; if you'd rather not commit it, add `unit15/aws/aws_lab_audit.jsonl` to `.gitignore` first.

#### How the code works

| Part | What it does |
| --- | --- |
| `to_converse()` | Wraps each contract tool as `toolSpec` with `inputSchema.json` for Bedrock's Converse API |
| `to_gateway()` | Copies only the keywords an AgentCore Gateway Lambda target accepts and lists what it had to drop |
| `translate()` | Checks both outputs against the request shapes in boto3's service descriptions (`Converse`, `CreateGatewayTarget`), with no network call |
| `model_scope()`, `residency()` | Reads the model ID's prefix and the region, and refuses unless the policy clearly allows that company's data there |
| `run_tool()` | Runs only tools in the `toolConfig`; anything else goes back to the model as an error |
| `ScriptedModel` | Hooks into boto3 just before a request would be signed and sent, reads the real request body, and returns an answer checked against Bedrock's response shape |
| `ask()` | The Converse loop: residency gate, model call, tool calls, tool results, at most four model calls |
| `check()` | The ten scenarios, each a `PASS` or `FAIL` line |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your path, or the virtual 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 'boto3'` or `'dotenv'` | A library is missing | `pip install -r requirements.txt` with `.venv` on |
| `ModuleNotFoundError: No module named 'calder_tool'` | The setup's tool isn't in `unit15` | Do Step 3 of [Set up for Unit 15](https://erpfde.com/topics/set-up-for-unit-15/) |
| `Missing unit15/tool_contract.json` | The contract wasn't written | `python unit15/calder_tool.py contract` |
| `Shape error (boto3 refused the request before sending it)` | A tool file doesn't match AWS's request shape, often after editing the contract | Read the field named in the message; a tool name may use only letters, digits, `_` and `-`, up to 64 characters |
| `Could not call AWS (NoCredentialsError)` | Step 7 without a key | Add `AWS_BEARER_TOKEN_BEDROCK` to `.env`, or leave out `--bedrock` |
| `AWS refused the call: UnrecognizedClientException` or `ValidationException` | Wrong or expired key, or a model ID your region doesn't offer | Create a new key; check the model ID and region in the console |
| `Could not call AWS (EndpointConnectionError)` or a proxy error | No network path to AWS, often a company proxy | Try another network; the scripted path needs no network |

### The SAP way

As of 24 November 2026:

- **AWS for SAP MCP Server** is AWS's, not SAP's, but it is the shortest documented path from an AWS agent to SAP's OData APIs. It is generally available, runs in AgentCore Runtime, reaches SAP through SAP BTP Integration Suite API Management and the SAP BTP Destination Service, and can be allowlisted by API prefix ([AWS docs](https://docs.aws.amazon.com/mcp-sap/latest/awsforsapmcp/introduction.html)). Identity propagation by token exchange and Entra ID sign-in arrived on 13 November 2026, along with OData V4, SuccessFactors and 17 regions in all ([AWS for SAP blog](https://aws.amazon.com/blogs/awsforsap/bringing-ai-agents-closer-to-sap-whats-new-in-aws-for-sap-mcp-server/)). AWS lists SAP Joule among its clients ([AWS](https://aws.amazon.com/about-aws/whats-new/2026/05/aws-sap-mcp-amazon-bedrock/)). Licensing: AWS charges nothing for the image; you pay for the AWS services it runs on, and SAP BTP Integration Suite is licensed by SAP.
- **Joule Agents over A2A.** SAP exposes Joule Agents to outside agents through the Agent Gateway using A2A 0.3.0 with HTTP+JSON and SAP Cloud Identity Services App2App tokens, and names AWS Bedrock AgentCore as a caller. SAP says not all components are generally available, and that two-way traffic with third-party agents through the gateway isn't supported yet ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/fe0d1d), updated 26 October 2026). The Amazon Quick page adds the identity detail: AgentCore Identity exchanges the user's token with SAP Cloud Identity Services on the user's behalf, signing a `private_key_jwt` assertion with a key kept in AWS KMS ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/b4d7e2)). [A2A for SAP agents](https://erpfde.com/topics/a2a-for-sap-agents/) has a sketch of hosting your own A2A agent on AgentCore.
- **SAP Integration Suite MCP Gateway.** SAP's own way to expose its APIs as MCP tools. An AWS agent is one more MCP client; [the MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) shows the policies it applies.

### Build vs. SAP

| Need | Build on AWS | Use SAP's offering | Calder's choice |
| --- | --- | --- | --- |
| Read a few OData APIs for a data-team agent | AWS for SAP MCP Server, or your own Converse loop with a gateway | MCP Gateway in Integration Suite | AWS MCP server, reads only, user propagation |
| A task Joule already does well | Rebuild it in Bedrock | A2A to the Joule agent | Wait for the Agent Gateway's GA, then A2A |
| Logic that spans SAP and AWS data | Agent on AgentCore with tools for both | SAP's agents don't see the AWS side | Build, behind the residency gate |
| Strict EU processing for `CP20` | `eu.` profiles, SCPs, CloudTrail checks | Not covered by the routes above; ask SAP where Joule's own processing runs | `eu.` profiles; the policy file records it |
| Writes to SAP | Approval step in your code, writes off in the server | Joule's own approval flows | Not in the first release |

### Architecture view

**Where it sits.** The agent and its model calls run in Calder's AWS account. SAP calls leave AWS for SAP BTP (Integration Suite API Management, Destination Service, Cloud Connector for on-premise systems) and reach `CP10`'s S/4HANA and, until the July 2027 rollout, `CP20`'s ECC.

```mermaid
flowchart LR
  subgraph AWS[Calder AWS account]
    AG[Agent on AgentCore Runtime] -->|model trip| BR[Bedrock: us. or eu. profile]
    AG -->|MCP| MS[AWS for SAP MCP Server]
    ID[AgentCore Identity] -.token exchange.-> MS
  end
  subgraph BTP[SAP BTP]
    APIM[Integration Suite API Management] --> DS[Destination Service]
  end
  MS -->|OAuth, user token| APIM
  DS --> S4[S/4HANA CP10]
  DS --> ECC[ECC CP20]
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Residency | `CP10` data in US, `CP20` data in EU, for storage and processing | A legal finding; the agent is switched off |
| Identity | Every SAP read under the person's SAP user | Over-broad access and an audit trail that names a bot |
| Least privilege | Allowlisted OData services, writes off | One prompt injection becomes a change in SAP |
| Latency | Answer in under 10 seconds for a two-tool question | Users go back to SAP screens |
| Cost | Model calls and AgentCore metered per use, reviewed monthly | A loop or a chatty prompt grows the bill unnoticed |

**Integration and identity.** The user signs in to an identity provider (Cognito or Entra ID); AgentCore Identity checks the inbound token and exchanges it on the user's behalf; API Management and the Destination Service carry it to SAP, where the user's roles apply. Data flows only through released OData services. The model trip carries no SAP credentials, only the data the tool returned.

**The decision to record.**

- *Context:* Calder's data team builds agents on AWS that read `CP10` and `CP20` orders.
- *Options:* (A) Converse loop per agent with direct SAP calls; (B) AWS for SAP MCP Server with token exchange; (C) A2A to Joule Agents.
- *Decision:* B for reads, with an allowlist of order services, writes off, `us.` profiles for `CP10` and `eu.` profiles for `CP20`, `global.` denied by SCP. Revisit C when SAP's Agent Gateway is generally available.
- *Consequences:* one place to scope SAP access; Calder runs and patches the server; an Integration Suite dependency; two model configurations instead of one.

**What a design review will ask.**

1. Show the SAP log for one agent read. Whose user is it?
2. Which SCP or IAM statement stops a `global.` model ID, and how do you prove no call ran outside its geography?
3. Which OData services are allowlisted, and who signed for each?
4. What happens if the identity exchange fails: does the agent stop or fall back to a shared user?
5. Is this path endorsed under SAP's API policy, and where is that written down?

### Production concerns

- **Security and SAP authorizations.** Propagate the user to SAP; deny the agent any route that falls back to a technical user. Keep write tools off in the MCP server, and refuse unoffered tools in your own loops, as S04 shows. Treat order texts as untrusted input ([prompt injection and tool poisoning](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/)).
- **Residency.** Enforce it twice: in your code (the gate) and in the account (an SCP that denies `global.` profiles, and IAM that allows only the approved profiles). Use CloudTrail's `inferenceRegion` field for spot checks.
- **Evaluation.** Test with users from both company codes and with orders that should be refused. Keep the scenario list in the repository and rerun it when the model ID changes.
- **Cost.** Bedrock charges per input and output token by model and region; AgentCore and the MCP server's AWS resources are metered separately; Integration Suite is on SAP's bill. Cap the loop (the lab stops at four model calls) and log tokens per question.
- **Operations.** Pin the boto3 version and the model ID. Subscribe to AWS's updates for the MCP server and SAP's for the Agent Gateway; both changed this autumn.
- **Clean core.** All routes here use released OData APIs or A2A from outside the SAP system; nothing is modified inside S/4HANA. Check the path against [SAP's API policy](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/).

### Pitfalls

- **Picking a `global.` model ID for the price.** The 10% saving buys processing anywhere. Make it an exception with a signature.
- **Checking the region, not the model ID.** An EU region with a global profile is not EU processing.
- **Blocking a destination region in an SCP.** AWS warns that a geographic profile fails if any of its destination regions is denied, even when the calling region is allowed.
- **Trusting the gateway schema to validate input.** The Lambda target schema has no `pattern`; validate in the tool.
- **Leaving writes on "for later".** A setting someone forgets is a change channel into SAP.
- **Testing as one user.** One user can't show that SAP refuses what a role refuses. Test with two.

### Exercise

Give the AWS agent the second tool from the setup's exercise, so it can list a customer's problem orders.

1. If you haven't, do the [Unit 15 setup exercise](https://erpfde.com/topics/set-up-for-unit-15/), which adds `list_problem_orders` to `unit15/calder_tool.py`, and run `python unit15/calder_tool.py contract`.
2. Run `python unit15/aws_bedrock_lab.py translate`. It now reports `2 tool(s)` and four dropped keywords.
3. Ask about a customer:

   ```bash
   python unit15/aws_bedrock_lab.py run "Which orders of customer 10000001 are stuck?"
   ```

   The scripted model now picks `list_problem_orders`, because it reads the tools in the request.
4. Open `unit15/aws_bedrock_lab.py`. In `check()`, find the line `lambda: residency("CP20", "eu-central-1", eu)[0]),` and paste these two lines directly below it, before the `]`:

   ```python
           ("S11 customer 10000001: list_problem_orders finds Brennock's four orders",
            lambda: "1000003, 1000004, 1000006, 1000007" in q("Which orders of customer 10000001 are stuck?")["answer"]),
   ```

5. Run `python unit15/aws_bedrock_lab.py check` and commit with the message `Unit 15: AWS agent with two tools`.

**Done when:** the check prints `PASS  S11 customer 10000001: list_problem_orders finds Brennock's four orders` and ends with `11 of 11 scenarios passed.` Keep `aws_residency_policy.json`: the decision guide later in Unit 15 compares where an agent should live, and residency is one of its criteria.

### Going further

For readers designing residency controls for a whole AWS organization, or choosing between client-side and server-side tool loops.

- [Geographic cross-Region inference](https://docs.aws.amazon.com/bedrock/latest/userguide/geographic-cross-region-inference.html) gives the exact IAM statements for a geographic profile: the profile, the model in the source region and the model in each destination region, joined by `bedrock:InferenceProfileArn`. Read it before writing an SCP.
- [Global cross-Region inference](https://docs.aws.amazon.com/bedrock/latest/userguide/global-cross-region-inference.html) shows how global calls appear to IAM (`aws:RequestedRegion` is `unspecified`) and the deny statement for `global.*` profiles. That is the account-level twin of the lab's gate.
- [Server-side tool execution](https://aws.amazon.com/about-aws/whats-new/2026/02/amazon-bedrock-server-side-tool-execution-agentcore-gateway) moves the tool loop into Bedrock. Weigh what you gain (less code, one call) against what you lose: your loop's own checks, such as the turn cap and the refusal of unoffered tools, must move into the gateway's configuration and IAM.
- [AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html) describes semantic tool selection across many targets. With dozens of SAP services behind one gateway, tool selection becomes part of what you evaluate, not just answer quality.

One hard edge case is mixed data in one conversation. If a question pulls a `CP10` order and then a `CP20` order, the second model call carries both. A per-company gate must then apply the stricter rule to the whole conversation, or start a new one per company.

### Check yourself

1. In the lab, why does S01 report that the AgentCore Gateway schema dropped pattern and additionalProperties?
   - A. The Converse API refuses JSON Schema keywords it doesn't know
   - B. The gateway's Lambda tool schema accepts only five keywords
   - C. boto3 strips every keyword that isn't a plain description
   - D. The shared contract wrote them in the wrong place

   Answer: B. In boto3 1.44.10 the Lambda target's `inputSchema` accepts `type`, `properties`, `required`, `items` and `description`. Converse keeps the full JSON Schema, so only the gateway translation loses the constraints.

2. After that translation, how is an input like "10000-02" stopped?
   - A. The gateway rejects it because the field is a string
   - B. Bedrock refuses to send the tool call to the gateway
   - C. The shared tool checks for 1 to 10 digits itself
   - D. The residency gate refuses inputs with punctuation

   Answer: C. Once `pattern` is gone, the schema can't stop it, so `get_sales_order` validates its own input (S05). Validation in the tool holds whatever schema language a platform uses.

3. The scripted model asks for release_credit_block (S04). What does the lab do, and why does it matter?
   - A. It runs the tool, because the model is the one that decides
   - B. It asks the user to approve, then releases the block
   - C. It crashes, because the tool name isn't in boto3's model
   - D. It returns an error result, because the tool isn't offered

   Answer: D. `run_tool()` only runs tools named in the `toolConfig` and sends anything else back as a `toolResult` with status `error`. A model can ask for anything; the code that runs tools must refuse what wasn't offered.

4. Augsburg's data team calls Bedrock from eu-central-1 with an in-region model ID. What does the residency gate decide for CP20?
   - A. Allow, because an in-region call in an EU region stays in the EU
   - B. Refuse, because only eu. profiles are allowed for CP20
   - C. Refuse, because in-region IDs may route anywhere
   - D. Allow only if allow_global is set to true

   Answer: A. With no prefix, `model_scope()` takes the calling region's geography, here `eu`, which the policy allows for `CP20`. S09 is the opposite case: an in-region call from us-east-1 runs in the US and is refused.

5. Your SCP allows only us-east-1, and calls with a us. profile start failing. What is the likely cause?
   - A. us. profiles can only be called from us-west-2
   - B. The SCP must allow the global. prefix as well
   - C. The profile routes to other US regions the SCP blocks
   - D. Geographic profiles need the bearer token, not IAM

   Answer: C. AWS says a region allowlist must include every destination region of a geographic profile, or calls fail even when the source region is allowed. Allow the destination regions or add an inference-profile exception.

6. How does an auditor find where a Bedrock request was actually processed?
   - A. From the model ID's prefix, which names the exact region
   - B. From CloudTrail's inferenceRegion field in the source region's log
   - C. From the destination region's CloudTrail, where the call is logged
   - D. From the token count, which differs by region

   Answer: B. AWS logs the call in the source region, and `additionalEventData.inferenceRegion` shows the region that processed it. A prefix only names the geography.

7. In AWS's MCP server, which change made SAP apply each user's own authorizations?
   - A. Moving the server from Lambda to AgentCore Runtime
   - B. Adding OData V4 next to OData V2 services
   - C. Switching the gateway's outbound grant to client credentials
   - D. On-behalf-of token exchange, added in November 2026

   Answer: D. AWS's 13 November post describes an RFC 8693 on-behalf-of exchange, so SAP applies the user's authorizations and logs against that user. Client credentials is the opposite: one technical identity for everyone.

8. Calder considers Bedrock's server-side tool execution through an AgentCore Gateway. What must move with it?
   - A. The residency policy, because Bedrock ignores model ID prefixes
   - B. Nothing, because the Converse loop still runs on the laptop
   - C. The loop's own checks, such as the turn cap and tool refusals
   - D. The SAP roles, because the gateway replaces SAP's checks

   Answer: C. With server-side execution Bedrock discovers and runs the gateway's tools in one call, so your loop is no longer in the middle. Its checks must live in the gateway's configuration and IAM instead.

## Sources

- [General availability of AWS for SAP MCP Server in Amazon Bedrock AgentCore (AWS What's New, 1 May 2026)](https://aws.amazon.com/about-aws/whats-new/2026/05/aws-sap-mcp-amazon-bedrock/): Opened 2026-11-24. GA; built on MCP and SAP's OData; S/4HANA and ECC; agents can create, read, update and delete business objects; AgentCore Identity with OAuth 2.0; runs on AgentCore Runtime from CloudFormation templates; container image at no cost; clients named Amazon Quick, Strands SDK agents and SAP Joule
- [What is the AWS for SAP MCP Server? (AWS documentation)](https://docs.aws.amazon.com/mcp-sap/latest/awsforsapmcp/introduction.html): Opened 2026-11-24, no page date. OData V2 and V4 services of S/4HANA, ECC and SuccessFactors; create, update and delete only when the operator enables them; allowlisting by API prefix; container in AgentCore Runtime, Streamable HTTP at /mcp; inbound token checked by an AgentCore Identity authorizer; outbound OAuth 2.0 to SAP BTP Integration Suite API Management, SAP BTP Destination Service to the SAP system; secrets in AWS Secrets Manager
- [Bringing AI agents closer to SAP: what's new in AWS for SAP MCP Server (AWS for SAP blog, 13 November 2026)](https://aws.amazon.com/blogs/awsforsap/bringing-ai-agents-closer-to-sap-whats-new-in-aws-for-sap-mcp-server/): Opened 2026-11-24. Identity propagation by on-behalf-of token exchange (RFC 8693), so SAP applies the user's own authorizations and logs against that user; Microsoft Entra ID added beside Amazon Cognito; OData V4 and SuccessFactors; three more regions for 17 in all; advises keeping write tools off and using a least-privilege SAP user
- [Amazon Bedrock AgentCore Gateway (AWS documentation)](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html): Opened 2026-11-24, no page date. Single entry point for agent traffic; turns OpenAPI, Smithy and Lambda into MCP tools; inbound and outbound authentication; semantic tool selection; targets grouped as MCP, HTTP and inference targets
- [Amazon Bedrock now supports server-side tool execution with AgentCore Gateway (AWS What's New, 24 February 2026)](https://aws.amazon.com/about-aws/whats-new/2026/02/amazon-bedrock-server-side-tool-execution-agentcore-gateway): Opened 2026-11-24. Through the Responses API, Bedrock discovers a gateway's tools and runs the calls without client-side orchestration; access still governed by the gateway and IAM
- [Increase throughput with cross-Region inference (Amazon Bedrock User Guide)](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html): Opened 2026-11-24, no page date. Geographic and global inference profiles; traffic stays on the AWS network, encrypted between regions; CloudTrail logs in the source region with additionalEventData.inferenceRegion; geographic at standard pricing, global about 10% cheaper
- [Geographic cross-Region inference (Amazon Bedrock User Guide)](https://docs.aws.amazon.com/bedrock/latest/userguide/geographic-cross-region-inference.html): Opened 2026-11-24, no page date. Processing stays within the geography (US, EU, APAC); prompts and outputs may leave the source region; data at rest stays where it resides; IAM with bedrock:InferenceProfileArn; an SCP region allowlist must include every destination region
- [Global cross-Region inference (Amazon Bedrock User Guide)](https://docs.aws.amazon.com/bedrock/latest/userguide/global-cross-region-inference.html): Opened 2026-11-24, no page date. global. prefix; routes to supported commercial regions worldwide; about 10% saving on input and output tokens; logs stay in the source region; IAM and SCP use aws:RequestedRegion unspecified with bedrock:InferenceProfileArn
- [Amazon Quick Integration with Joule Agents (SAP Architecture Center, updated 2026-10-23)](https://architecture.learning.sap.com/docs/ref-arch/b4d7e2): Opened 2026-11-24. Amazon Quick reaches AgentCore over an MCP connector; AgentCore sends A2A message/send to the Agent Gateway; AgentCore Identity performs an on-behalf-of exchange with SAP Cloud Identity Services using a private_key_jwt client assertion whose key stays in AWS KMS; some components not yet GA, including the Agent Gateway
- [Integrating Joule Agents into Your Ecosystem, inbound A2A (SAP Architecture Center, updated 2026-10-26)](https://architecture.learning.sap.com/docs/ref-arch/fe0d1d): Opened 2026-11-24. Joule Agents exposed through the Agent Gateway over A2A 0.3.0 with HTTP+JSON; SAP Cloud Identity Services App2App tokens; lists AWS Bedrock AgentCore as a caller; not all components GA; bidirectional traffic with third-party agents through the gateway not yet supported
