Orchestrate

Report an issue

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

0 / 2000

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

The Integration Suite MCP gateway, hands-on

Turn a released API into a governed MCP server with OAuth, scopes, quotas and trimmed tools, build the same gateway locally, and call it from the course client.

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

The 60-second version

An AI agent that needs SAP data has to call something. If every team connects its agent straight to an SAP API, each one handles its own keys, limits and logging, and nobody sees the whole picture.

SAP Integration Suite now offers a middle layer for this: the MCP gateway. You take an API you already run, pick the operations an agent may use, and publish them as an MCP server. MCP (Model Context Protocol) is the open standard agents use to discover and call tools.

The gateway then does what an API gateway does, for agents:

  • Who is calling? Every call needs an OAuth token.
  • May they? The token must carry the right scope.
  • How much? Quotas and surge limits stop runaway loops.
  • What do they see? Only the tools and fields you chose.
  • What happened? Every call is logged and shows up in analytics.

As of November 2026, SAP lists this as generally available since July 2026, with availability tied to your Integration Suite service plan.

Why it matters to the business

Take Calder Pumpworks, the fictional pump maker this course follows. Its customer service team wants an agent that explains stuck sales orders: credit blocks, missing billing data, delivery holds. The data sits behind a released sales order API.

Without a gateway, the agent's developer gets an API credential and wires it in. Three problems follow:

  • No business-sized limit. An agent stuck in a loop can call the API thousands of times. Nothing stops it before the backend team notices.
  • Too much surface. The API can change orders as well as read them. The agent only needs to read. With direct access, the write sits one prompt away.
  • No shared view. Security can't see which agents call which systems, how often, or for whom.

The MCP gateway turns those into configuration. The agent sees two read tools, not the whole API. A surge policy caps bursts. Every call is logged with the agent's identity. And the next agent reuses the same governed MCP server instead of building its own connection.

There is a cost side too. Backend APIs return many fields an agent never needs, and every field is text the model reads on each call. SAP's gateway lets you hide fields and code values from the agent's view, which SAP says cuts token use and wrong parameter choices.

How SAP does it

As of November 2026, SAP's Integration Suite documentation describes the MCP server as its own artifact type, built and deployed like an API or an integration flow. The MCP gateway is the runtime that serves it. The pieces:

Piece What it does Status per SAP's What's New
MCP server from an API artifact Publishes chosen operations of an OData or REST API you already manage GA 2026-07-05
MCP server from an HTTP endpoint Same, from any HTTPS service plus its OpenAPI description Documented; on-premise principal propagation GA 2026-07-26
MCP server from RFCs Publishes remote-enabled function modules from SAP ECC or S/4HANA through Cloud Connector Documented
MCP server from a remote MCP server Puts someone else's MCP server behind SAP's policies GA 2026-09-20
Developer Hub subscriptions Agents subscribe to a product and get their own client credentials GA 2026-07-05
Tool simplification Hide parameters and code values, rename and re-describe tools GA 2026-10-18
Analytics Health and usage per MCP server, including agent calls and errors GA 2026-07-05

Dates come from SAP's What's New for API Management. Rows marked "Documented" appear in SAP's guides without a dated entry of their own.

Two conditions decide whether you can use it. The MCP server runs only on the Integration Cell runtime, which SAP activates in designated regions and clouds. And availability depends on your service plan (SAP Note 2903776). As of November 2026, SAP's tutorial lists the MCP server for the Enhanced, Premium and Trial plans. SAP's MCP gateway tutorial runs on the BTP trial but says productive use needs the Premium or Enhanced Edition. Check both notes before you plan a pilot.

SAP's agent routes fit together like this. Agents built inside SAP use Joule Studio. Outside agents that need SAP's own agents go through the Agent Gateway, covered in AI gateways. Outside agents that need SAP APIs as tools use the MCP gateway, the subject of this topic.

A day in the life of one governed MCP server

Who Does what Where
Integration developer Creates an MCP server from Calder's sales order API, picks two read operations, hides technical fields Integration Suite, Design
Security architect Keeps the default Authentication and Authorization policies, sets the required scope, adds a surge limit Integration Suite, Policies
API product owner Publishes the server in a product with a short description of what it's for Developer Hub
Agent developer Subscribes the order exception agent, gets a client ID and secret, configures the agent Developer Hub, agent host
Agent at runtime Gets a token, lists two tools, reads order 1000002, explains the credit block MCP gateway
Operations Watches calls, errors and response times per agent; investigates a burst of 429 refusals Integration Suite, Monitor and Analyze

The order matters. Scope, tools and limits are decided before the first agent connects, not after an incident.

Questions to ask

  1. Is the MCP server feature in our Integration Suite service plan, and is Integration Cell available in our region?
  2. Which existing API or RFC will each MCP server publish, and is that interface released and supported?
  3. Does each call run as a technical user or as the signed-in person? Which SAP roles back that identity?
  4. Which operations and fields will the agent see, and who signed that off?
  5. What surge and quota limits fit the business volume, and who gets alerted when an agent hits them?
  6. Where do we see calls per agent, and how long do we keep those logs?
  7. Who reviews a tool definition when the source API changes?
  8. For outside agents, does the route match what SAP's API policy allows for AI access? (The policy is covered in SAP's tools for agents.)

Common misconceptions

  • "The MCP gateway gives the agent SAP authorizations." It checks a token and a scope. What the agent may do inside S/4HANA still depends on the user or technical user behind the call.
  • "Publishing an API as MCP means publishing all of it." You choose operations one by one, up to 50 per server, and can hide fields and values.
  • "A quota is a security control." It limits volume. It doesn't stop a permitted agent from reading data it shouldn't use for a task.
  • "If it works on the trial, we're ready for production." SAP's tutorials use the trial for learning. Productive use needs the Premium or Enhanced Edition, with Integration Cell in your region.
  • "An agent framework can connect any way it likes." SAP recommends Developer Hub credentials and calls the Process Integration Runtime key route an anti-pattern.

Key terms

All course terms, A to Z, in the glossary

  • MCP server: a service that offers tools, resources and prompts to AI agents over the Model Context Protocol.
  • MCP gateway: the Integration Suite runtime that serves MCP servers and applies policies to their calls.
  • Integration Cell: SAP's managed cloud runtime in Integration Suite where API and MCP server artifacts are deployed.
  • API artifact: an API managed in Integration Suite, with its own policies, that an MCP server can use as its source.
  • Developer Hub: the catalog where products containing APIs and MCP servers are published and subscribed to.
  • Scope: a permission name carried in an OAuth token and checked by the Authorization policy.
  • Surge protection: a policy that refuses requests above a rate within a short interval.
  • Quota: a policy that caps the number of requests over a longer period, such as a day.
  • Tool simplification: hiding parameters and code values from an MCP tool without changing the source API.

Check yourself

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

1What does SAP Integration Suite's MCP gateway add on top of an API Calder already runs?

Answer: D. The gateway reuses an existing API or RFC and puts governance in front of it: OAuth, scopes, quotas, surge limits and logging. SAP authorizations inside S/4HANA still come from the identity behind the call.

2Calder's agent only needs to read orders, but the API can also change them. What is the right move?

Answer: A. Tools are chosen operation by operation. An operation that is not published can't be called through the MCP server, which is far stronger than an instruction in a prompt.

3Before planning a pilot, which two conditions should a leader confirm?

Answer: C. SAP ties the feature to the service plan (SAP Note 2903776), and MCP servers run only on Integration Cell, which SAP activates in designated regions. A trial is for learning, not for a productive pilot.

4Why does a quota on an MCP server not settle the question of what the agent may see?

Answer: C. A quota caps how many calls an agent makes. Which data it sees is decided by the published tools and fields, the scope check and the user or technical user behind the call.

5An agent hits HTTP 429 refusals every morning at 08:00. Who should look first, and where?

Answer: C. A 429 from the gateway means a surge or quota policy refused calls. Monitoring and analytics show which agent, which server and which limit, so the team can fix the agent's behavior or resize the limit.

6Why does SAP offer to hide fields and code values in MCP tools?

Answer: D. SAP explains that full backend schemas cost tokens on every call and confuse agents with raw values. Hiding is non-destructive: the source API stays unchanged.
Deep layer · 40 min read

Mental model: an API proxy that speaks MCP

If you have built an API proxy, you already know most of this. An MCP server in Integration Suite is a proxy whose front door speaks MCP instead of REST. Behind the door, it calls an API, an HTTP endpoint, RFCs or another MCP server. In between sits the same policy chain that API Management has always run.

flowchart LR
  A[Agent<br/>MCP client] -->|MCP + bearer token| S[MCP sender adapter]
  S --> P[Policies<br/>authentication, authorization,<br/>IP filter, surge, quota]
  P --> T[Tool definitions<br/>chosen, trimmed]
  T --> R[HTTP receiver adapter]
  R --> B[(Source: API artifact,<br/>HTTP endpoint, RFC,<br/>remote MCP server)]

