Most SAP customers also run Microsoft 365, Teams and Azure. Sooner or later someone asks for "an assistant in Teams that knows our orders". There are three routes for that, and they differ in who builds what and who owns the answer.
Joule inside Microsoft 365 Copilot. SAP's own assistant answers SAP questions from inside Teams and Copilot. You configure it; you don't build it.
A Copilot Studio agent that calls SAP tools. Your team builds an agent in Microsoft's low-code tool, and it calls SAP through an MCP server or a connector.
A custom agent on Azure. Developers build an agent in code on Azure's model services, and it calls SAP's APIs.
Whichever route you take, one question decides whether it is safe: when the agent reads SAP, whose identity does SAP see? If it sees the real person, SAP's own roles decide what they may read, and the audit trail names them. If it sees one shared technical user, everybody in Teams gets that user's access. Principal propagation is the name for carrying the person's identity all the way to SAP.
Calder Pumpworks, the course's fictional pump maker, is a Microsoft shop. Its customer service team lives in Teams. Each morning they chase the six blocked sales orders from order to cash: a credit block, a missing price, a delivery block and so on. Today a clerk opens SAP, searches, and copies details into a chat. An assistant in Teams could save that walk.
The value is real but small per question, so the risk side decides the project:
Data exposure. An inside sales rep at Calder handles direct customers only. If the Teams agent reads SAP as a shared user, that rep can ask about a distributor's credit block and get an answer SAP itself would have refused.
Audit. Calder's auditors check who looked at credit data. A shared user's log says "the bot", every time.
Cost and licensing. Each route has its own meter: Microsoft 365 Copilot and Copilot Studio licences on one side, SAP AI Units for Joule's features on the other (SAP). Two meters for one question is easy to miss in a business case.
Ownership. With route 1 SAP owns the answer quality. With routes 2 and 3 Calder does, including testing every time SAP or Microsoft changes something.
As of 24 November 2026, here is what each route rests on. Statuses change quickly, so check the linked pages on the day you decide.
Joule and Microsoft 365 Copilot. SAP describes a two-way integration: Microsoft 365 users reach SAP tasks and data through Joule, and Joule users reach Microsoft 365 information. The product page lists it as an AI feature for which AI Units are currently required, and availability varies by country (SAP). SAP's setup lesson says it starts with Microsoft Teams, is opt-in, shows which assistant answered, and needs a licensed Microsoft 365 Copilot environment, an activated Joule, and identity alignment between the two (SAP Learning). Microsoft's Sapphire summary says it reached general availability in late 2025 (Microsoft Tech Community).
Copilot Studio through SAP's MCP Gateway. SAP's Architecture Center publishes a reference architecture for a Copilot Studio agent that reaches SAP through the MCP Gateway in SAP Integration Suite, with the user's identity flowing from Microsoft Entra ID to SAP Cloud Identity Services. The Unit 15 setup summarizes it, and the MCP gateway topic builds a local stand-in of the gateway.
Copilot Studio or Azure through SAP BTP or Azure API Management. Microsoft documents a Copilot agent calling an API exposed on SAP BTP, where BTP authenticates the user, and SAP Cloud Connector reaches systems behind the firewall (Microsoft Learn). A second Microsoft guide uses Azure API Management to turn the user's Entra ID token into an SAP token (Microsoft Learn).
Agent to agent. In May 2026 Microsoft described early scenarios in which Copilot Studio hands SAP work to Joule over A2A through SAP's agent gateway (Microsoft Tech Community). A2A for SAP agents teaches the protocol.
The tools you expose (MCP server, OData connector)
Any released API you wire up
Whose identity SAP sees
The user, through the identity alignment SAP requires
The user, if you choose OAuth sign-in; one technical user if you choose an API key
The user, if you build the token exchange; often a shared user if you don't
Main cost lines
Microsoft 365 Copilot licences plus SAP AI Units
Copilot Studio licensing plus the SAP side (Integration Suite)
Azure model usage plus the SAP side
Who owns answer quality
SAP
You
You
Fits Calder when
The question is already a Joule skill
The team wants a Teams agent over a few SAP tools
The workflow needs custom logic or other systems too
The decision for a leader: start with route 1 for anything Joule already covers, use route 2 for a narrow Teams agent, and keep route 3 for work that needs custom code. In every case, refuse a design where SAP sees a shared user for personal questions.
When our agent reads an order, which SAP user appears in the SAP log: the person or a technical user?
How are Entra accounts matched to SAP users, and who fixes a person who doesn't match?
For Joule in Microsoft 365 Copilot: is it available in our region, how many AI Units does it consume, and which Joule skills does it cover for our edition?
For Copilot Studio: which authentication does the MCP server or connector use, and do our Power Platform data policies allow it?
Who tests the agent when SAP releases a new version, or when Microsoft changes Copilot Studio?
"Signing in to Teams means SAP knows who I am." Only if the integration carries that identity to SAP. With an API key, SAP sees the key's user.
"An API key is fine for a pilot." A pilot on real data with a shared user already shows people data their role doesn't allow. Use a key only on made-up data.
"Joule in Teams and a Copilot Studio agent are the same thing." Joule is SAP's assistant with SAP's skills; a Copilot Studio agent is yours, and so are its tools, tests and mistakes.
"The agent's guardrails will stop it from showing restricted orders." Instructions to a model are not an authorization check. SAP's roles are, but only if SAP sees the real user.
"Copilot Studio can reach any server." It needs an HTTPS address it can reach, and it uses the Streamable HTTP transport; Microsoft dropped the older SSE transport after August 2025 (Microsoft Learn).
Pick one answer for each question. The explanation appears after you choose.
1Calder's Teams agent reads SAP with one API key. An inside sales rep asks about a distributor's credit-blocked order. What happens?
Answer: B. With an API key, SAP sees one technical user for every person, so the rep's own role never gets checked. Only carrying the person's identity to SAP lets SAP's roles decide.
2Which route should Calder try first for a question that a Joule skill already answers?
Answer: B. When Joule already covers the question, activating it in Microsoft 365 Copilot avoids building and maintaining your own agent. Custom routes make sense where Joule doesn't reach.
3What does principal propagation give Calder's auditors?
Answer: C. Principal propagation carries the signed-in person to SAP, so SAP's own log and roles apply per person. A shared technical user makes every read look the same.
4A business case for Joule in Microsoft 365 Copilot lists only Microsoft 365 Copilot licences. What is missing?
Answer: A. SAP's product page says AI Units are currently required for the Joule and Microsoft 365 Copilot feature. A case that counts only the Microsoft side undercounts the cost.
5A team wants to run a Copilot Studio pilot on real orders with an API key "to keep it simple". What should a leader say?
Answer: A. A shared key shows real data to people whose roles don't allow it, even in a small pilot. Made-up data keeps the simple setup safe; real data needs the person's identity to reach SAP.
6Who owns the quality of the answers in a Copilot Studio agent that calls SAP tools?
Answer: A. With routes 2 and 3 the company builds the agent, so it owns testing, quality and fixes. With Joule in Microsoft 365 Copilot, SAP owns the answers.
An agent call to SAP has two questions, and they are easy to confuse:
May this agent call this server at all? That is the door: a key, a token, a network rule.
Which SAP user is reading? That is the identity SAP checks its roles against.
An API key answers only the first. A user token carried through a trust chain (Entra ID, then SAP Cloud Identity Services or an API gateway, then SAP) answers both. Every Microsoft route in this topic is a different way to build that chain. When you review a design, follow the person's identity hop by hop until it reaches SAP, and note where it turns into a shared user. That spot is where SAP stops being able to protect its data.
You don't build anything here. SAP's lesson lists the prerequisites: a licensed Microsoft 365 Copilot environment, an activated Joule, identity alignment between the SAP and Microsoft environments, and network and trust settings between them (SAP Learning). Identity alignment is the important line: Joule acts for the signed-in user, so each Microsoft account must match an SAP identity. The detailed setup is in SAP's Discovery Center mission and the Help Portal, which the lesson points to.
#Route 2: a Copilot Studio agent with an MCP server
Copilot Studio adds an MCP server through a wizard. As of Microsoft's page updated 18 November 2026, you open the agent's Tools page, choose Add a tool, New tool, then Model Context Protocol, and enter a server name, description and URL (Microsoft Learn). The authentication choice is the identity decision:
Choice in the wizard
What it sends
Whose identity SAP can see
None
Nothing
Nobody; only for public data
API key (Header or Query)
One key, which the agent's user provides
The key's technical user
OAuth 2.0 (Dynamic discovery, Dynamic or Manual)
A token per user, after sign-in and consent
The person, if the server and SAP trust the token's issuer
Microsoft's page says the OAuth token lets the agent use the server on behalf of the user. It also says the wizard creates a Power Platform connector behind the scenes, so your Power Platform data policies apply to MCP access. Two more rules from Microsoft's concept page: generative orchestration must be on, and Copilot Studio supports MCP tools and resources (Microsoft Learn). A preview article covers the same step for agents in Microsoft's new agent experience, and warns that each MCP server counts against the agent's tool limit (Microsoft Learn, preview).
The MCP server can be SAP's MCP Gateway in Integration Suite, or one you run. Copilot Studio also has older routes: the SAP OData connector, which supports Basic, Anonymous, and Entra ID single sign-on through Azure API Management, and an on-premises data gateway for systems behind a firewall (Microsoft Learn).
A developer builds the agent in code and calls a model on Azure. The model call and the SAP call are separate. The model call is authenticated as the application. The SAP call must carry the user, and Microsoft documents two ways to do it:
Through SAP BTP. The agent calls an API exposed on BTP (SAP API Management, Integration Suite or an app proxy). BTP authenticates the user, which gives single sign-on and principal propagation, and SAP Cloud Connector forwards the call to an SAP system behind the firewall (Microsoft Learn). For BTP to trust Entra ID, Entra is set up as a corporate identity provider in SAP Cloud Identity Services, which then acts as a proxy for SAP applications (Microsoft Learn).
Through Azure API Management. A policy in Azure API Management exchanges the user's Entra ID token for an SAP OAuth token, using a SAML trust between Entra ID and the SAP system. The user's principal name from Entra is matched to the SAP user's email (Microsoft Learn).
sequenceDiagram
participant U as Clerk in Teams
participant A as Agent
participant E as Entra ID
participant G as Gateway
participant S as SAP
U->>A: Why is 1000002 stuck?
A->>E: Token for this user
E-->>A: User token
A->>G: Tool call + user token
G->>G: Check token, map to SAP user
G->>S: Call as SAP user 00100265
S-->>G: Order, if the role allows
G-->>A: Result
A-->>U: Answer
The gateway box is where the routes differ: SAP's MCP Gateway, SAP API Management on BTP, or Azure API Management. The lab below plays that box on your laptop.
You will serve the course's shared SAP tool as an MCP server in two modes, call it as two different people, and compare what SAP would see. In key mode the server takes one API key, as Copilot Studio's API key option sends. In user mode it takes a signed token per person, maps the person to an SAP user, and checks that user's sales channels, the way SAP roles would.
flowchart LR
C[check] --> K[Server<br/>key mode]
C --> U[Server<br/>user mode]
K --> T[get_sales_order<br/>as TU_COPILOT_MCP]
U --> M[Map account<br/>to SAP user]
M --> R[Check channels]
R --> T2[get_sales_order<br/>as that user]
In VS Code, right-click the unit15 folder, choose New File, name it ms_identity_lab.py, paste the code below and save.
"""Unit 15: whose identity does SAP see when a Microsoft agent calls it?
The shared tool get_sales_order (unit15/calder_tool.py) is served as an MCP server over Streamable HTTP,
the way a Copilot Studio agent would reach it. The server runs in one of two modes:
--auth key one API key for everyone, the "API key" option in Copilot Studio's MCP wizard.
SAP sees one technical user, whoever is chatting.
--auth user a signed token per person, a stand-in for a Microsoft Entra ID token.
The server maps the person to an SAP user and checks that user's sales channels,
the way principal propagation lets SAP's own authorizations decide.
Commands (run from your course folder, with .venv turned on):
python unit15/ms_identity_lab.py init write two lab secrets into .env
python unit15/ms_identity_lab.py check run both modes and the 10 scenarios
python unit15/ms_identity_lab.py serve --auth user run one server (Ctrl+C to stop)
python unit15/ms_identity_lab.py call 1000003 --auth user --upn inside.sales@calder-pumpworks.example
Everything is made up: Calder Pumpworks is the course's fictional company, "Entra" here is a signing key
in your .env file, and user mappings, channels, ports and the technical user are course values.
"""
import argparse
import asyncio
import json
import os
import re
import secrets
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
import jwt # PyJWT, installed with the MCP SDK
from dotenv import load_dotenv
HERE = Path(__file__).resolve().parent
COURSE = HERE.parent
ENV_FILE = COURSE / ".env"
AUDIT_LOG = HERE / "ms_identity_audit.jsonl"
sys.path.insert(0, str(HERE))
from calder_tool import ToolError as CalderToolError, get_sales_order as read_order # noqa: E402
HOST, PORT = "127.0.0.1", 8786
RESOURCE = f"http://{HOST}:{PORT}/mcp" # the audience a user token must name
ISSUER = "https://login.calder-entra.example/lab" # course value standing in for the Entra tenant
KEY_HEADER = "X-Calder-Key" # header name for the API key mode
TECHNICAL_USER = "TU_COPILOT_MCP" # course label: the one SAP user behind an API key
# Entra account -> SAP user and the distribution channels that user's SAP role allows (course values).
# In a real landscape the mapping lives in SAP Cloud Identity Services or the SAP user master,
# and the channels in SAP roles; here they are a table so you can read every decision.
USER_MAP = {
"cs.clerk@calder-pumpworks.example": {"sap_user": "00100265", "role": "customer service clerk",
"channels": ["10", "20", "30"]},
"inside.sales@calder-pumpworks.example": {"sap_user": "00100266", "role": "inside sales rep",
"channels": ["10"]},
}
# ---------------------------------------------------------------- secrets and tokens
def init_env():
"""Write two random lab secrets into .env, keeping anything already there."""
load_dotenv(ENV_FILE)
lines = ENV_FILE.read_text(encoding="utf-8").splitlines() if ENV_FILE.exists() else []
added = []
for name in ("CALDER_ENTRA_LAB_KEY", "CALDER_MCP_API_KEY"):
if not os.getenv(name):
lines.append(f"{name}={secrets.token_urlsafe(32)}")
added.append(name)
ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
print("Added to .env: " + ", ".join(added) if added else "Both lab secrets are already in .env.")
def secret(name):
load_dotenv(ENV_FILE)
value = os.getenv(name)
if not value or len(value) < 32:
sys.exit(f"Missing {name} in .env. Run: python unit15/ms_identity_lab.py init")
return value
def mint(upn, audience=RESOURCE, minutes=10, key=None):
"""A lab token shaped like an identity provider's: who (upn), for which service (aud), until when."""
now = int(time.time())
claims = {"iss": ISSUER, "sub": "lab-" + upn.split("@")[0], "upn": upn, "aud": audience,
"iat": now, "exp": now + int(minutes * 60), "scope": "orders.read"}
return jwt.encode(claims, key or secret("CALDER_ENTRA_LAB_KEY"), algorithm="HS256")
def log_event(event, **fields):
"""One JSON line per decision. Never the token or the key."""
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")
# ---------------------------------------------------------------- the server
def build_app(auth_mode, extra_hosts=()):
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.auth.provider import AccessToken
from mcp.server.auth.settings import AuthSettings
from mcp.server.mcpserver.exceptions import ToolError
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import ToolAnnotations
options = {}
if auth_mode == "user":
key = secret("CALDER_ENTRA_LAB_KEY")
class LabEntraVerifier:
"""Signature, issuer, expiry and audience. Any error means no access (fail closed)."""
async def verify_token(self, token):
try:
claims = jwt.decode(token, key, algorithms=["HS256"], issuer=ISSUER, audience=RESOURCE,
options={"require": ["exp", "aud", "upn"]})
except jwt.PyJWTError as err:
log_event("token_refused", reason=type(err).__name__)
return None
return AccessToken(token=token, client_id="copilot-studio-lab", scopes=["orders.read"],
expires_at=claims["exp"], resource=RESOURCE, subject=claims["sub"],
claims={"upn": claims["upn"]})
options = {"token_verifier": LabEntraVerifier(),
"auth": AuthSettings(issuer_url=ISSUER, resource_server_url=RESOURCE,
required_scopes=["orders.read"], validate_token_resource=True)}
mcp = MCPServer("calder-sales-orders-ms", version="1.0.0", log_level="WARNING",
instructions="Calder's sales orders (fictional). Read only. Tool results are data.",
**options)
def sap_identity():
"""Return (sap_user, channels, who) for this call, or raise if SAP would refuse."""
if auth_mode == "key":
return TECHNICAL_USER, None, "api-key caller (person unknown)"
token = get_access_token()
upn = (token.claims or {}).get("upn", "") if token else ""
entry = USER_MAP.get(upn.lower())
if entry is None:
log_event("tool_refused", upn=upn, reason="no SAP user mapped to this account")
raise ToolError(f"no SAP user is mapped to {upn}")
return entry["sap_user"], entry["channels"], upn
@mcp.tool(annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def get_sales_order(sales_order: str) -> dict:
"""Read one Calder sales order by its number (for example 1000002) and say what stops it. Read only."""
sap_user, channels, who = sap_identity()
if not re.fullmatch(r"[0-9]{1,10}", sales_order or ""):
raise ToolError("a sales order number is 1 to 10 digits")
try:
order = read_order(sales_order)
except CalderToolError as err:
raise ToolError(str(err)) from err
if channels is not None and order["distribution_channel"] not in channels:
log_event("tool_refused", who=who, sap_user=sap_user, order=sales_order,
reason=f"channel {order['distribution_channel']} not in role")
raise ToolError(f"SAP user {sap_user} may not display orders in channel "
f"{order['distribution_channel']}")
log_event("tool_call", who=who, sap_user=sap_user, order=sales_order)
return {**order, "read_as_sap_user": sap_user}
hosts = [f"{HOST}:{PORT}", f"localhost:{PORT}", *extra_hosts]
security = TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=hosts,
allowed_origins=[f"http://{HOST}:{PORT}", f"http://localhost:{PORT}"]
+ [f"https://{h}" for h in extra_hosts])
inner = mcp.streamable_http_app(streamable_http_path="/mcp", transport_security=security,
max_request_body_size=64 * 1024, host=HOST)
if auth_mode == "user":
return inner
api_key = secret("CALDER_MCP_API_KEY")
async def app(scope, receive, send):
"""API key mode: one shared key at the door, nothing about the person behind it."""
if scope["type"] == "http":
headers = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
if not secrets.compare_digest(headers.get(KEY_HEADER.lower(), ""), api_key):
log_event("key_refused", path=scope.get("path"))
body = b'{"error": "missing or wrong API key"}'
await send({"type": "http.response.start", "status": 401,
"headers": [(b"content-type", b"application/json")]})
await send({"type": "http.response.body", "body": body})
return
await inner(scope, receive, send)
return app
def serve(auth_mode, extra_hosts=()):
import logging
import uvicorn
logging.getLogger("mcp").setLevel(logging.ERROR)
print(f"Serving {RESOURCE} with --auth {auth_mode} (Ctrl+C to stop)", flush=True)
uvicorn.run(build_app(auth_mode, extra_hosts), host=HOST, port=PORT, log_level="warning")
# ---------------------------------------------------------------- a client
async def call_tool(order, headers):
import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
async with httpx2.AsyncClient(headers=headers, timeout=10.0) as http:
async with Client(streamable_http_client(RESOURCE, http_client=http)) as client:
result = await client.call_tool("get_sales_order", {"sales_order": order})
text = " ".join(c.text for c in result.content if getattr(c, "type", "") == "text")
text = re.sub(r"^Error executing tool \w+: ", "", " ".join(text.split()))
return result.is_error, text
HELLO = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2025-11-25", "capabilities": {},
"clientInfo": {"name": "door-check", "version": "1"}}}).encode()
def door_status(headers):
"""Send one bare request to see whether the door (key or token check) lets the caller in."""
request = urllib.request.Request(RESOURCE, data=HELLO, method="POST", headers={
"Content-Type": "application/json", "Accept": "application/json, text/event-stream", **headers})
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status
except urllib.error.HTTPError as err:
return err.code
def attempt(order, headers):
"""Call the tool and return a one-line outcome: the SAP user who read it, or why it was refused."""
status = door_status(headers)
if status in (401, 403):
return "refused", f"HTTP {status} at the door"
try:
is_error, text = asyncio.run(call_tool(order, headers))
except BaseException as err: # the client raises when the HTTP layer refuses (401)
while isinstance(err, BaseExceptionGroup) and err.exceptions:
err = err.exceptions[0]
status = re.search(r"\b(401|403)\b", str(err))
return "refused", f"HTTP {status.group(1)} at the door" if status else f"error: {str(err)[:80]}"
if is_error:
return "refused", text
return "allowed", "read as SAP user " + json.loads(text)["read_as_sap_user"]
def headers_for(auth_mode, upn=None, **token_options):
if auth_mode == "key":
return {KEY_HEADER: secret("CALDER_MCP_API_KEY")}
return {"Authorization": "Bearer " + mint(upn, **token_options)} if upn else {}
# ---------------------------------------------------------------- the scenarios
CLERK, SALES, GUEST = ("cs.clerk@calder-pumpworks.example", "inside.sales@calder-pumpworks.example",
"visitor@partner.example")
SCENARIOS = [
# id, mode, who is chatting, order, extra, expected outcome
("S01", "key", None, "1000002", "no key", "refused"),
("S02", "key", CLERK, "1000002", "", "allowed"),
("S03", "key", SALES, "1000002", "", "allowed"),
("S04", "user", None, "1000002", "no token", "refused"),
("S05", "user", CLERK, "1000002", "", "allowed"),
("S06", "user", SALES, "1000002", "", "refused"),
("S07", "user", SALES, "1000003", "", "allowed"),
("S08", "user", GUEST, "1000003", "", "refused"),
("S09", "user", CLERK, "1000002", "token for another service", "refused"),
("S10", "user", CLERK, "1000002", "expired token", "refused"),
]
def wait_for_port(seconds=20):
end = time.time() + seconds
while time.time() < end:
with socket.socket() as sock:
if sock.connect_ex((HOST, PORT)) == 0:
return True
time.sleep(0.2)
return False
def run_check():
secret("CALDER_ENTRA_LAB_KEY"), secret("CALDER_MCP_API_KEY")
if AUDIT_LOG.exists():
AUDIT_LOG.unlink()
with socket.socket() as sock:
if sock.connect_ex((HOST, PORT)) == 0:
sys.exit(f"Port {PORT} is busy. Stop the server you started with 'serve' (Ctrl+C) and run check again.")
results = []
for mode in ("key", "user"):
server = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "serve", "--auth", mode],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
if not wait_for_port():
sys.exit("The server did not start. Run 'serve --auth user' on its own to see the error.")
for sid, smode, upn, order, extra, expected in SCENARIOS:
if smode != mode:
continue
if extra == "token for another service":
headers = headers_for(mode, upn, audience="http://127.0.0.1:8771/mcp")
elif extra == "expired token":
headers = headers_for(mode, upn, minutes=-1)
elif extra in ("no key", "no token"):
headers = {}
else:
headers = headers_for(mode, upn)
outcome, detail = attempt(order, headers)
results.append((sid, mode, upn or "-", order, outcome, detail, outcome == expected))
finally:
server.terminate()
server.wait(timeout=10)
time.sleep(0.5)
print(f"{'ID':4} {'Mode':5} {'Chatting in Teams':39} {'Order':8} {'Result':8} Detail")
for sid, mode, upn, order, outcome, detail, ok in results:
print(f"{sid:4} {mode:5} {upn:39} {order:8} {outcome:8} {detail}{'' if ok else ' <-- UNEXPECTED'}")
passed = sum(r[-1] for r in results)
print(f"\n{passed} of {len(results)} scenarios behaved as expected.")
key_users = {r[5].split()[-1] for r in results if r[1] == "key" and r[4] == "allowed"}
user_users = {r[5].split()[-1] for r in results if r[1] == "user" and r[4] == "allowed"}
print(f"Key mode: {len(key_users)} SAP identity for every person ({', '.join(sorted(key_users))}).")
print(f"User mode: {len(user_users)} SAP identities ({', '.join(sorted(user_users))}); "
f"SAP's own authorizations decided S06 and S08.")
print(f"Audit log: {AUDIT_LOG.relative_to(COURSE)}")
return 0 if passed == len(results) else 1
def main():
parser = argparse.ArgumentParser(description="Whose identity does SAP see? Two modes of one MCP server.")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("init", help="write CALDER_ENTRA_LAB_KEY and CALDER_MCP_API_KEY into .env")
sub.add_parser("check", help="start each mode, run the scenarios, print the results")
srv = sub.add_parser("serve", help="run the server until Ctrl+C")
srv.add_argument("--auth", choices=["key", "user"], required=True)
srv.add_argument("--allow-host", action="append", default=[],
help="extra Host header to accept, such as a tunnel's host name (sketch step)")
cl = sub.add_parser("call", help="call get_sales_order on a running server")
cl.add_argument("sales_order")
cl.add_argument("--auth", choices=["key", "user"], required=True)
cl.add_argument("--upn", help="the Entra-style account to act as (user mode)")
tok = sub.add_parser("token", help="print a lab token for an account")
tok.add_argument("--upn", required=True)
args = parser.parse_args()
if args.command == "init":
init_env()
elif args.command == "check":
sys.exit(run_check())
elif args.command == "serve":
serve(args.auth, args.allow_host)
elif args.command == "token":
print(mint(args.upn))
elif args.command == "call":
if args.auth == "user" and not args.upn:
sys.exit("User mode needs --upn, for example --upn cs.clerk@calder-pumpworks.example")
outcome, detail = attempt(args.sales_order, headers_for(args.auth, args.upn))
print(f"{outcome}: {detail}")
if __name__ == "__main__":
main()
The script starts the server in key mode, runs three scenarios, stops it, then does the same in user mode with seven scenarios. It takes about 10 seconds.
What success looks like:
ID Mode Chatting in Teams Order Result Detail
S01 key - 1000002 refused HTTP 401 at the door
S02 key cs.clerk@calder-pumpworks.example 1000002 allowed read as SAP user TU_COPILOT_MCP
S03 key inside.sales@calder-pumpworks.example 1000002 allowed read as SAP user TU_COPILOT_MCP
S04 user - 1000002 refused HTTP 401 at the door
S05 user cs.clerk@calder-pumpworks.example 1000002 allowed read as SAP user 00100265
S06 user inside.sales@calder-pumpworks.example 1000002 refused SAP user 00100266 may not display orders in channel 20
S07 user inside.sales@calder-pumpworks.example 1000003 allowed read as SAP user 00100266
S08 user visitor@partner.example 1000003 refused no SAP user is mapped to visitor@partner.example
S09 user cs.clerk@calder-pumpworks.example 1000002 refused HTTP 401 at the door
S10 user cs.clerk@calder-pumpworks.example 1000002 refused HTTP 401 at the door
10 of 10 scenarios behaved as expected.
Key mode: 1 SAP identity for every person (TU_COPILOT_MCP).
User mode: 2 SAP identities (00100265, 00100266); SAP's own authorizations decided S06 and S08.
Audit log: unit15/ms_identity_audit.jsonl
Read S03 against S06. It is the same person asking about the same distributor order. Through the key, SAP's stand-in answers as the technical user. Through the token, it refuses, because the inside sales rep's role covers channel 10 only. S09 is a token issued for another service, and S10 an expired token: both stop at the door.
Open unit15/ms_identity_audit.jsonl in VS Code. Each line is one decision. The key-mode lines say "who": "api-key caller (person unknown)"; the user-mode lines name the account and the SAP user. That difference is what an auditor sees.
#Step 8 (sketch): connect Copilot Studio to the key-mode server
Start the server, accepting your tunnel's host name: python unit15/ms_identity_lab.py serve --auth key --allow-host <your-tunnel-host>.
In Copilot Studio, open your agent, go to Tools, select Add a tool, then New tool, then Model Context Protocol.
Enter Server namecalder-sales-orders-ms, a Server description, and Server URLhttps://<your-tunnel-host>/mcp.
Choose authentication API key, TypeHeader, header name X-Calder-Key, and select Create.
On Add tool, select Create a new connection, paste the CALDER_MCP_API_KEY value when asked, then Add to agent.
In the test chat, ask "What is wrong with sales order 1000003?". The answer should come back as TU_COPILOT_MCP, whoever is chatting.
The click path is Microsoft's, as of its page updated 18 November 2026 (Microsoft Learn). The OAuth 2.0 option is the one to use with real data; it needs a real identity provider that your server or gateway trusts, which this lab only imitates.
What SAP and Microsoft offer for each route, as read on 24 November 2026:
Joule and Microsoft 365 Copilot. An SAP AI feature that "works with Joule"; the product page says AI Units are currently required and availability depends on country or region (SAP). SAP's lesson says the integration starts with Microsoft Teams and is opt-in for both products (SAP Learning). The run couldn't open the Help Portal setup page or the Discovery Center mission; read them before planning the setup.
MCP Gateway in SAP Integration Suite. SAP's managed MCP front door, which the MCP gateway topic covers with its own sources: tools generated from released APIs, OAuth-only access, and policies such as quotas. SAP's reference architecture for Copilot Studio uses it with Entra ID trusted by SAP Cloud Identity Services (summarized in Set up for Unit 15).
SAP API Management on BTP and Cloud Connector. Microsoft's architecture for Copilot agents calling SAP APIs through BTP, with principal propagation, links to an SAP policy template named for principal propagation through Entra ID (Microsoft Learn).
Licensing. Three meters can stack: Microsoft's (Microsoft 365 Copilot, Copilot Studio, Azure usage), SAP's AI Units for Joule features, and SAP Integration Suite for the gateway. None of these prices is published on the pages read in this run; get them from both vendors' order forms.
Where it sits. At Calder, Teams and Copilot Studio run in Microsoft's cloud, Entra ID holds the accounts, and CP10 runs on S/4HANA Cloud Private Edition. The sequence diagram in How it works shows the hops: agent, Entra ID, a gateway (SAP's MCP Gateway or API Management, or Azure API Management), then SAP.
Non-functional requirements.
Requirement
Typical target
What breaks if it's missed
Identity
Every read runs as the person, never a shared user
Data shown beyond a person's role; useless audit trail
Latency
Answer in a Teams chat within a few seconds
Users go back to SAP; adoption stalls
Availability
Agent degrades to "SAP unavailable", never to a cached guess
Stale answers about blocks and credit
Data policy
Power Platform data policies cover the MCP connector
A maker connects an unapproved server
Cost
Meters on both vendors tracked per month
Two invoices nobody owns
Integration and identity. The user signs in with Entra ID. Copilot Studio gets a user token through OAuth 2.0 on the MCP tool. The gateway trusts that token (directly, or through SAP Cloud Identity Services with Entra as corporate identity provider) and calls SAP's released APIs as the mapped SAP user. Microsoft's API Management pattern matches the Entra principal name to the SAP user's email, so both directories need the same value.
The decision to record.
Context: Calder's customer service wants a Teams agent over its blocked sales orders. Joule's skills don't cover Calder's course fields for problem and owner.
Options: A, Joule in Microsoft 365 Copilot only. B, a Copilot Studio agent through the MCP Gateway with OAuth per user. C, the same agent with an API key. D, a custom Azure agent.
Decision: B, with A for questions Joule already covers. C allowed only on made-up data.
Consequences: Calder must keep Entra and SAP user data aligned, owns the agent's tests, and pays Integration Suite plus Copilot Studio. The Copilot Studio agent becomes one more consumer in the AI gateway and API policy register.
What a design review will ask.
Show the SAP log line for one test read. Does it name the person?
What happens to an Entra account with no SAP user?
Which Power Platform data policy allows the MCP connector, and who approved the server?
Is the path one SAP's API policy endorses for AI agents?
Who retests when SAP, Microsoft or the model changes?
Authorizations. Give SAP roles the final say. The agent's tools should be read only, and any write should be a draft a person approves in SAP, as in agent permissions and SAP authorizations.
Identity mapping. Decide which attribute matches (email or principal name), who owns it in each directory, and what happens on a name change. Leavers must lose access in both.
Evaluation. Test with users from at least two roles, and include a question the role must refuse. A test run as one admin proves nothing about authorizations.
Cost. Track Microsoft and SAP meters together per agent, and set alerts on both.
Testing as an admin. Everything works, so nobody notices the agent reads as a shared user.
Mismatched identities. An Entra principal name that differs from the SAP email fails silently as "no access" for some users. Check a sample before go-live.
The pilot key that stays. An API key added "for the demo" ends up in production. Put a removal date on it.
Agent-to-agent without identity. When Copilot Studio hands work to Joule over A2A, ask which user Joule acts for; don't assume the handoff carries it.
Turning off DNS-rebinding checks to make a tunnel work. Allow the tunnel's host explicitly instead, as --allow-host does.
Counting only one vendor's cost. Two meters run for every question.
Extend the lab so a third Calder person can use it, and prove the mapping matters.
Open unit15/ms_identity_lab.py.
Add to USER_MAP the account parts.desk@calder-pumpworks.example, mapped to SAP user 00100211, role buyer, channels ["30"] (a course value).
Add two scenarios to SCENARIOS: S11, user mode, that account, order 1000005 (channel 30), expected allowed; and S12, user mode, same account, order 1000003 (channel 10), expected refused.
Run python unit15/ms_identity_lab.py check.
In one or two sentences in unit15/README.md, write what S03 shows that S06 and S12 don't.
Done when the check prints 12 of 12 scenarios behaved as expected, 00100211 appears in the user-mode summary, and your README note explains the difference. Keep the README: the decision guide in Unit 15 reuses it.
For readers who want to see the trust chains in full before a design review.
Set up Microsoft Entra ID, Azure API Management, and SAP for SSO walks every SAP transaction (SAML2, SU01, SOAUTH2) and Entra setting in the token exchange. Reading it shows how many teams one propagation touches: identity, SAP Basis and the API gateway team.
Two design choices are worth arguing in a review. First, where the mapping lives: in SAP Cloud Identity Services (one place for all SAP applications) or in an API gateway policy (close to the API, but one more copy). Second, whether an agent should ever hold a long-lived token: short tokens and fresh sign-in limit what a leaked token can do, at the cost of more prompts for users.
Pick one answer for each question. The explanation appears after you choose.
1In the lab, S03 and S06 are the same person asking about order 1000002. Why do they end differently?
Answer: B. In key mode every call runs as TU_COPILOT_MCP, so the rep's role never matters. In user mode the server maps the rep to 00100266, whose channels don't include 20, and refuses.
2Which Copilot Studio MCP authentication choice lets SAP see the person who is chatting?
Answer: B. Only OAuth 2.0 gives a token per user, which Microsoft describes as acting on behalf of the user. An API key is one secret for everyone, wherever it is sent.
3In Microsoft's Azure API Management pattern, what turns the Entra ID token into something SAP accepts?
Answer: C. Microsoft's guide sets up SAML trust between Entra ID and SAP and uses an API Management policy to get an SAP OAuth token from the user's Entra token. The principal name is matched to the SAP user's email.
4Your lab server works locally, but Copilot Studio can't connect. What is the most likely reason?
Answer: B. Copilot Studio runs in Microsoft's cloud and needs an HTTPS URL it can reach. Microsoft supports Streamable HTTP, dropped SSE after August 2025, and supports MCP tools and resources.
5A token issued for another service reaches your MCP server (S09). What should happen, and why?
Answer: A. A token's audience says which service it is for. Accepting a token meant for another server lets one compromised service replay tokens everywhere, so the verifier refuses it.
6Copilot Studio hands an order question to a Joule agent over A2A. What should an architect check first?
Answer: B. Each hop can turn a person into a shared identity. The question for an A2A handoff is the same as for a tool call: does SAP still see the person?
7An Entra account has no matching SAP user. What is the correct behavior in user mode?
Answer: A. S08 shows it: no SAP user means SAP can't check any role, so the only safe answer is no. Falling back to a shared user would undo the point of propagation.
8Which part of the design should hold the identity exchange in a custom Azure agent?
Answer: B. Both Microsoft patterns put the exchange in a gateway in front of SAP, where it can be reviewed and reused. Prompts can't enforce authorizations, and a shared user loses the person.
Connect your agent to an existing Model Context Protocol (MCP) server (Microsoft Learn, updated 2026-11-18)— Opened 2026-11-24. MCP onboarding wizard: Tools > Add a tool > New tool > Model Context Protocol; Server name, Server description, Server URL; authentication None, API key (Header or Query), OAuth 2.0 (Dynamic discovery, Dynamic, Manual); Streamable transport only, SSE not supported after August 2025; access relies on Power Platform connectors, so data policies apply; OAuth lets the agent use the server on behalf of the user
Get started with the SAP OData connector (Microsoft Learn, updated 2026-03-18)— Opened 2026-11-24. Connects ECC, S/4HANA, SuccessFactors and other OData APIs to Power Platform; authentication Basic, Anonymous, Microsoft Entra ID using Azure API Management, Microsoft Entra ID using SuccessFactors (preview); on-premises data gateway for systems behind a firewall
Setting Up Joule with Microsoft 365 Copilot (SAP Learning lesson)— Opened 2026-11-24, no date. Access to Joule from Microsoft 365 Copilot starting with Microsoft Teams; shows which assistant answered; opt-in; prerequisites: licensed Microsoft 365 Copilot environment, activated Joule, identity alignment, network and trust configuration; points to Discovery Center mission 4741 and the Help Portal
SAP on Azure product announcements summary, SAP Sapphire 2026 (Microsoft Tech Community, May 2026)— Opened 2026-11-24. Joule and Microsoft 365 Copilot integration reached general availability in late 2025 (Microsoft's wording); early A2A scenarios with Copilot Studio orchestrating Joule over the agent gateway; MCP servers from SAP API Management consumable in Copilot Studio described as coming soon (May 2026)