Three ideas follow from that picture:

  1. The tool list is a design decision. Tools are generated from the source's operations, but you choose which, rename them, describe them and trim them. An operation you leave out does not exist for the agent.
  2. Identity is decided twice. The gateway checks the agent's token and scope. The backend still checks the identity the gateway passes on: a technical user, or the signed-in person through principal propagation.
  3. Everything else is ordinary API operations. Versioning, transport between tenants, monitoring, analytics and limits work the way they do for API artifacts.

This topic builds the same chain on your computer, so you can see each check refuse a call, then shows the steps in a real tenant.

How it works

Where it runs

As of November 2026, an MCP server is an artifact you add to an integration package under Design > Integrations and APIs, and it deploys only to the Integration Cell runtime (Create an MCP Server from an API Artifact). SAP describes Integration Cell as a managed, Kubernetes-based cloud runtime for API and MCP server lifecycle management (Integration Cell). You activate it under Settings > Runtime, and only in designated BTP regions and cloud providers, listed in SAP Note 3769634 (Activate Integration Cell).

Each MCP server has two adapters. The MCP sender adapter receives agent requests and can't be changed. The HTTP receiver adapter calls the source, with a default timeout of 60,000 ms (Configure an MCP Server Created from an API Artifact).

Four sources

Source What you give it Constraints SAP documents
API artifact An OData or REST API artifact deployed on Integration Cell OpenAPI 3.0.0 to 3.0.3 (no Swagger 2.0); the API must use OAuth-based authentication
HTTP endpoint A URL or a BTP destination, plus an OpenAPI 3.0.x file you upload or generate Destination proxy type Internet or OnPremise; destination label IntegrationCell.Include
RFC An RFC destination through Cloud Connector; you search and pick function modules SAP ECC 6.0, SAP ECC 5.0 and SAP S/4HANA; Cloud Connector must allow the discovery modules and BAPI_TRANSACTION_COMMIT
Remote MCP server A destination to someone else's MCP server Destination proxy type Internet only

Sources: HTTP endpoint, RFC, remote MCP server.

Tools, resources and prompts

The MCP server page describes all three MCP building blocks:

  • Tools come from API operations: method, path, an input schema and an output schema. Up to 50 tools per server (raised from 15 to 30 on 2026-08-23 and to 50 on 2026-10-18).
  • Resources come from GET operations only, up to 15 per server.
  • Prompts you write yourself: a name, optional arguments, and user and assistant messages.

Tool simplification (GA 2026-10-18) lets you hide optional input and output attributes, hide individual code values, and rewrite names and descriptions. Hiding is non-destructive: the source API is unchanged, and a later Synchronize keeps your choices unless a hidden field became mandatory (MCP Server Tool Simplification). A response may hold up to 500,000 tokens (Limits).

Integration Suite speaks both current MCP revisions: 2025-11-25 (a session with an initialize handshake and an Mcp-Session-Id header) and 2026-07-28 (stateless, one request at a time), the second added on 2026-10-18. Connect with whichever your client is built on. The difference between the two is covered in Model Context Protocol.

The policy chain

Every MCP server starts with two policies that you can't delete (configure page):

  • Authentication must come first and must be OAuth-based. For a server built from an API artifact, it's inherited from that API and read-only. It validates tokens from BTP's XSUAA by default, or from an external OIDC identity provider (Authentication).
  • Authorization checks the token for an OAuth scope, a developer key (the subscription's client ID), or both. The default scope is API.invoke (Authorization).

You can add three more: IP Filter, Quota and Surge Protection. They differ in a way that matters for agents:

Policy Counts Window When exceeded
Quota Requests per application over a period such as an hour, day or month Fixed; refusals last until the window ends HTTP 429
Surge protection Requests reaching the API at runtime, regardless of client 200 ms to 10 s HTTP 429
IP filter Caller address against allowed or denied ranges (CIDR) n/a Refused

Sources: Quota, Surge Protection, IP Filter. SAP's MCP configuration page gives "4 calls every 10 seconds" per agent as a surge example.

One more setting avoids checking twice. If the source API artifact has its own Authorization policy, SAP recommends turning on Trust Upstream MCP Authorization there, so the check runs once at the MCP layer.

Identity: technical user or the person

sequenceDiagram
  participant U as User
  participant A as Agent host
  participant I as Identity provider
  participant G as MCP gateway
  participant S as S/4HANA
  A->>I: client credentials (technical user) or sign-in (user)
  I-->>A: access token
  A->>G: tools/call + bearer token
  G->>G: authentication, authorization, limits
  G->>S: call with technical user, or the user via principal propagation
  S-->>G: data the identity may see
  G-->>A: tool result

SAP documents two ways for an agent to connect (IdP user token, technical user token):

  • Technical user token. The agent uses client credentials. Every call runs with the technical user's permissions. Simple, and right for batch agents, but every person using the agent gets the same data.
  • IdP user token. The person signs in through the Authorization Code flow, and calls run with that person's permissions. With XSUAA, the user must exist in the subaccount's identity provider, and API.invoke has no default role collection, so an administrator builds one (XSUAA access). With an external identity provider, SAP lists SAP Cloud Identity Services, Okta, Auth0 and Microsoft Entra ID, with optional PKCE; for Entra ID and Auth0, user propagation by Authorization Code isn't directly supported (external IdP).

For the hop to an on-premise backend, a destination with PrincipalPropagation carries the user through Cloud Connector; SAP's What's New lists principal propagation for on-premise MCP flows as GA on 2026-07-26. SAP's July 2026 user group update still showed principal propagation on the roadmap, so check the feature in your tenant before you design around it.

Consumption through Developer Hub

The intended path is a product in Developer Hub. An application developer chooses Subscribe > Create New Subscription for Agent, enters a title and a Callback URL, and Developer Hub generates a client ID and secret (Subscribe to Products). The application's Overview tab shows Key, Secret and Token URL (credentials via Developer Hub). The other route, a Process Integration Runtime service key, SAP calls an anti-pattern (Invoke the MCP Server Endpoint URL).

That subscription is what makes per-agent limits and per-agent analytics possible: each agent has its own client ID.

Build it yourself: a governed MCP server on your computer

You will build a small MCP gateway that does what Integration Suite's does, in about 400 lines of Python you can read. It reads an OpenAPI description of a sales order API, publishes two of its four operations as tools, hides technical fields, and runs five policies in order. Then you call it from the course's MCP client and watch each policy refuse something.

flowchart LR
  C[gateway_client.py<br/>the agent side] -->|1. client ID + secret| TK[/oauth/token/]
  TK -->|token| C
  C -->|2. MCP + bearer token| GW[mcp_gateway.py<br/>policies, tools, log]
  GW -->|3. own backend key| API[calder_sales_api.py<br/>4 operations]
  GW --> L[(gateway_log.jsonl)]

Before you start: complete Set up your computer for this course and Set up for Unit 5B. This lab also needs the MCP Python SDK; if you have done Set up for Unit 9, you have it.

What you need

  • Your orchestrate-course folder with .venv and a unit5b folder.
  • Python 3.10 or later. No accounts and no cost; nothing leaves your computer.
  • About 45 minutes.

The API is a stand-in. Its field names follow SAP's sales order API where the course has used them before (see calling your first SAP API); CustomerName, Problem and Owner are course fields. Orders 1000002 to 1000007 are the fictional open orders from order to cash. The agent names AGT_ORDER_EXC and AGT_SUPPLY_WATCH are the ones from AI gateways. Scopes, limits and ports are course values.

Step 1: Open the course folder and install the libraries

  1. Open VS Code, choose File > Open Folder and open orchestrate-course.

  2. Open a terminal with Terminal > New Terminal.

  3. Turn on the virtual environment if the prompt doesn't start with (.venv):

    • Windows (PowerShell):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate
  4. Open requirements.txt and make sure it has these two lines. If mcp[cli] or python-dotenv is already there without a version, replace that line:

    mcp[cli]==2.3.0
    python-dotenv==1.2.4
  5. Install:

    pip install -r requirements.txt
  6. Check that the SDK is version 2:

    python -c "import mcp, importlib.metadata as m; print(m.version('mcp'))"
    2.3.0

Step 2: Save the stand-in sales order API

This file plays the backend: four operations (list orders, read one order, change an order's date, read a customer's credit data) and its OpenAPI 3.0.3 description. It refuses any call without its own key, which only the gateway knows.

  1. In VS Code, right-click unit5b, choose New File, name it calder_sales_api.py, paste the code below and save.
"""Unit 5B: a local stand-in for a released sales order API, with its OpenAPI 3.0.3 description.

This is the "backend" that the lab's MCP gateway turns into MCP tools. It is NOT an SAP API:
field names follow SAP's sales order API where the course has used them before, and the
fields marked "course field" are made up. All data is Calder Pumpworks' fictional scenario.

You don't need to start this file yourself: mcp_gateway.py starts it on 127.0.0.1:8771.
To run it alone (for curious readers):
    python unit5b/calder_sales_api.py
"""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

HOST, PORT = "127.0.0.1", 8771
BACKEND_KEY = "calder-backend-key"   # course value: only the gateway knows it, never the agent

# Open orders from the order-to-cash topic (fictional). Amounts in USD; 1000005 has no price yet.
ORDERS = {
    "1000002": {"SoldToParty": "10000002", "CustomerName": "Hallam Fluid Systems", "DistributionChannel": "20",
                "RequestedDeliveryDate": "2026-10-30", "TotalNetAmount": "24288.00",
                "Problem": "credit block", "Owner": "Credit analyst"},
    "1000003": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "RequestedDeliveryDate": "2026-11-02", "TotalNetAmount": "12300.00",
                "Problem": "billing data incomplete", "Owner": "Sales order team"},
    "1000004": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "RequestedDeliveryDate": "2026-10-27", "TotalNetAmount": "24600.00",
                "Problem": "partly confirmed", "Owner": "Order fulfillment"},
    "1000005": {"SoldToParty": "10000002", "CustomerName": "Hallam Fluid Systems", "DistributionChannel": "30",
                "RequestedDeliveryDate": "2026-10-28", "TotalNetAmount": "",
                "Problem": "price missing", "Owner": "Pricing team"},
    "1000006": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "RequestedDeliveryDate": "2026-10-20", "TotalNetAmount": "4200.00",
                "Problem": "billing block", "Owner": "Billing clerk"},
    "1000007": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "DistributionChannel": "10",
                "RequestedDeliveryDate": "2026-11-09", "TotalNetAmount": "8400.00",
                "Problem": "delivery block", "Owner": "Customer service"},
}
CUSTOMERS = {
    "10000001": {"Customer": "10000001", "CustomerName": "Brennock Water Utility", "CreditLimit": "250000.00",
                 "Currency": "USD"},
    "10000002": {"Customer": "10000002", "CustomerName": "Hallam Fluid Systems", "CreditLimit": "40000.00",
                 "Currency": "USD"},
}

SAP_CLIENT = {"name": "sap-client", "in": "query", "required": False,
              "description": "Technical client number of the backend system",
              "schema": {"type": "string", "example": "100"}}

OPENAPI = {
    "openapi": "3.0.3",
    "info": {"title": "Calder sales orders (course stand-in)", "version": "1.0.0"},
    "servers": [{"url": f"http://{HOST}:{PORT}"}],
    "paths": {
        "/salesorders": {"get": {
            "operationId": "listSalesOrders",
            "summary": "Read sales orders",
            "parameters": [
                {"name": "SoldToParty", "in": "query", "required": False,
                 "description": "Customer number", "schema": {"type": "string"}},
                {"name": "Problem", "in": "query", "required": False, "description": "Problem code",
                 "schema": {"type": "string", "enum": ["credit block", "billing data incomplete",
                                                       "partly confirmed", "price missing", "billing block",
                                                       "delivery block", "none"]}},
                {"name": "$format", "in": "query", "required": False, "description": "",
                 "schema": {"type": "string", "enum": ["json", "xml"]}},
                SAP_CLIENT],
            "responses": {"200": {"description": "Sales orders"}}}},
        "/salesorders/{SalesOrder}": {
            "get": {"operationId": "getSalesOrder", "summary": "Read one sales order",
                    "parameters": [{"name": "SalesOrder", "in": "path", "required": True,
                                    "description": "Sales order number", "schema": {"type": "string"}},
                                   SAP_CLIENT],
                    "responses": {"200": {"description": "One sales order"}}},
            "patch": {"operationId": "updateSalesOrder", "summary": "Change the requested delivery date",
                      "parameters": [{"name": "SalesOrder", "in": "path", "required": True,
                                      "description": "Sales order number", "schema": {"type": "string"}},
                                     {"name": "RequestedDeliveryDate", "in": "query", "required": True,
                                      "description": "New date, YYYY-MM-DD", "schema": {"type": "string"}}],
                      "responses": {"200": {"description": "Changed"}}}},
        "/customers/{Customer}": {"get": {
            "operationId": "getCustomer", "summary": "Read a customer's credit data",
            "parameters": [{"name": "Customer", "in": "path", "required": True,
                            "description": "Customer number", "schema": {"type": "string"}}, SAP_CLIENT],
            "responses": {"200": {"description": "One customer"}}}},
    },
}


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):          # keep the console quiet
        pass

    def answer(self, status, body):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def route(self, method):
        url = urlparse(self.path)
        query = {k: v[0] for k, v in parse_qs(url.query).items()}
        parts = [p for p in url.path.split("/") if p]
        if url.path == "/openapi.json":
            return self.answer(200, OPENAPI)
        if self.headers.get("APIKey") != BACKEND_KEY:
            return self.answer(401, {"error": "backend credential missing or wrong"})
        if method == "GET" and parts == ["salesorders"]:
            rows = [{"SalesOrder": k, **v} for k, v in sorted(ORDERS.items())]
            for field in ("SoldToParty", "Problem"):
                if query.get(field):
                    rows = [r for r in rows if r[field] == query[field]]
            return self.answer(200, {"value": rows})
        if len(parts) == 2 and parts[0] == "salesorders":
            order = ORDERS.get(parts[1])
            if order is None:
                return self.answer(404, {"error": f"sales order {parts[1]} not found"})
            if method == "PATCH":
                order["RequestedDeliveryDate"] = query.get("RequestedDeliveryDate", "")
            return self.answer(200, {"SalesOrder": parts[1], **order})
        if method == "GET" and len(parts) == 2 and parts[0] == "customers":
            customer = CUSTOMERS.get(parts[1])
            if customer is None:
                return self.answer(404, {"error": f"customer {parts[1]} not found"})
            return self.answer(200, customer)
        return self.answer(404, {"error": "no such resource"})

    def do_GET(self):
        self.route("GET")

    def do_PATCH(self):
        self.route("PATCH")


def make_server():
    return ThreadingHTTPServer((HOST, PORT), Handler)


if __name__ == "__main__":
    print(f"Calder sales order stand-in on http://{HOST}:{PORT} (OpenAPI at /openapi.json). Ctrl+C stops it.")
    make_server().serve_forever()

Step 3: Save the MCP server definition

This file is the equivalent of what you click together in Integration Suite: the server's name and path, the source, which operations become tools, what to hide, and the policies in order.

  1. Create unit5b/gateway_config.json, paste the text below and save.
{
  "mcp_server": "CalderSalesOrders",
  "mcp_path": "/calder/salesorders/mcp",
  "source_openapi": "http://127.0.0.1:8771/openapi.json",
  "tools": [
    {
      "operation": "listSalesOrders",
      "name": "list_sales_orders",
      "description": "List Calder's open sales orders that are stuck, with the problem and the team that owns it. Filter by customer number or problem.",
      "hide": ["$format", "sap-client"],
      "hide_enum": {"Problem": ["none"]}
    },
    {
      "operation": "getSalesOrder",
      "name": "get_sales_order",
      "description": "Read one Calder sales order by its 7-digit number, for example 1000002.",
      "hide": ["sap-client"]
    }
  ],
  "policies": [
    {"type": "authentication"},
    {"type": "authorization", "scope": "salesorder.read"},
    {"type": "ip_filter", "allow": ["127.0.0.1/32", "::1/128"]},
    {"type": "surge_protection", "calls": 4, "seconds": 10},
    {"type": "quota", "calls": 100, "period_seconds": 86400}
  ]
}

Read it once before moving on. updateSalesOrder and getCustomer are in the API but not in tools, so the agent will never see them. $format and sap-client are hidden: optional technical fields an agent has no use for. The code value none is hidden from Problem, because the order exception agent only looks at stuck orders.

Step 4: Save the gateway

  1. Create unit5b/mcp_gateway.py, paste the code below and save.
"""Unit 5B: a local MCP gateway, built to show what SAP Integration Suite's MCP gateway does.

It reads an OpenAPI 3.0 description of an HTTP API, turns the operations you choose into MCP tools,
and puts policies in front of them: authentication, authorization, IP filter, surge protection and
quota. Every request is logged. It is a teaching model, not SAP software and not production code.

Commands:
    python unit5b/mcp_gateway.py subscribe --agent AGT_ORDER_EXC --scope salesorder.read
    python unit5b/mcp_gateway.py serve          start the stand-in API and the gateway (Ctrl+C stops)
    python unit5b/mcp_gateway.py tools          print the tools the gateway will publish, then exit
    python unit5b/mcp_gateway.py logs           summarize unit5b/gateway_log.jsonl

The gateway listens on http://127.0.0.1:8770. Tokens come from http://127.0.0.1:8770/oauth/token.
"""
import argparse
import base64
import hashlib
import hmac
import ipaddress
import json
import secrets
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict, deque
from datetime import datetime, timezone
from pathlib import Path

HERE = Path(__file__).resolve().parent
CONFIG = HERE / "gateway_config.json"
SUBSCRIPTIONS = HERE / "gateway_subscriptions.json"
LOG = HERE / "gateway_log.jsonl"
HOST, PORT = "127.0.0.1", 8770
TOKEN_SECONDS = 900                         # tokens live 15 minutes (a course value)
SIGNING_KEY = secrets.token_bytes(32)       # new on every start, so old tokens stop working
sys.path.insert(0, str(HERE))
import calder_sales_api as backend          # noqa: E402  (the stand-in API next to this file)


# ------------------------------------------------------------------ subscriptions (like Developer Hub)
def load_subscriptions():
    return json.loads(SUBSCRIPTIONS.read_text()) if SUBSCRIPTIONS.exists() else {}


def subscribe(agent, scopes):
    subs = load_subscriptions()
    client_id = "agt-" + secrets.token_hex(4)
    secret = secrets.token_urlsafe(24)
    subs[client_id] = {"agent": agent, "scopes": scopes,
                       "secret_sha256": hashlib.sha256(secret.encode()).hexdigest(),
                       "created": datetime.now(timezone.utc).isoformat(timespec="seconds")}
    SUBSCRIPTIONS.write_text(json.dumps(subs, indent=2))
    print(f"Subscription created for agent '{agent}' with scope(s): {' '.join(scopes)}")
    print("Copy these three lines into your .env file (the secret is shown only once):\n")
    print(f"CALDER_MCP_TOKEN_URL=http://{HOST}:{PORT}/oauth/token")
    print(f"CALDER_MCP_CLIENT_ID={client_id}")
    print(f"CALDER_MCP_CLIENT_SECRET={secret}")


# ------------------------------------------------------------------ tokens (signed, short-lived)
def b64(data):
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


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


def issue_token(client_id, sub, audience):
    claims = {"sub": client_id, "agent": sub["agent"], "scope": " ".join(sub["scopes"]),
              "aud": audience, "exp": int(time.time()) + TOKEN_SECONDS}
    body = b64(json.dumps(claims).encode())
    sig = b64(hmac.new(SIGNING_KEY, body.encode(), hashlib.sha256).digest())
    return f"{body}.{sig}", claims


def verify_token(token, audience):
    try:
        body, sig = token.split(".")
        good = b64(hmac.new(SIGNING_KEY, body.encode(), hashlib.sha256).digest())
        if not hmac.compare_digest(sig, good):
            return None, "signature does not match (token from an earlier gateway run?)"
        claims = json.loads(unb64(body))
    except (ValueError, json.JSONDecodeError):
        return None, "token is not in the expected format"
    if claims.get("exp", 0) < time.time():
        return None, "token expired"
    if claims.get("aud") != audience:
        return None, f"token was issued for {claims.get('aud')}, not this MCP server"
    return claims, ""


# ------------------------------------------------------------------ tools from OpenAPI
def build_tools(config, spec):
    """Turn the chosen OpenAPI operations into MCP tool definitions (name, description, input schema)."""
    operations = {}
    for path, methods in spec["paths"].items():
        for method, op in methods.items():
            operations[op["operationId"]] = (method.upper(), path, op)
    tools = {}
    for choice in config["tools"]:
        if choice["operation"] not in operations:
            raise SystemExit(f"gateway_config.json names operation {choice['operation']!r}, "
                             f"which the OpenAPI description doesn't have")
        method, path, op = operations[choice["operation"]]
        hidden = set(choice.get("hide", []))
        props, required, where = {}, [], {}
        for p in op.get("parameters", []):
            if p["name"] in hidden:
                if p.get("required"):
                    raise SystemExit(f"{p['name']} is required by the API, so it can't be hidden")
                continue
            schema = dict(p.get("schema", {"type": "string"}))
            schema.pop("example", None)
            if "enum" in schema and p["name"] in choice.get("hide_enum", {}):
                schema["enum"] = [v for v in schema["enum"] if v not in choice["hide_enum"][p["name"]]]
            if p.get("description"):
                schema["description"] = p["description"]
            props[p["name"]] = schema
            where[p["name"]] = p["in"]
            if p.get("required"):
                required.append(p["name"])
        name = choice.get("name", choice["operation"])
        tools[name] = {"method": method, "path": path, "where": where,
                       "description": choice.get("description") or op.get("summary", ""),
                       "input_schema": {"type": "object", "properties": props, "required": required,
                                        "additionalProperties": False}}
    if len(tools) > 50:
        raise SystemExit("SAP allows at most 50 tools per MCP server; this lab keeps the same limit")
    return tools


def call_backend(tool, arguments):
    """Check the arguments against the published schema, then call the API with the gateway's own key."""
    schema = tool["input_schema"]
    unknown = sorted(set(arguments) - set(schema["properties"]))
    if unknown:
        return True, f"argument(s) {', '.join(unknown)} are not part of this tool"
    missing = [r for r in schema["required"] if not arguments.get(r)]
    if missing:
        return True, f"missing required argument(s): {', '.join(missing)}"
    for name, value in arguments.items():
        allowed = schema["properties"][name].get("enum")
        if allowed and value not in allowed:
            return True, f"{name} must be one of: {', '.join(allowed)}"
    path, query = tool["path"], {}
    for name, value in arguments.items():
        if tool["where"][name] == "path":
            path = path.replace("{" + name + "}", urllib.parse.quote(str(value), safe=""))
        else:
            query[name] = value
    url = f"http://{backend.HOST}:{backend.PORT}{path}"
    if query:
        url += "?" + urllib.parse.urlencode(query)
    req = urllib.request.Request(url, method=tool["method"], headers={"APIKey": backend.BACKEND_KEY})
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return False, resp.read().decode()
    except urllib.error.HTTPError as err:
        return True, f"backend answered {err.code}: {err.read().decode()}"


# ------------------------------------------------------------------ policies, in configured order
class Policies:
    def __init__(self, config):
        self.config = config
        self.audience = config["mcp_path"]
        self.surge = defaultdict(deque)        # client -> times of recent tool calls
        self.quota = {}                        # client -> (window start, count)

    def run(self, ip, headers, rpc_method):
        """Return (claims, None) if the request may pass, or (claims, (status, policy, message))."""
        claims = None
        is_tool_call = rpc_method == "tools/call"
        now = time.time()
        for policy in self.config["policies"]:
            kind = policy["type"]
            if kind == "authentication":
                auth = headers.get("authorization", "")
                if not auth.lower().startswith("bearer "):
                    return None, (401, kind, "no bearer token; get one from /oauth/token")
                claims, why = verify_token(auth[7:].strip(), self.audience)
                if claims is None:
                    return None, (401, kind, why)
            elif kind == "authorization":
                if policy["scope"] not in (claims or {}).get("scope", "").split():
                    return claims, (403, kind, f"token lacks scope {policy['scope']}")
            elif kind == "ip_filter":
                addr = ipaddress.ip_address(ip)
                if not any(addr in ipaddress.ip_network(net) for net in policy["allow"]):
                    return claims, (403, kind, f"address {ip} is not on the allow list")
            elif kind == "surge_protection" and is_tool_call:
                recent = self.surge[claims["sub"]]
                while recent and now - recent[0] > policy["seconds"]:
                    recent.popleft()
                if len(recent) >= policy["calls"]:
                    return claims, (429, kind, f"more than {policy['calls']} tool calls in "
                                               f"{policy['seconds']} s; slow down and retry")
                recent.append(now)
            elif kind == "quota" and is_tool_call:
                start, count = self.quota.get(claims["sub"], (now, 0))
                if now - start >= policy["period_seconds"]:
                    start, count = now, 0
                if count >= policy["calls"]:
                    return claims, (429, kind, f"quota of {policy['calls']} tool calls used up until "
                                               f"the window resets")
                self.quota[claims["sub"]] = (start, count + 1)
        return claims, None


def log(entry):
    entry = {"time": datetime.now(timezone.utc).isoformat(timespec="milliseconds"), **entry}
    with LOG.open("a") as f:
        f.write(json.dumps(entry) + "\n")


def request_id(body):
    try:
        msg = json.loads(body or b"{}")
        return msg.get("id") if isinstance(msg, dict) else None
    except json.JSONDecodeError:
        return None


def describe(body):
    """Pull the JSON-RPC method and tool name out of a request body, for policies and the log."""
    try:
        msg = json.loads(body or b"{}")
    except json.JSONDecodeError:
        return "", ""
    if isinstance(msg, list):                  # older clients may batch; use the first message
        msg = msg[0] if msg else {}
    if not isinstance(msg, dict):              # not JSON-RPC; the MCP server will refuse it
        return "", ""
    params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
    return msg.get("method", ""), params.get("name", "") if msg.get("method") == "tools/call" else ""


# ------------------------------------------------------------------ the server
def make_app(config, tools):
    import mcp_types as types
    from mcp.server.lowlevel import Server
    from starlette.requests import Request
    from starlette.responses import JSONResponse
    from starlette.routing import Route

    async def list_tools(ctx, params):
        return types.ListToolsResult(tools=[
            types.Tool(name=name, description=t["description"], input_schema=t["input_schema"],
                       annotations=types.ToolAnnotations(read_only_hint=t["method"] == "GET"))
            for name, t in tools.items()])

    async def call_tool(ctx, params):
        import anyio
        tool = tools.get(params.name)
        if tool is None:
            is_error, text = True, f"tool {params.name} is not exposed by this MCP server"
        else:
            is_error, text = await anyio.to_thread.run_sync(call_backend, tool, params.arguments or {})
        return types.CallToolResult(content=[types.TextContent(type="text", text=text)], is_error=is_error)

    server = Server(config["mcp_server"], version="1.0.0", on_list_tools=list_tools, on_call_tool=call_tool)

    async def token(request: Request):
        form = await request.form()
        if form.get("grant_type") != "client_credentials":
            return JSONResponse({"error": "unsupported_grant_type"}, status_code=400)
        client_id, secret = form.get("client_id", ""), form.get("client_secret", "")
        auth = request.headers.get("authorization", "")
        if auth.lower().startswith("basic "):
            try:                               # a malformed header is a refusal, not a crash
                client_id, _, secret = base64.b64decode(auth[6:], validate=True).decode().partition(":")
            except ValueError:
                client_id, secret = "?", ""
        sub = load_subscriptions().get(client_id)
        if sub is None or not hmac.compare_digest(
                hashlib.sha256(secret.encode()).hexdigest(), sub["secret_sha256"]):
            log({"agent": "?", "client_id": client_id, "rpc": "token", "status": 401,
                 "outcome": "rejected: unknown client or wrong secret"})
            return JSONResponse({"error": "invalid_client"}, status_code=401)
        tok, claims = issue_token(client_id, sub, config["mcp_path"])
        return JSONResponse({"access_token": tok, "token_type": "bearer", "expires_in": TOKEN_SECONDS,
                             "scope": claims["scope"]})

    inner = server.streamable_http_app(streamable_http_path=config["mcp_path"], json_response=True,
                                       stateless_http=True,
                                       custom_starlette_routes=[Route("/oauth/token", token, methods=["POST"])])
    policies = Policies(config)

    async def app(scope, receive, send):
        """Run the policies in front of the MCP endpoint, then hand the request to the MCP server."""
        if scope["type"] != "http" or scope["path"] != config["mcp_path"]:
            return await inner(scope, receive, send)
        started = time.perf_counter()
        body, more = b"", True
        while more:
            message = await receive()
            body += message.get("body", b"")
            more = message.get("more_body", False)
        rpc, tool = describe(body) if scope["method"] == "POST" else (scope["method"], "")
        headers = {k.decode().lower(): v.decode() for k, v in scope["headers"]}
        claims, rejected = policies.run(scope["client"][0], headers, rpc)
        entry = {"agent": (claims or {}).get("agent", "?"), "client_id": (claims or {}).get("sub", "?"),
                 "rpc": rpc, "tool": tool}
        if rejected:
            status, policy, message = rejected
            log({**entry, "status": status, "outcome": f"rejected by {policy}: {message}",
                 "ms": round((time.perf_counter() - started) * 1000, 1)})
            extra = [(b"www-authenticate", b"Bearer")] if status == 401 else []
            data = json.dumps({"jsonrpc": "2.0", "id": request_id(body),        # a JSON-RPC error, so
                               "error": {"code": -32000,                       # MCP clients can show it
                                         "message": f"HTTP {status} from policy {policy}: {message}",
                                         "data": {"status": status, "policy": policy}}}).encode()
            await send({"type": "http.response.start", "status": status,
                        "headers": [(b"content-type", b"application/json"), *extra]})
            return await send({"type": "http.response.body", "body": data})

        sent, status_seen, answer = False, [0], []

        async def replay():
            nonlocal sent
            if sent:
                return await receive()
            sent = True
            return {"type": "http.request", "body": body, "more_body": False}

        async def watch(message):
            if message["type"] == "http.response.start":
                status_seen[0] = message["status"]
            elif message["type"] == "http.response.body":
                answer.append(message.get("body", b""))
            await send(message)

        await inner(scope, replay, watch)
        tool_error = tool and b'"isError":true' in b"".join(answer).replace(b" ", b"")
        log({**entry, "status": status_seen[0], "outcome": "passed, tool error" if tool_error else "passed",
             "ms": round((time.perf_counter() - started) * 1000, 1)})

    return app


def fetch_spec(config):
    with urllib.request.urlopen(config["source_openapi"], timeout=5) as resp:
        return json.loads(resp.read())


def serve():
    import uvicorn
    config = json.loads(CONFIG.read_text())
    api = backend.make_server()
    threading.Thread(target=api.serve_forever, daemon=True).start()
    tools = build_tools(config, fetch_spec(config))
    print(f"Stand-in API on http://{backend.HOST}:{backend.PORT}  (OpenAPI read, "
          f"{len(tools)} of {sum(len(m) for m in fetch_spec(config)['paths'].values())} operations exposed)")
    print(f"MCP server {config['mcp_server']} on http://{HOST}:{PORT}{config['mcp_path']}")
    print("Policies, in order: " + " -> ".join(p["type"] for p in config["policies"]))
    print("Every request is logged to unit5b/gateway_log.jsonl. Ctrl+C stops the gateway.")
    uvicorn.run(make_app(config, tools), host=HOST, port=PORT, log_level="warning")


def show_tools():
    config = json.loads(CONFIG.read_text())
    api = backend.make_server()
    threading.Thread(target=api.serve_forever, daemon=True).start()
    for name, t in build_tools(config, fetch_spec(config)).items():
        print(f"{name}  ({t['method']} {t['path']})")
        print(f"  {t['description']}")
        for p, s in t["input_schema"]["properties"].items():
            req = " (required)" if p in t["input_schema"]["required"] else ""
            enum = f" one of: {', '.join(s['enum'])}" if "enum" in s else ""
            print(f"  - {p}{req}{enum}")
    api.shutdown()


def show_logs():
    if not LOG.exists():
        return print("No log yet. Start the gateway and run the client first.")
    rows = [json.loads(line) for line in LOG.read_text().splitlines() if line.strip()]
    print(f"{len(rows)} requests logged in unit5b/gateway_log.jsonl\n")
    calls = Counter((r["agent"], r.get("tool") or r["rpc"], r["outcome"].split(":")[0]) for r in rows)
    print(f"{'agent':<20} {'tool or method':<22} {'outcome':<36} count")
    for (agent, what, outcome), n in sorted(calls.items()):
        print(f"{agent:<20} {what:<22} {outcome:<36} {n}")
    times = [r["ms"] for r in rows if r.get("ms") is not None and r["outcome"].startswith("passed")]
    if times:
        print(f"\nMedian time through the gateway for passed requests: {sorted(times)[len(times) // 2]} ms")


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="command", required=True)
    s = sub.add_parser("subscribe", help="create client credentials for an agent")
    s.add_argument("--agent", required=True)
    s.add_argument("--scope", nargs="+", default=["salesorder.read"])
    sub.add_parser("serve", help="start the stand-in API and the gateway")
    sub.add_parser("tools", help="print the tools the gateway will publish")
    sub.add_parser("logs", help="summarize the gateway log")
    args = parser.parse_args()
    if args.command == "subscribe":
        subscribe(args.agent, args.scope)
    elif args.command == "serve":
        serve()
    elif args.command == "tools":
        show_tools()
    else:
        show_logs()


if __name__ == "__main__":
    main()
  1. Ask it which tools it will publish. It starts the stand-in API, reads the OpenAPI description, builds the tools and exits:

    python unit5b/mcp_gateway.py tools
    list_sales_orders  (GET /salesorders)
      List Calder's open sales orders that are stuck, with the problem and the team that owns it. Filter by customer number or problem.
      - SoldToParty
      - Problem one of: credit block, billing data incomplete, partly confirmed, price missing, billing block, delivery block
    get_sales_order  (GET /salesorders/{SalesOrder})
      Read one Calder sales order by its 7-digit number, for example 1000002.
      - SalesOrder (required)

    Two tools, no sap-client, no $format, no none. That is tool simplification.

Step 5: Subscribe the agent

In Integration Suite, an agent developer subscribes in Developer Hub and gets a key and secret. Here, one command does the same.

  1. Run:

    python unit5b/mcp_gateway.py subscribe --agent AGT_ORDER_EXC --scope salesorder.read
    Subscription created for agent 'AGT_ORDER_EXC' with scope(s): salesorder.read
    Copy these three lines into your .env file (the secret is shown only once):
    
    CALDER_MCP_TOKEN_URL=http://127.0.0.1:8770/oauth/token
    CALDER_MCP_CLIENT_ID=agt-9efaddbc
    CALDER_MCP_CLIENT_SECRET=3RvIpzQJAfEyp01QTkEk3Mhl74TdTs8G

    Your client ID and secret are different: they are random.

  2. Open .env in the course folder (create it if it doesn't exist) and paste the three lines at the end. Save.

Step 6: Start the gateway

  1. Run:

    python unit5b/mcp_gateway.py serve
    Stand-in API on http://127.0.0.1:8771  (OpenAPI read, 2 of 4 operations exposed)
    MCP server CalderSalesOrders on http://127.0.0.1:8770/calder/salesorders/mcp
    Policies, in order: authentication -> authorization -> ip_filter -> surge_protection -> quota
    Every request is logged to unit5b/gateway_log.jsonl. Ctrl+C stops the gateway.
  2. Leave this terminal running. Open a second terminal with Terminal > New Terminal and turn on .venv there too (Step 1, item 3).

Step 7: Save the course client

This is the agent's side: get a token, connect over Streamable HTTP, list and call tools. It is the MCP SDK's Client, the same one used in Model Context Protocol, with an Authorization header added.

  1. Create unit5b/gateway_client.py, paste the code below and save.
"""Unit 5B: the course's MCP client, pointed at a governed MCP server.

It gets an OAuth token with the client credentials in .env, connects to the MCP endpoint over
Streamable HTTP, and lists or calls tools. The same script works against the local gateway
(mcp_gateway.py) and, by changing the four lines in .env, against an MCP server deployed in
SAP Integration Suite (see "The SAP way" in the topic; that path is not tested here).

Commands:
    python unit5b/gateway_client.py tools
    python unit5b/gateway_client.py call get_sales_order SalesOrder=1000002
    python unit5b/gateway_client.py call list_sales_orders Problem="credit block"
    python unit5b/gateway_client.py burst 6           six quick calls, to meet surge protection
    python unit5b/gateway_client.py tools --no-token  what an agent without credentials gets
"""
import argparse
import asyncio
import base64
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

import httpx2
from dotenv import load_dotenv
from mcp import Client
from mcp.client.streamable_http import streamable_http_client

DEFAULT_URL = "http://127.0.0.1:8770/calder/salesorders/mcp"


def get_token():
    """OAuth 2.0 client credentials: send the client ID and secret, get a short-lived bearer token."""
    token_url = os.getenv("CALDER_MCP_TOKEN_URL")
    client_id = os.getenv("CALDER_MCP_CLIENT_ID")
    secret = os.getenv("CALDER_MCP_CLIENT_SECRET")
    if not (token_url and client_id and secret):
        sys.exit("Missing in .env: CALDER_MCP_TOKEN_URL, CALDER_MCP_CLIENT_ID or CALDER_MCP_CLIENT_SECRET. "
                 "Run: python unit5b/mcp_gateway.py subscribe --agent AGT_ORDER_EXC")
    basic = base64.b64encode(f"{client_id}:{secret}".encode()).decode()
    req = urllib.request.Request(token_url, data=urllib.parse.urlencode({"grant_type": "client_credentials"}).encode(),
                                 headers={"Authorization": f"Basic {basic}",
                                          "Content-Type": "application/x-www-form-urlencoded"})
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            answer = json.loads(resp.read())
    except urllib.error.HTTPError as err:
        sys.exit(f"Token request refused ({err.code}): {err.read().decode()[:200]}")
    except urllib.error.URLError as err:
        sys.exit(f"Can't reach {token_url}: {err.reason}. Is the gateway running?")
    print(f"Token received: expires in {answer.get('expires_in')} s, scope '{answer.get('scope', '')}'")
    return answer["access_token"]


def parse_args_list(pairs):
    args = {}
    for pair in pairs:
        key, sep, value = pair.partition("=")
        if not sep:
            sys.exit(f"Write tool arguments as name=value, not {pair!r}")
        args[key] = value
    return args


def first_text(result):
    return " ".join(c.text for c in result.content if getattr(c, "type", "") == "text")


async def run(command, url, token, tool=None, arguments=None, count=0):
    headers = {"Authorization": f"Bearer {token}"} if token else {}
    async with httpx2.AsyncClient(headers=headers, timeout=httpx2.Timeout(30.0, read=300.0)) as http:
        async with Client(streamable_http_client(url, http_client=http)) as client:
            if command == "tools":
                listed = await client.list_tools()
                print(f"{len(listed.tools)} tools offered by {url}")
                for t in listed.tools:
                    props = t.input_schema.get("properties", {})
                    print(f"- {t.name}: {t.description}")
                    print(f"    inputs: {', '.join(props) or '(none)'}")
            elif command == "call":
                result = await client.call_tool(tool, arguments)
                label = "TOOL ERROR" if result.is_error else "Result"
                print(f"{label}: {first_text(result)}")
            elif command == "burst":
                for i in range(1, count + 1):
                    try:
                        result = await client.call_tool("get_sales_order", {"SalesOrder": "1000002"})
                        print(f"call {i}: ok, {json.loads(first_text(result))['Problem']}")
                    except Exception as err:    # the gateway answered with an HTTP error
                        print(f"call {i}: refused, {explain(err)}")


def short(err):
    text = str(err) or type(err).__name__
    return text.splitlines()[0][:160]


def main():
    load_dotenv()
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("command", choices=["tools", "call", "burst"])
    parser.add_argument("rest", nargs="*", help="for call: TOOL name=value ...; for burst: a number")
    parser.add_argument("--no-token", action="store_true", help="connect without a token")
    opts = parser.parse_args()
    url = os.getenv("CALDER_MCP_URL", DEFAULT_URL)
    token = None if opts.no_token else get_token()
    tool, arguments, count = None, None, 0
    if opts.command == "call":
        if not opts.rest:
            sys.exit("Name a tool, for example: call get_sales_order SalesOrder=1000002")
        tool, arguments = opts.rest[0], parse_args_list(opts.rest[1:])
    if opts.command == "burst":
        count = int(opts.rest[0]) if opts.rest else 6
    try:
        asyncio.run(run(opts.command, url, token, tool, arguments, count))
    except Exception as err:
        sys.exit(f"Refused: {explain(err)}")


def explain(err):
    """Dig the gateway's message out of the SDK's exception group."""
    seen = [err]
    while seen:
        e = seen.pop()
        seen.extend(getattr(e, "exceptions", []))
        error = getattr(e, "error", None)          # an MCP error carries the server's message
        if error is not None and getattr(error, "message", ""):
            return error.message
    return short(err)

if __name__ == "__main__":
    main()

Step 8: List the tools and read an order

Run these in the second terminal.

  1. List what the agent sees:

    python unit5b/gateway_client.py tools
    Token received: expires in 900 s, scope 'salesorder.read'
    2 tools offered by http://127.0.0.1:8770/calder/salesorders/mcp
    - list_sales_orders: List Calder's open sales orders that are stuck, with the problem and the team that owns it. Filter by customer number or problem.
        inputs: SoldToParty, Problem
    - get_sales_order: Read one Calder sales order by its 7-digit number, for example 1000002.
        inputs: SalesOrder
  2. Read Hallam's blocked order:

    python unit5b/gateway_client.py call get_sales_order SalesOrder=1000002
    Token received: expires in 900 s, scope 'salesorder.read'
    Result: {"SalesOrder": "1000002", "SoldToParty": "10000002", "CustomerName": "Hallam Fluid Systems", "DistributionChannel": "20", "RequestedDeliveryDate": "2026-10-30", "TotalNetAmount": "24288.00", "Problem": "credit block", "Owner": "Credit analyst"}
  3. List Brennock's stuck orders. You should see four: 1000003, 1000004, 1000006 and 1000007:

    python unit5b/gateway_client.py call list_sales_orders SoldToParty=10000001

    An empty list ({"value": []}) is a valid answer: it means no stuck orders for that customer. Try SoldToParty=10000099 to see one.

Step 9: Watch each policy refuse a call

Each command below is something an agent might do. Read the refusal and which policy gave it.

  1. No token (authentication):

    python unit5b/gateway_client.py tools --no-token
    Refused: HTTP 401 from policy authentication: no bearer token; get one from /oauth/token
  2. A tool that isn't published. The API has an operation that changes the delivery date. The agent tries it anyway:

    python unit5b/gateway_client.py call update_sales_order SalesOrder=1000007 RequestedDeliveryDate=2026-11-20
    Token received: expires in 900 s, scope 'salesorder.read'
    TOOL ERROR: tool update_sales_order is not exposed by this MCP server

    This is a tool error, not an HTTP error: the call passed the policies, and the MCP server answered that no such tool exists. Order 1000007 is unchanged.

  3. A hidden field. Hidden means not part of the tool, so the lab refuses it:

    python unit5b/gateway_client.py call get_sales_order SalesOrder=1000002 sap-client=100
    Token received: expires in 900 s, scope 'salesorder.read'
    TOOL ERROR: argument(s) sap-client are not part of this tool
  4. Too fast (surge protection). Wait ten seconds after the last command, then send six calls in a row:

    python unit5b/gateway_client.py burst 6
    Token received: expires in 900 s, scope 'salesorder.read'
    call 1: ok, credit block
    call 2: ok, credit block
    call 3: ok, credit block
    call 4: ok, credit block
    call 5: refused, HTTP 429 from policy surge_protection: more than 4 tool calls in 10 s; slow down and retry
    call 6: refused, HTTP 429 from policy surge_protection: more than 4 tool calls in 10 s; slow down and retry

    If fewer than four pass, calls from your previous commands were still inside the 10-second window. Wait and run it again.

  5. The wrong scope (authorization). Subscribe a second agent that is only meant to read purchase orders:

    python unit5b/mcp_gateway.py subscribe --agent AGT_SUPPLY_WATCH --scope po.read

    Then run the client with that agent's ID and secret for one command, without touching .env. Replace the two values with the ones just printed:

    • Windows (PowerShell):

      $env:CALDER_MCP_CLIENT_ID="agt-xxxxxxxx"; $env:CALDER_MCP_CLIENT_SECRET="paste-secret"; python unit5b/gateway_client.py tools; Remove-Item Env:CALDER_MCP_CLIENT_ID, Env:CALDER_MCP_CLIENT_SECRET
    • macOS / Linux:

      CALDER_MCP_CLIENT_ID=agt-xxxxxxxx CALDER_MCP_CLIENT_SECRET=paste-secret python unit5b/gateway_client.py tools
    Token received: expires in 900 s, scope 'po.read'
    Refused: HTTP 403 from policy authorization: token lacks scope salesorder.read

    The token is valid. The agent simply isn't allowed on this MCP server.

Step 10: Read the log

  1. Summarize what the gateway saw:

    python unit5b/mcp_gateway.py logs
    24 requests logged in unit5b/gateway_log.jsonl
    
    agent                tool or method         outcome                              count
    ?                    initialize             rejected by authentication           1
    ?                    server/discover        rejected by authentication           1
    AGT_ORDER_EXC        get_sales_order        passed                               5
    AGT_ORDER_EXC        get_sales_order        passed, tool error                   1
    AGT_ORDER_EXC        get_sales_order        rejected by surge_protection         2
    AGT_ORDER_EXC        list_sales_orders      passed                               1
    AGT_ORDER_EXC        server/discover        passed                               6
    AGT_ORDER_EXC        tools/list             passed                               4
    AGT_ORDER_EXC        update_sales_order     passed, tool error                   1
    AGT_SUPPLY_WATCH     initialize             rejected by authorization            1
    AGT_SUPPLY_WATCH     server/discover        rejected by authorization            1
    
    Median time through the gateway for passed requests: 1.5 ms

    Your counts differ if you ran commands more or fewer times. Times vary by computer.

  2. Notice three things. Refused calls are logged with the agent's name, which is what operations needs. A refused connection shows twice: the client first tries the stateless server/discover of the 2026-07-28 revision, then falls back to the older initialize. And after a tool call, the SDK's client lists tools to look up that tool's output schema and check the result against it.

  3. Open unit5b/gateway_log.jsonl to see one line per request:

    {"time": "2026-11-11T15:30:25.543+00:00", "agent": "AGT_ORDER_EXC", "client_id": "agt-9efaddbc", "rpc": "server/discover", "tool": "", "status": 200, "outcome": "passed", "ms": 1.5}
  4. Stop the gateway: click the first terminal and press Ctrl+C.

Step 11: Save your work in Git

  1. Keep the secrets file and the log out of Git. Add these two lines to .gitignore:

    unit5b/gateway_subscriptions.json
    unit5b/gateway_log.jsonl
  2. Commit:

    git add .gitignore requirements.txt unit5b/calder_sales_api.py unit5b/gateway_config.json unit5b/mcp_gateway.py unit5b/gateway_client.py
    git commit -m "Unit 5B: local MCP gateway with policies and the course client"

What the code does

Part What it does
calder_sales_api.py, OPENAPI The backend's contract: four operations with parameters, in OpenAPI 3.0.3 like SAP's MCP server requires
calder_sales_api.py, BACKEND_KEY The backend's own credential. Only the gateway sends it; the agent never sees it
gateway_config.json The MCP server definition: path, chosen operations, names, descriptions, hidden fields and values, policies in order
build_tools Turns each chosen operation into an MCP tool: name, description and an input schema with hidden fields removed. Stops at 50 tools, like SAP
subscribe, issue_token The Developer Hub stand-in: creates a client ID and secret, then issues 15-minute signed tokens with the agent's scopes and this server as audience
Policies.run Runs the policies in the configured order and returns the first refusal: 401, 403 or 429
app Sits in front of the MCP endpoint: reads the request, runs the policies, logs the outcome, then hands the request to the MCP server
call_tool, call_backend Refuses tools and arguments that aren't published, then calls the backend with the gateway's own key
gateway_client.py, get_token OAuth client credentials: sends ID and secret to the token URL, receives a bearer token
gateway_client.py, run Connects with the SDK's Client over Streamable HTTP, with the token in the Authorization header

The lab simplifies on purpose. Its surge and quota count only tools/call requests and count per agent; SAP's surge protection counts requests regardless of client. It signs tokens with a key that changes on every start. It has no person in the loop, so every call runs as the agent. SAP's real gateway does none of this the lab's way; it shows the order of checks, not SAP's implementation.

If something goes wrong

What you see What it means What to do
python is not recognized, or command not found Python isn't on the path, or it's called python3 Use python3 on macOS and Linux; see Set up your computer
ModuleNotFoundError: No module named 'mcp' or 'dotenv' .venv is off or the libraries are missing Check for (.venv) in the prompt, then pip install -r requirements.txt
No module named 'httpx2' or cannot import name 'Client' from 'mcp' You have version 1 of the MCP SDK Set the line to mcp[cli]==2.3.0 and install again
Missing in .env: CALDER_MCP_TOKEN_URL... Step 5's three lines aren't in .env Paste them, save, and run from the course folder
Can't reach http://127.0.0.1:8770/oauth/token The gateway isn't running Start it in the first terminal (Step 6)
Token request refused (401): invalid_client Wrong client ID or secret, or you deleted gateway_subscriptions.json Subscribe again and replace the lines in .env
HTTP 401 ... signature does not match The gateway restarted, so old tokens are void Run the client again; it fetches a new token each time
[Errno 48] or [WinError 10048] address in use Something else uses port 8770 or 8771, or an old gateway is still running Close the other terminal, or stop the old process
A company proxy or VPN blocks the calls Some proxies intercept even local traffic Set NO_PROXY=127.0.0.1,localhost in the terminal, or try off the VPN

The SAP way

Here are the same steps in Integration Suite, as SAP documents them in November 2026. This part is a sketch: we could not run it in this session.

  1. Expose the API first. In Integration Suite, create an API artifact for your sales order API on the Integration Cell runtime, with OAuth authentication. Its OpenAPI description must be version 3.0.0 to 3.0.3. The course's sales order API is introduced in calling your first SAP API.
  2. Create the MCP server. Go to Design > Integrations and APIs, open your package, choose Edit, then Artifacts > Add > MCP Server. Choose API as the source and Next.
  3. Provide MCP details. Select the API, then enter a Name (letters, digits, underscore), an ID, an MCP Path such as /calder/salesorders (not empty and not /), a Version, the Runtime Profile (Integration Cell) and check the Virtual Host.
  4. Create tools. Tick the read operations only, and choose Add.
  5. Trim the tools. Under MCP Configuration > Tools, rename and re-describe each tool, then use Input Schema and Output Schema to hide fields and code values the agent doesn't need.
  6. Set policies. On Policies, keep Authentication and Authorization. Set the scope the agent's token must carry. Add Surge Protection and Quota sized to the business volume. In the source API's Authorization policy, turn on Trust Upstream MCP Authorization.
  7. Deploy from the artifact's actions, confirming the runtime profile and virtual host.
  8. Publish and subscribe. Add the MCP server to a product in Developer Hub and publish it. As the agent developer, choose Subscribe > Create New Subscription for Agent, enter the agent's Callback URL, and create it. Copy Key, Secret and Token URL from the application's Overview.
  9. Point the course client at it. Put four lines in .env: the deployed endpoint (from Monitor > Integrations and APIs) as CALDER_MCP_URL, and the token URL, key and secret. The client's get_token uses client credentials, which fits a technical-user setup. For a user token, the agent host must run the Authorization Code flow instead; SAP's pages give Claude Desktop's callback URL as an example.
  10. Watch it. Under Monitor > Integrations and APIs, check message processing per call. Under Analyze, the Overview, Health and Usage pages show agent calls, errors and response times per MCP server (Analyze APIs and MCP Servers).

Two traps from SAP's pages: a backend certificate that isn't in the runtime keystore makes every call fail with an internal server error (Deploy an MCP Server), and with shadow users, per-user scope checks don't work, so SAP points you to developer-key authorization.

Licensing. SAP ties the MCP server feature to the Integration Suite service plan without a separate public price we could find. SAP's tutorials name the Premium or Enhanced Edition for productive use. Integration Suite's AI-assisted features (such as generating an OpenAPI description for an HTTP endpoint) are listed for the Premium and Enhanced editions as a free promotion until the January 2027 release (HTTP endpoint page). Confirm both with your SAP account team.

Build vs. SAP

Concern Your own MCP server or gateway Integration Suite MCP gateway
Getting started Minutes on a laptop, like this lab A BTP trial for learning; for production, a plan with MCP and Integration Cell in your region
Sources Whatever you code API artifacts, HTTP endpoints, RFCs from ECC and S/4HANA, remote MCP servers
Identity You build token checks, scopes and principal propagation XSUAA or external OIDC; principal propagation through destinations and Cloud Connector
Limits You code and operate them Quota, Surge Protection, IP Filter as configuration
Tool design Full control in code Generated from the source, then trimmed and described in the editor; up to 50 tools
Consumption Your own key management Developer Hub products and per-agent subscriptions
Operations Your logs, your dashboards Message processing monitor and MCP analytics
SAP's API policy for AI access You must show the route is allowed SAP names the MCP gateway as an endorsed route (see SAP's tools for agents)
Best for Learning, prototypes, logic SAP's editor can't express Production access to SAP APIs from many agents

The lab is for understanding. For agents that reach SAP APIs in production, the MCP gateway is the default; build your own only for what it can't do, and put that behind the gateway as a remote MCP server.

Architecture view

Where it sits. The MCP gateway lives in Integration Suite on BTP, between agents and backends. For Calder, the order exception agent calls an MCP server on Integration Cell. That server calls the sales order API artifact, which reaches CP10's S/4HANA system. An RFC-based server could reach CP20's ECC through Cloud Connector until the July 2027 move.

flowchart LR
  AG[Agents<br/>Joule Studio, own, partner] --> DH[Developer Hub<br/>subscriptions]
  AG --> MG[MCP gateway<br/>Integration Cell]
  MG --> APIA[API artifact<br/>sales orders]
  APIA --> S4[(CP10 S/4HANA)]
  MG -->|RFC via Cloud Connector| ECC[(CP20 ECC)]
  MG --> MON[Monitor + Analyze]

Non-functional requirements.

Requirement Typical target for Calder What breaks if missed
Identity Read-only agents as a technical user; agents acting for a clerk with the clerk's token A clerk sees orders outside their sales area
Volume Surge and quota sized per agent from expected calls (Calder's order agent: tens of orders a day) A looping agent floods S/4HANA or starves other consumers
Latency Tool call well under the 60,000 ms receiver timeout Agent hosts time out and retry, doubling load
Availability Same as the API it fronts Agent works, then fails silently during backend maintenance
Cost Tools trimmed to the fields the agent reads Every call carries a large schema; token bills grow

Integration and identity. Data flows agent to gateway over MCP, gateway to backend over the API artifact's protocol (OData or REST) or RFC. The agent's identity enters as an OAuth token from XSUAA or the external identity provider. The backend identity is either the destination's technical user or the person, propagated through Cloud Connector.

The decision to record. In the short ADR form from the design-doc topic:

  • Context: Calder's order exception agent needs read access to stuck sales orders; later agents will need more.
  • Options: A, each agent calls the sales order API directly with its own credential; B, an own MCP server on BTP; C, an MCP server in the Integration Suite MCP gateway built from the existing API artifact.
  • Decision: C, with two read tools, a technical user for this agent, scope salesorder.read, surge and quota per subscription.
  • Consequences: needs a plan with MCP and Integration Cell; tool definitions become reviewed artifacts; write tools are a separate MCP server with user tokens and a human approval step.

What a design review will ask.

  1. Which identity does S/4HANA see for each tool call, and how was that tested?
  2. Why is each published tool needed, and who approves a new one?
  3. How were the surge and quota numbers chosen, and who is alerted on 429s?
  4. What happens to the tools when the source API changes, and who runs Synchronize?
  5. Is the route allowed under SAP's API policy for AI access, in writing?

Production concerns

  • Authorizations. The gateway's scope check is coarse: one scope per MCP server. Fine-grained rules (sales area, company code) still come from S/4HANA roles. Design the technical user's role as narrowly as the tools, as covered in agent permissions and SAP authorizations.
  • Writes. Keep change operations out of read servers. If an agent must change data, publish the write on its own server, with user tokens, and route it through a human approval step as in human approval in AI workflows.
  • Tool descriptions are part of the attack surface. A remote MCP server behind the gateway can change its tool descriptions. Review and pin them, as in prompt injection and tool poisoning.
  • Evaluation. Test the agent against the trimmed tools, not the full API. A hidden field the agent needed shows up as wrong answers, not errors.
  • Lifecycle. MCP servers transport between tenants like other API artifacts. Add each one to the interface inventory from the integration lead's toolkit, with an owner and a test case.
  • Clean core. The gateway changes nothing in S/4HANA. Publish released APIs; treat RFC sources as a bridge, especially custom ones.

Pitfalls

  • Publishing a whole API "for later". Every extra tool is something the agent may call. Start with the two the use case needs.
  • Assuming 429s are rare. Agents retry. Without a backoff, a refused agent makes more requests, not fewer.
  • Mixing a technical user with a user-facing agent. The clerk sees what the technical user sees. Decide identity per server.
  • Forgetting API.invoke. User-token access fails until an administrator creates a role collection with it, or authorization uses the developer key.
  • Hiding a field the backend needs. Required fields can't be hidden; optional fields with meaningful defaults can change results when dropped. Test after trimming.
  • Using Process Integration Runtime keys in production. SAP calls it an anti-pattern; per-agent subscriptions are what make per-agent limits and analytics work.

Exercise: publish a third tool and tighten the quota

You'll add the customer credit lookup as a tool and lower the quota, then prove both.

  1. Stop the gateway if it's running (Ctrl+C in its terminal).

  2. Open unit5b/gateway_config.json. In tools, after the get_sales_order entry's closing }, add a comma and this entry:

    {
      "operation": "getCustomer",
      "name": "get_customer_credit",
      "description": "Read a Calder customer's credit limit by customer number, for example 10000002.",
      "hide": ["sap-client"]
    }
  3. In policies, change the quota line to 5 tool calls per hour:

    {"type": "quota", "calls": 5, "period_seconds": 3600}
  4. Save, run python unit5b/mcp_gateway.py tools and check that three tools are listed.

  5. Start the gateway with python unit5b/mcp_gateway.py serve.

  6. In the second terminal, run python unit5b/gateway_client.py call get_customer_credit Customer=10000002. Hallam's limit should be 40000.00.

  7. Run python unit5b/gateway_client.py call get_sales_order SalesOrder=1000002 five times, a few seconds apart.

  8. Write two sentences in unit5b/mcp_gateway_notes.md: which identity this tool would need in a real system, and why a credit limit tool might belong on a different MCP server than the order tools.

Done when: tools shows three tools including get_customer_credit; the credit call returns 40000.00; the sixth tool call in the hour is refused with HTTP 429 from policy quota; and your notes file is committed. Keep the notes: agent permissions and SAP authorizations works through questions like these.

Check yourself

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

1In Integration Suite, which runtime does an MCP server deploy to?

Answer: B. SAP documents that MCP servers deploy only to the Integration Cell runtime, which you activate under Settings > Runtime in designated regions and cloud providers.

2You want to build an MCP server from an existing API artifact. Which API can SAP's editor use?

Answer: D. SAP lists three conditions: OData or REST artifacts deployed on Integration Cell, OpenAPI 3.0.0 to 3.0.3, and OAuth-based authentication. Swagger 2.0 is not supported.

3Which two policies does every MCP server start with, and which must run first?

Answer: C. Authentication and Authorization are added by default and can't be deleted, and the Authentication policy must be the first in the request flow. Quota, Surge Protection and IP Filter are optional additions.

4In the lab, the agent calls update_sales_order. Why does it get a tool error instead of an HTTP 403?

Answer: D. The token was valid and had the right scope, so all policies passed. updateSalesOrder is in the API but not in tools in gateway_config.json, so the MCP server answers that the tool doesn't exist.

5What does hiding sap-client in the tool definition achieve?

Answer: B. Hiding removes the attribute from the agent-facing schema only. SAP calls it non-destructive: the source API stays as it was, and you can unhide the field without resynchronizing.

6Your agent gets HTTP 429 on call 5 of a burst. Which policy most likely fired, and what should the agent do?

Answer: A. A burst over a few seconds trips surge protection, which SAP configures in an interval of up to 10 seconds. The right response is a backoff. Switching subscriptions to dodge a limit defeats the control.

7A clerk-facing agent connects with client credentials as one technical user. What is the risk?

Answer: B. With a technical user token, every request runs with the technical user's permissions. For an agent acting for a person, use an IdP user token and propagate the user to the backend.

8Calder wants an agent to read orders in ECC company code CP20 before the July 2027 move. What does the gateway offer?

Answer: B. The RFC source connects through an RFC destination and Cloud Connector, and SAP lists ECC 6.0, ECC 5.0 and S/4HANA as supported. It is a bridge: the RFC must be one you would support after the move.

Sources

Sign in to track your progress

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

or

Tell us a little about you

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

SAP areas you work in