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.

Generating an MCP server from an OData API

Turn an SAP OData service into MCP tools with a generator, then cut, rename and describe them until an agent can use them safely.

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

The 60-second version

An AI agent works with SAP through tools: small, named actions such as "find blocked sales orders". The Model Context Protocol (MCP) is the common way to offer those tools to an agent. SAP systems already describe their APIs precisely, so a program can read that description and write an MCP server for you in minutes. SAP offers this in two places: Joule Studio and SAP Integration Suite.

The catch is that a generator translates the whole API, not the job. SAP's sales order API has 22 entity sets. Generate one tool per operation and you get dozens of tools (76 in the course's trimmed copy), each described as something like "Get entities from A_SalesOrder". An agent offered all of them reads tens of thousands of characters before it starts, picks the wrong tool more often, and can reach operations that create, change or delete orders.

So treat the generated server as a first draft. A person who knows the process cuts it down to the few tools one agent needs, renames them, writes descriptions that say when to use each one, hides fields the agent shouldn't see, and keeps every change to SAP data behind an approval step. That curation is quick, and it decides whether the agent works.

Why it matters to the business

  • Speed is real, but only for the first draft. Generating from a released API saves the hours of writing tool plumbing by hand. The work that remains is judgment: which actions the agent may take, and how they are explained to it.
  • Cost and reliability. Every tool definition goes to the model with every request. SAP's own TechEd 2026 workshop shows an agent that failed with "Input is too long" because it carried over 300 generated tools (AD263). Fewer, clearer tools mean cheaper calls and fewer wrong ones.
  • Risk. A generated server can include create, update and delete tools for every entity. SAP's architecture guidance warns that raw transactional APIs without business context risk incorrect transactions on writes (SAP Architecture Center, 26 October 2026).
  • Upkeep. APIs change. A generated server that someone curated must be checked again when the API is regenerated, or a tool breaks quietly.

Example. At Calder Pumpworks, the course's fictional pump maker, customer service wants an agent that explains why orders 1000002 to 1000007 are stuck (credit block, missing payment terms, partial confirmation, missing price, billing block, delivery hold). It needs two or three read tools over the sales order API. It doesn't need billing plans, pricing elements or the ability to delete an order.

How SAP does it

As of November 2026, SAP offers two generators, and the course adds the hand-written route you already know:

  • Joule Studio can generate an MCP server from an existing SAP OData or REST API, deploy it to the SAP-managed runtime, and attach it to any agent as a tool source (SAP Architecture Center, 25 October 2026). The page gives no release status for this asset. In SAP's TechEd workshop, the coding agent finds the API in SAP Knowledge Graph, downloads its description, and writes a mapping file of tools (AD263).
  • SAP Integration Suite's MCP gateway turns an OData or REST API artifact into a governed MCP server with policies. Since 18 October 2026 it lets you refine generated tools: hide parameters, restrict value lists, and rewrite names and descriptions, without touching the API itself (GA per What's New). Availability depends on your service plan. The MCP gateway topic builds one.
  • SAP's own position. SAP's architecture page warns against MCP over raw transactional APIs, says Joule Studio MCP servers add semantic enrichment of business capabilities, and says SAP manages their lifecycle, including specification upgrades and security patches (SAP Architecture Center).
  • Hand-written servers, as in the Model Context Protocol: full control, and full upkeep.

Generated versus agent-ready

The course's lab runs the same comparison on a stand-in for SAP's sales order API:

Generated from the API After curation for one agent
Tools 76 (list, get, create, update and delete per entity set, plus 2 actions) 2 (list orders, read one order)
Tools that change SAP data 32 0
Descriptions "Get entities from A_SalesOrder" When to use it, what it returns, that it is read-only
Characters the model reads per request about 97,000 about 3,700
Fields returned every field of the entity the 10 to 14 a person needs to decide

Questions to ask

  1. Which agent will use this server, and which three to ten actions does it actually need?
  2. Is any generated tool able to create, change or delete SAP data? Who approves those changes, and where is that enforced?
  3. Who writes and reviews the tool descriptions, and are they tested with real questions from users?
  4. Whose identity reaches SAP when a tool runs: the user's, or a technical user's? (See SAP tools for agents.)
  5. What happens to our edits when the API is regenerated or synchronized, and who checks?
  6. Is the generator generally available in our edition and service plan, and how is it charged?

Common misconceptions

  • "Generated means done." Generated means complete, which is the problem. The agent needs a small, explained set.
  • "More tools make the agent more capable." Past a point they make it slower, more expensive and more often wrong.
  • "Hiding a tool or field is security." It reduces noise. Access is still decided by SAP authorizations and the gateway's policies.
  • "The API's field labels are good enough descriptions." Labels such as "Net Value" were written for screens. An agent needs to know when and why to use a tool.
  • "Curate once and forget it." Each API change can remove a field your curation relies on.

Key terms

All course terms, A to Z, in the glossary

  • MCP server: a program that offers tools, data and prompts to AI agents through the Model Context Protocol.
  • Tool definition: the name, description and input and output schema the model reads to decide whether and how to call a tool.
  • OData $metadata: the machine-readable description of an OData service: its entity sets, fields, keys and actions.
  • Generator: software that turns an API description into tool definitions automatically.
  • Curation: a person's edits to generated tools: keep, delete, rename, describe, hide fields, restrict values.
  • Tool simplification: SAP Integration Suite's name for curating generated MCP tools without changing the source API.
  • Synchronization: updating a generated MCP server after its source API changed.

Check yourself

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

1Why should a generated MCP server be treated as a first draft?

Answer: D. A generator translates every operation of the API, so the result is complete but not focused. The agent works better, and more safely, with the few tools its job needs, named and described for that job.

2Calder's agent only explains why orders are stuck. What should happen to the generated delete and update tools?

Answer: D. Write tools let the model change SAP data. An explaining agent needs none, and any change should go through a person's approval that the model can't skip.

3What is the main business cost of offering an agent about 80 generated tools?

Answer: B. The model reads every tool definition with every request. SAP's TechEd workshop shows an agent failing with "Input is too long" because of hundreds of generated tools.

4A vendor says hiding fields in the MCP server keeps salary data safe. What should you answer?

Answer: A. Hiding shapes what the agent sees, which helps accuracy and cost. Who may see which data is decided by SAP authorizations and the gateway's policies, not by the tool schema.

5Which question matters most before switching on a generated server for a real agent?

Answer: A. Scope and approval decide both value and risk. The rest are details the builders can settle once the agent's job and its limits are clear.

6SAP updates the sales order API and the server is synchronized. What is the risk?

Answer: D. Curation sits on top of the generated definitions. When the source changes, someone must check that the kept tools and fields still exist and still mean the same thing.
Deep layer · 40 min read

Mental model: the generator translates the interface, you design the tool

An OData service describes what exists: entity sets, fields, keys, actions. A generator can translate that faithfully into MCP: one tool per operation, one parameter per query option, one property per field. That translation is mechanical, so machines do it well.

An agent needs what to do: "find orders on credit block", "show me why 1000004 is short". That is a design decision about one job, one user and one risk level. No generator can make it, because the $metadata doesn't contain it.

So the work splits in two. The generator produces a complete, correct, unusable draft. You produce a short, explained, safe tool set from it, and you keep that curation as a file that survives the next regeneration. Everything below is about doing that second part well.

How it works

From $metadata to tools

flowchart LR
  M["$metadata (EDMX)<br/>entity sets, fields,<br/>keys, actions"] --> G[Generator]
  G --> T["Generated tools<br/>one per operation"]
  T --> C[Curation<br/>a person's decisions]
  CF[(curation file)] --> C
  C --> F[Agent-ready tools<br/>few, described, read-only]
  F --> S[MCP server] --> A[Agent]

An OData V2 $metadata document lists each entity set (such as A_SalesOrder), its entity type with keys and properties, navigation properties (such as to_Item) and function imports (actions such as releaseApprovalRequest). SAP adds V2 annotations: sap:label on every property, sap:creatable, sap:updatable and sap:deletable on entity sets, sap:filterable and sap:sortable on properties (SAP V2 annotations).

A generator maps these mechanically. The course's lab follows the shape of the OASIS OData-to-OpenAPI mapping, whose converters produce operation summaries like "Get entities from Customers" and query parameters for $top, $skip, $filter, $orderby, $select and $expand (OASIS odata-openapi):

In the $metadata Becomes in the generated server
Entity set A list tool and a get-by-key tool
sap:creatable / updatable / deletable not false Create, update and delete tools
Function import One tool per action, usually a POST
Property and its sap:label A field in the input or output schema; the label becomes its description
Sortable properties An $orderby value list with each field ascending and descending
Navigation properties An $expand value list

Integration Suite needs an OpenAPI 3.0.x description of the API artifact as its starting point (Create an MCP Server from an API Artifact). In SAP's TechEd workshop, Joule Studio's flow starts from the API's EDMX (AD263). Neither SAP page publishes the exact naming and description rules its generator uses, so check the real output of yours rather than relying on the course's lab.

What goes wrong with the raw output

SAP's Integration Suite documentation names three kinds of noise in schemas generated from API artifacts: many fields irrelevant to any single use case, enum parameters with long lists of raw values, and backend fields without descriptions. It adds that in multi-tool workflows every tool schema is held in context at once (MCP Server Tool Simplification). To that list, add three agent problems:

  • Descriptions that name the endpoint, not the job. "Get entities from A_SalesOrder" tells the model what the call is, not when it helps.
  • Free-text query languages. A $filter string parameter invites the model to invent OData syntax the service may reject.
  • Write tools by default. Every creatable entity set yields create, update and delete tools.

SAP's own workshop hit these limits. Its notes say the full purchase order service exposes 80+ tools, show a server with 228 tools, and trace a "400 Input is too long for requested model" error to 302 tool definitions across two servers; the fix is to list only the tools the agent needs, roughly 20 or fewer read tools (AD263).

The curation moves

Move Why Where SAP documents it
Delete tools Fewer choices, no write tools Integration Suite (add or delete tools); Joule Studio agent's asset.yaml tool list
Rename, retitle, redescribe The model chooses by description Integration Suite Details tab
Hide input parameters Fewer ways to go wrong Integration Suite input schema
Hide output attributes Smaller answers, less exposure Integration Suite output schema
Restrict enum values Only the options this job needs Integration Suite value help
Pin a hidden parameter's value Keep a fixed sort order or limit Course extra, not an SAP feature

Integration Suite treats hiding as non-destructive: the source API stays as it is and a hidden parameter can be shown again (Tool Simplification). The course lab keeps the same property: your curation is a separate file, and the generated tools are never edited.

When the API changes

Integration Suite's Synchronize pulls the latest OpenAPI description of the source API, lists removed, added and changed tools, resources, authentication policy and schema changes, and waits for you to confirm and save; it exists only for servers created from an API artifact (Synchronize API Changes). Hidden settings are kept where possible, but an attribute that became required is shown again, so the agent always gets a valid schema (Tool Simplification). SAP's architecture guidance adds: version your MCP tool manifests and coordinate breaking schema changes with the agents that use them (SAP Architecture Center).

What makes a good agent-facing tool

The MCP specification fixes the format: a tool has a name, optional title, description, inputSchema, optional outputSchema and optional annotations such as readOnlyHint. Names should be 1 to 128 characters of letters, digits, underscore, hyphen and dot, and unique within a server. If a tool declares an output schema, its structured result must conform to it (MCP tools, 2026-07-28). The content is yours to design, as tool design for agents covers. For generated tools, four checks catch most problems:

  1. The description says when to use the tool, what it returns and that it is read-only.
  2. Every visible parameter has a description, with an example where syntax matters.
  3. Value lists are short, and only offer what this job needs.
  4. No tool changes SAP data unless a person approves the change outside the model.

Build it yourself: generate, check, curate and serve

You will run a small generator over a stand-in of SAP's sales order API, check the result with an agent-readiness linter, curate it down to two tools with a JSON file, serve those tools as a real MCP server, and see what breaks when the API changes.

flowchart LR
  X[salesorder_metadata.xml] -->|generate| G[generated_tools.json<br/>76 tools]
  G -->|lint| R1[findings]
  K[curation.json<br/>your decisions] -->|curate| F[final_tools.json<br/>2 tools]
  G -->|curate| F
  F -->|serve over stdio| S[MCP server] -->|demo, call| D[Calder's orders]

Before you start: complete Set up your computer for this course and Set up for Unit 9, which installs the MCP Python SDK version 2. Reading the Model Context Protocol first helps.

What you need

  • Your orchestrate-course folder with .venv and a unit09 folder.
  • Python 3.10 or later and the mcp package, version 2.x. No accounts and no cost; nothing leaves your computer.
  • Optional, for Step 10 only: your free SAP Business Accelerator Hub key in .env as SAP_API_KEY.
  • About 40 minutes.

The stand-in uses SAP's real entity set, key and field names for the sales order API, taken from SAP's generated model of it (SAP Cloud SDK for JavaScript). It keeps all 22 entity sets but only some of their fields. The labels, which entity sets are writable, the order type OR, the status and block codes, and all data are course values. The orders are Calder's fictional open orders from order to cash.

Step 1: Open the course folder and check the MCP SDK

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

  2. Open a terminal: Terminal > New Terminal.

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

    • Windows (PowerShell):

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

      source .venv/bin/activate
  4. Check the SDK version:

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

    You should see a version starting with 2., such as 2.3.0. If you see 1.x or an error, run pip install --upgrade "mcp[cli]".

  5. Create the lab folder:

    • Windows (PowerShell):

      New-Item -ItemType Directory -Force unit09/odata_mcp
    • macOS / Linux:

      mkdir -p unit09/odata_mcp

Run every command in this topic from the course folder, not from inside unit09.

Step 2: Save the script

  1. In VS Code, right-click unit09, choose New File, name it odata_to_mcp.py, paste the code below and save.
"""Unit 9: generate an MCP server from an OData service's $metadata, then make it fit for an agent.

The generator reads an OData V2 $metadata document (EDMX) and turns every operation into an MCP
tool, the way an automatic generator does. The curation step applies your decisions from
curation.json (keep, rename, describe, hide, pin) and a checker scores both versions.

The metadata is a STAND-IN for SAP's sales order API (API_SALES_ORDER_SRV): entity set, key and
field names come from SAP's published API, but most fields are left out, and the labels,
creatable/updatable flags and all data are course values. Orders belong to Calder Pumpworks,
the course's fictional company.

Commands (run from the orchestrate-course folder):
    python unit09/odata_to_mcp.py generate            # metadata -> generated_tools.json
    python unit09/odata_to_mcp.py lint generated      # agent-readiness check
    python unit09/odata_to_mcp.py curate              # + curation.json -> final_tools.json
    python unit09/odata_to_mcp.py compare             # before and after, side by side
    python unit09/odata_to_mcp.py demo                # start the MCP server and call it
    python unit09/odata_to_mcp.py call --tool NAME --arg name=value   # one call of your own
    python unit09/odata_to_mcp.py sync                # the API changed: what breaks?
    python unit09/odata_to_mcp.py serve               # the MCP server itself (stdio)
    python unit09/odata_to_mcp.py fetch               # optional: SAP's sandbox $metadata (needs SAP_API_KEY)
Built-in modules only, except `serve`, `demo` and `call`, which need the MCP Python SDK (mcp 2.x).
"""
import argparse
import json
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path

HERE = Path(__file__).resolve().parent
WORK = HERE / "odata_mcp"
METADATA = WORK / "salesorder_metadata.xml"
GENERATED = WORK / "generated_tools.json"
CURATION = WORK / "curation.json"
FINAL = WORK / "final_tools.json"

SERVICE = "API_SALES_ORDER_SRV"
NS = {"edmx": "http://schemas.microsoft.com/ado/2007/06/edmx",
      "edm": "http://schemas.microsoft.com/ado/2008/09/edm",
      "m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
      "sap": "http://www.sap.com/Protocols/SAPData"}
SAP = "{" + NS["sap"] + "}"

# ---------------------------------------------------------------- the stand-in service
# name:Type:label. Names are SAP's; labels and the choice of fields are course values.
HEADER = """SalesOrder:String:Sales Document|SalesOrderType:String:Sales Doc. Type|SalesOrganization:String:Sales Org.|
DistributionChannel:String:Distr. Channel|OrganizationDivision:String:Division|SalesGroup:String:Sales Group|
SalesOffice:String:Sales Office|SalesDistrict:String:Sales District|SoldToParty:String:Sold-To Party|
CreationDate:DateTime:Created On|CreatedByUser:String:Created By|LastChangeDate:DateTime:Changed On|
LastChangeDateTime:DateTimeOffset:Time Stamp|PurchaseOrderByCustomer:String:Cust. Reference|
CustomerPurchaseOrderType:String:PO Type|CustomerPurchaseOrderDate:DateTime:Cust. Ref. Date|
SalesOrderDate:DateTime:Document Date|TotalNetAmount:Decimal:Net Value|OverallDeliveryStatus:String:Delivery Status|
TotalBlockStatus:String:Block Status|OverallOrdReltdBillgStatus:String:Billing Status|
TransactionCurrency:String:Doc. Currency|SDDocumentReason:String:Order Reason|PricingDate:DateTime:Pricing Date|
RequestedDeliveryDate:DateTime:Req. Deliv.Date|ShippingCondition:String:Shipping Cond.|
CompleteDeliveryIsDefined:Boolean:Complete Dlv.|ShippingType:String:Shipping Type|
HeaderBillingBlockReason:String:Billing Block|DeliveryBlockReason:String:Delivery Block|
IncotermsClassification:String:Incoterms|CustomerPaymentTerms:String:Payment Terms|PaymentMethod:String:Pmnt Meth.|
SalesOrderApprovalReason:String:Approval Reason|SalesDocApprovalStatus:String:Approval Status|
OverallSDProcessStatus:String:Overall Status|TotalCreditCheckStatus:String:Credit Status|
OverallTotalDeliveryStatus:String:Total Dlv. Status|OverallSDDocumentRejectionSts:String:Rejection Status"""
ITEM = """SalesOrder:String:Sales Document|SalesOrderItem:String:Item|SalesOrderItemCategory:String:Item Category|
SalesOrderItemText:String:Item Description|Material:String:Material|MaterialByCustomer:String:Customer Material|
RequestedQuantity:Decimal:Order Quantity|RequestedQuantityUnit:String:Sales Unit|
ConfdDelivQtyInOrderQtyUnit:Decimal:Confirmed Qty|ItemGrossWeight:Decimal:Gross Weight|ItemWeightUnit:String:Weight Unit|
TransactionCurrency:String:Doc. Currency|NetAmount:Decimal:Net Value|MaterialGroup:String:Material Group|
ProductionPlant:String:Plant|StorageLocation:String:Stor. Location|ShippingPoint:String:Shipping Point|
DeliveryPriority:String:Delivery Prior."""
PARTNER = """SalesOrder:String:Sales Document|PartnerFunction:String:Partner Funct.|Customer:String:Customer|
Supplier:String:Supplier|Personnel:String:Personnel No.|ContactPerson:String:Contact Person|AddressID:String:Address|
VATRegistration:String:VAT Reg. No."""
# Entity sets: (name, keys, fields, navigation properties, writable). The other 19 sets keep only their keys here.
SETS = [
    ("A_SalesOrder", ["SalesOrder"], HEADER, ["to_Item", "to_Partner", "to_PricingElement", "to_Text", "to_BillingPlan",
     "to_PaymentPlanItemDetails", "to_PrecedingProcFlowDoc", "to_SubsequentProcFlowDoc", "to_RelatedObject"], True),
    ("A_SalesOrderItem", ["SalesOrder", "SalesOrderItem"], ITEM, ["to_SalesOrder", "to_Partner", "to_PricingElement",
     "to_ScheduleLine", "to_Text", "to_BillingPlan", "to_RelatedObject", "to_PrecedingProcFlowDocItem",
     "to_SubsequentProcFlowDocItem"], True),
    ("A_SalesOrderHeaderPartner", ["SalesOrder", "PartnerFunction"], PARTNER, ["to_SalesOrder", "to_Address"], True),
    ("A_SalesOrderItemPartner", ["SalesOrder", "SalesOrderItem", "PartnerFunction"], "", ["to_SalesOrder"], True),
    ("A_SalesOrderHeaderPrElement", ["SalesOrder", "PricingProcedureStep", "PricingProcedureCounter"], "",
     ["to_SalesOrder"], True),
    ("A_SalesOrderItemPrElement", ["SalesOrder", "SalesOrderItem", "PricingProcedureStep", "PricingProcedureCounter"],
     "", ["to_SalesOrder"], True),
    ("A_SalesOrderText", ["SalesOrder", "Language", "LongTextID"], "", ["to_SalesOrder"], True),
    ("A_SalesOrderItemText", ["SalesOrder", "SalesOrderItem", "Language", "LongTextID"], "", ["to_SalesOrder"], True),
    ("A_SalesOrderPartnerAddress", ["SalesOrder", "PartnerFunction", "AddressRepresentationCode"], "",
     ["to_SalesOrder"], True),
    ("A_SalesOrderItemPartnerAddress", ["SalesOrder", "SalesOrderItem", "PartnerFunction",
     "AddressRepresentationCode"], "", ["to_SalesOrder"], True),
    ("A_SalesOrderScheduleLine", ["SalesOrder", "SalesOrderItem", "ScheduleLine"], "", [], False),
    ("A_SalesOrderBillingPlan", ["SalesOrder", "BillingPlan"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderBillingPlanItem", ["SalesOrder", "BillingPlan", "BillingPlanItem"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderItemBillingPlan", ["SalesOrder", "SalesOrderItem", "BillingPlan"], "", ["to_SalesOrder"], False),
    ("A_SlsOrderItemBillingPlanItem", ["SalesOrder", "SalesOrderItem", "BillingPlan", "BillingPlanItem"], "",
     ["to_SalesOrder"], False),
    ("A_SlsOrdPaymentPlanItemDetails", ["SalesOrder", "PaymentPlanItem"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderPrecdgProcFlow", ["SalesOrder", "DocRelationshipUUID"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderSubsqntProcFlow", ["SalesOrder", "DocRelationshipUUID"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderItmPrecdgProcFlow", ["SalesOrder", "SalesOrderItem", "DocRelationshipUUID"], "", ["to_SalesOrder"],
     False),
    ("A_SalesOrderItmSubsqntProcFlow", ["SalesOrder", "SalesOrderItem", "DocRelationshipUUID"], "", ["to_SalesOrder"],
     False),
    ("A_SalesOrderRelatedObject", ["SalesOrder", "SDDocRelatedObjectSequenceNmbr"], "", ["to_SalesOrder"], False),
    ("A_SalesOrderItemRelatedObject", ["SalesOrder", "SalesOrderItem", "SDDocRelatedObjectSequenceNmbr"], "",
     ["to_SalesOrder"], False),
]
FUNCTIONS = [("releaseApprovalRequest", "Release Approval"), ("rejectApprovalRequest", "Reject Approval")]


def parse_fields(text):
    fields = []
    for chunk in text.replace("\n", "").split("|"):
        if chunk.strip():
            name, typ, label = chunk.strip().split(":", 2)
            fields.append((name, typ, label))
    return fields


def write_metadata(path, version):
    """Write the stand-in $metadata. Version 2 is a course-made API change for the sync drill."""
    lines = ['<?xml version="1.0" encoding="utf-8"?>',
             f'<edmx:Edmx Version="1.0" xmlns:edmx="{NS["edmx"]}" xmlns:m="{NS["m"]}" xmlns:sap="{NS["sap"]}">',
             '<edmx:DataServices m:DataServiceVersion="2.0">',
             f'<Schema Namespace="{SERVICE}" xml:lang="en" sap:schema-version="1" xmlns="{NS["edm"]}">']
    for name, keys, fields_text, navs, _ in SETS:
        fields = parse_fields(fields_text) or [(k, "Guid" if k.endswith("UUID") else "String", k) for k in keys]
        if version == 2 and name == "A_SalesOrder":
            fields = [f for f in fields if f[0] != "CustomerPurchaseOrderDate"]          # course change: removed
            fields.append(("OverallDeliveryBlockStatus", "String", "Dlv. Block Status"))  # course change: added
        lines.append(f'<EntityType Name="{name}Type" sap:content-version="1"><Key>')
        lines += [f'<PropertyRef Name="{k}"/>' for k in keys]
        lines.append("</Key>")
        for fname, typ, label in fields:
            nullable = "false" if fname in keys else "true"
            lines.append(f'<Property Name="{fname}" Type="Edm.{typ}" Nullable="{nullable}" sap:label="{label}"/>')
        lines += [f'<NavigationProperty Name="{n}"/>' for n in navs]
        lines.append("</EntityType>")
    lines.append(f'<EntityContainer Name="{SERVICE}_Entities" m:IsDefaultEntityContainer="true">')
    for name, _, _, _, writable in SETS:
        flag = "true" if writable else "false"
        lines.append(f'<EntitySet Name="{name}" EntityType="{SERVICE}.{name}Type" sap:creatable="{flag}" '
                     f'sap:updatable="{flag}" sap:deletable="{flag}" sap:content-version="1"/>')
    for fname, label in FUNCTIONS:
        lines.append(f'<FunctionImport Name="{fname}" ReturnType="{SERVICE}.A_SalesOrderType" '
                     f'EntitySet="A_SalesOrder" m:HttpMethod="POST" sap:label="{label}" '
                     f'sap:action-for="{SERVICE}.A_SalesOrderType">'
                     '<Parameter Name="SalesOrder" Type="Edm.String" Mode="In" MaxLength="10"/></FunctionImport>')
    lines += ["</EntityContainer>", "</Schema>", "</edmx:DataServices>", "</edmx:Edmx>"]
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


# ---------------------------------------------------------------- the generator
EDM_TO_JSON = {"String": {"type": "string"}, "Decimal": {"type": "string", "format": "decimal"},
               "DateTime": {"type": "string", "format": "date-time"},
               "DateTimeOffset": {"type": "string", "format": "date-time"},
               "Boolean": {"type": "boolean"}, "Guid": {"type": "string", "format": "uuid"},
               "Int32": {"type": "integer"}}


def read_metadata(path):
    """Parse an OData V2 $metadata document into entity sets and function imports."""
    root = ET.parse(path).getroot()
    schema = root.find("edmx:DataServices/edm:Schema", NS)
    service = schema.get("Namespace")
    types = {}
    for et in schema.findall("edm:EntityType", NS):
        props = []
        for p in et.findall("edm:Property", NS):
            props.append({"name": p.get("Name"), "edm": p.get("Type").split(".")[-1],
                          "label": p.get(SAP + "label", ""),
                          "filterable": p.get(SAP + "filterable", "true") == "true",
                          "sortable": p.get(SAP + "sortable", "true") == "true"})
        types[et.get("Name")] = {"keys": [k.get("Name") for k in et.findall("edm:Key/edm:PropertyRef", NS)],
                                 "props": props,
                                 "navs": [n.get("Name") for n in et.findall("edm:NavigationProperty", NS)]}
    sets, functions = [], []
    container = schema.find("edm:EntityContainer", NS)
    for es in container.findall("edm:EntitySet", NS):
        if es.get(SAP + "addressable", "true") == "false":
            continue
        t = types[es.get("EntityType").split(".")[-1]]
        sets.append({"name": es.get("Name"), **t,
                     **{op: es.get(SAP + op, "true") == "true" for op in ("creatable", "updatable", "deletable")}})
    for fi in container.findall("edm:FunctionImport", NS):
        functions.append({"name": fi.get("Name"), "method": fi.get("{" + NS["m"] + "}HttpMethod", "GET"),
                          "label": fi.get(SAP + "label", ""),
                          "params": [{"name": p.get("Name"), "edm": p.get("Type").split(".")[-1]}
                                     for p in fi.findall("edm:Parameter", NS)]})
    return service, sets, functions


def prop_schema(p):
    schema = dict(EDM_TO_JSON.get(p["edm"], {"type": "string"}))
    if p.get("label"):
        schema["description"] = p["label"]
    return schema


def entity_schema(es):
    return {"type": "object", "properties": {p["name"]: prop_schema(p) for p in es["props"]}}


def tool(name, description, method, path, es_name, kind, properties, required, output):
    return {"name": name, "description": description,
            "inputSchema": {"type": "object", "properties": properties, "required": required},
            "outputSchema": output,
            "annotations": {"readOnlyHint": method == "GET"},
            "http": {"method": method, "path": path, "entity_set": es_name, "kind": kind}}


def generate_tools(path):
    """One tool per operation, with the summaries and query options of the OASIS OData-to-OpenAPI mapping."""
    service, sets, functions = read_metadata(path)
    suffix = "_for_" + service.lower()
    tools = []
    for es in sets:
        n, low = es["name"], es["name"].lower()
        props = {p["name"]: p for p in es["props"]}
        key_params = {k: prop_schema(props[k]) for k in es["keys"]}
        key_path = "(" + ",".join(f"{k}='{{{k}}}'" for k in es["keys"]) + ")"
        sortable = [p["name"] for p in es["props"] if p["sortable"]]
        select = {"type": "array", "items": {"type": "string", "enum": [p["name"] for p in es["props"]]},
                  "description": "Select properties to be returned"}
        expand = {"type": "array", "items": {"type": "string", "enum": es["navs"]},
                  "description": "Expand related entities"}
        query = {"$top": {"type": "integer", "minimum": 0, "description": "Show only the first n items"},
                 "$skip": {"type": "integer", "minimum": 0, "description": "Skip the first n items"},
                 "$filter": {"type": "string", "description": "Filter items by property values"},
                 "$inlinecount": {"type": "string", "enum": ["allpages", "none"],
                                  "description": "Include count of items"},
                 "$orderby": {"type": "array", "description": "Order items by property values",
                              "items": {"type": "string",
                                        "enum": [v for s in sortable for v in (s, s + " desc")]}},
                 "$select": select}
        if es["navs"]:
            query["$expand"] = expand
        listing = {"type": "object", "properties": {"results": {"type": "array", "items": entity_schema(es)}}}
        tools.append(tool("list_" + low + suffix, f"Get entities from {n}", "GET", "/" + n, n, "list",
                          query, [], listing))
        single = {**key_params, "$select": select, **({"$expand": expand} if es["navs"] else {})}
        with_navs = entity_schema(es)
        with_navs["properties"].update({nav: {"type": "array", "items": {"type": "object"},
                                              "description": "Related entities, when expanded"} for nav in es["navs"]})
        tools.append(tool("get_" + low + suffix, f"Get entity from {n} by key", "GET", "/" + n + key_path, n,
                          "get", single, list(es["keys"]), with_navs))
        body = {p["name"]: prop_schema(p) for p in es["props"]}
        if es["creatable"]:
            tools.append(tool("create_" + low + suffix, f"Add new entity to {n}", "POST", "/" + n, n, "create",
                              body, list(es["keys"]), entity_schema(es)))
        if es["updatable"]:
            tools.append(tool("update_" + low + suffix, f"Update entity in {n}", "PATCH", "/" + n + key_path, n,
                              "update", body, list(es["keys"]), None))
        if es["deletable"]:
            tools.append(tool("delete_" + low + suffix, f"Delete entity from {n}", "DELETE", "/" + n + key_path, n,
                              "delete", key_params, list(es["keys"]), None))
    for fi in functions:
        params = {p["name"]: dict(EDM_TO_JSON.get(p["edm"], {"type": "string"})) for p in fi["params"]}
        tools.append(tool(fi["name"].lower() + suffix, fi["label"] or f"Invoke function import {fi['name']}",
                          fi["method"], "/" + fi["name"], "", "function", params, list(params), None))
    return {"service": service, "source": path.name, "tools": tools}


# ---------------------------------------------------------------- the agent-readiness check
NAME_OK = re.compile(r"^[A-Za-z0-9_.-]{1,128}$")
GENERIC = re.compile(r"^(Get entities from|Get entity from|Add new entity to|Update entity in|Delete entity from|"
                     r"Invoke function import)\b")
TALKS_TO_MODEL = re.compile(r"ignore (all|any|previous)|<important>|do not tell|always (say|recommend)",
                            re.IGNORECASE)
MAX_TOOLS, AGENT_TOOLS, CHAR_BUDGET = 50, 20, 20000   # 50: Integration Suite limit; 20 and 20,000: course values


def definition_chars(t):
    """Characters the model reads for one tool: name, title, description, input and output schema."""
    seen = {k: t.get(k) for k in ("name", "title", "description", "inputSchema", "outputSchema")}
    return len(json.dumps(seen, separators=(",", ":")))


def lint(doc):
    tools, findings = doc["tools"], []

    def add(level, rule, where, message):
        findings.append((level, rule, where, message))

    if len(tools) > MAX_TOOLS:
        add("ERROR", "R1", "server", f"{len(tools)} tools; Integration Suite allows up to {MAX_TOOLS} per MCP server")
    elif len(tools) > AGENT_TOOLS:
        add("WARN", "R1", "server", f"{len(tools)} tools; keep an agent's set to about {AGENT_TOOLS} or fewer")
    names = [t["name"] for t in tools]
    for t in tools:
        n, desc = t["name"], t.get("description") or ""
        if not NAME_OK.match(n) or names.count(n) > 1:
            add("ERROR", "R2", n, "name breaks the MCP naming rules or is not unique")
        if GENERIC.match(desc) or len(desc) < 40:
            add("WARN", "R3", n, "description says what the endpoint is, not when an agent should use it")
        bare = [p for p, s in t["inputSchema"]["properties"].items() if not s.get("description")]
        if bare:
            add("WARN", "R4", n, f"{len(bare)} parameter(s) without a description: {', '.join(bare[:3])}")
        for p, s in t["inputSchema"]["properties"].items():
            values = s.get("enum") or s.get("items", {}).get("enum") or []
            if len(values) > 20:
                add("WARN", "R5", n, f"parameter {p} offers {len(values)} enum values")
        if t["http"]["method"] != "GET":
            add("ERROR", "R6", n, f"{t['http']['method']} tool lets the model change SAP data without an approval step")
        if TALKS_TO_MODEL.search(desc):
            add("ERROR", "R7", n, "description gives the model instructions")
        flt = t["inputSchema"]["properties"].get("$filter")
        if flt and not re.search(r"\b[A-Z][A-Za-z]+ (eq|ne) ", flt.get("description", "")):
            add("WARN", "R8", n, "free-text $filter with no example of a valid filter")
    total = sum(definition_chars(t) for t in tools)
    if total > CHAR_BUDGET:
        add("WARN", "R9", "server", f"{total:,} characters of tool definitions; course budget is {CHAR_BUDGET:,}")
    return findings, total


def print_lint(label, doc):
    findings, total = lint(doc)
    errors = sum(1 for f in findings if f[0] == "ERROR")
    print(f"{label}: {len(doc['tools'])} tools, {total:,} characters of tool definitions")
    shown = {}
    for level, rule, where, message in findings:
        shown[rule] = shown.get(rule, 0) + 1
        if shown[rule] <= 2:
            print(f"  {level:5} {rule} {where}: {message}")
        elif shown[rule] == 3:
            print(f"  ...   {rule} more findings like this one")
    print(f"  {errors} errors, {len(findings) - errors} warnings")
    return findings, total


# ---------------------------------------------------------------- curation
def curate(generated, curation):
    """Apply a person's decisions. Hiding is non-destructive: the generated file is never changed."""
    by_name = {t["name"]: t for t in generated["tools"]}
    final, problems = [], []
    for c in curation["tools"]:
        src = by_name.get(c["from"])
        if src is None:
            problems.append(f"{c['name']}: source tool {c['from']} no longer exists")
            continue
        t = json.loads(json.dumps(src))
        t.update({"name": c["name"], "title": c.get("title", c["name"]), "description": c["description"]})
        inp = c.get("input", {})
        props, required = t["inputSchema"]["properties"], t["inputSchema"]["required"]
        pins = inp.get("pin", {})
        for p in inp.get("hide", []):
            if p not in props:
                problems.append(f"{c['name']}: hidden parameter {p} no longer exists")
            elif p in required and p not in pins:
                problems.append(f"{c['name']}: {p} is required now, so it stays visible")
            else:
                props.pop(p)
        for p, values in inp.get("enum", {}).items():
            schema = props.get(p, {})
            target = schema.get("items", schema)
            unknown = [v for v in values if v not in target.get("enum", [])]
            if unknown:
                problems.append(f"{c['name']}: enum values {unknown} not offered by the source")
            target["enum"] = [v for v in values if v in target.get("enum", [])]
        for p, text in inp.get("describe", {}).items():
            if p in props:
                props[p]["description"] = text
        for p, limit in inp.get("max", {}).items():
            if p in props:
                props[p]["maximum"] = limit
        t["inputSchema"]["required"] = [r for r in required if r in props]
        show = c.get("output", {}).get("show")
        if show:
            out = t["outputSchema"]
            entity = out["properties"]["results"]["items"] if "results" in out.get("properties", {}) else out
            missing = [f for f in show if f not in entity["properties"]]
            if missing:
                problems.append(f"{c['name']}: output field(s) {missing} no longer exist")
            expandable = props.get("$expand", {}).get("items", {}).get("enum", [])
            entity["properties"] = {f: s for f, s in entity["properties"].items() if f in show or f in expandable}
            entity["additionalProperties"] = False
        t["http"]["pins"] = pins
        final.append(t)
    return {"service": generated["service"], "server": curation["server"], "tools": final}, problems


# ---------------------------------------------------------------- stand-in data and backend
# Calder Pumpworks' open orders (fictional). Order type, status and block codes are course values, not SAP's:
# TotalCreditCheckStatus 'B' stands for a credit block here, DeliveryBlockReason 'HC' and billing block 'AC' too.
def order(so, party, ref, date, amount, **extra):
    row = {"SalesOrder": so, "SalesOrderType": "OR", "SalesOrganization": "CPUS", "DistributionChannel": "10",
           "OrganizationDivision": "PU", "SoldToParty": party, "PurchaseOrderByCustomer": ref,
           "CustomerPurchaseOrderDate": "2026-10-12", "RequestedDeliveryDate": date, "TotalNetAmount": amount,
           "TransactionCurrency": "USD", "CustomerPaymentTerms": "NT30", "OverallSDProcessStatus": "A",
           "TotalCreditCheckStatus": "A", "DeliveryBlockReason": "", "HeaderBillingBlockReason": ""}
    row.update(extra)
    return row


ORDERS = [
    order("1000001", "10000001", "BWU-PO-5590", "2026-11-06", "29100.00", OverallSDProcessStatus="C"),
    order("1000002", "10000002", "HFS-PO-7702", "2026-10-30", "24288.00", DistributionChannel="20",
          CustomerPaymentTerms="NT45", TotalCreditCheckStatus="B"),
    order("1000003", "10000001", "BWU-PO-5598", "2026-11-02", "12300.00", CustomerPaymentTerms=""),
    order("1000004", "10000001", "BWU-PO-5601", "2026-10-27", "24600.00"),
    order("1000005", "10000002", "HFS-PO-7719", "2026-10-28", "0.00", DistributionChannel="30",
          CustomerPaymentTerms="NT45"),
    order("1000006", "10000001", "BWU-PO-5607", "2026-10-20", "4200.00", HeaderBillingBlockReason="AC"),
    order("1000007", "10000001", "BWU-PO-5611", "2026-11-09", "8400.00", DeliveryBlockReason="HC"),
]
ITEMS = [
    {"SalesOrder": "1000001", "SalesOrderItem": "10", "Material": "CP-ES200", "RequestedQuantity": "4",
     "RequestedQuantityUnit": "PC", "ConfdDelivQtyInOrderQtyUnit": "4", "NetAmount": "16800.00"},
    {"SalesOrder": "1000001", "SalesOrderItem": "20", "Material": "CP-ES300", "RequestedQuantity": "2",
     "RequestedQuantityUnit": "PC", "ConfdDelivQtyInOrderQtyUnit": "2", "NetAmount": "12300.00"},
    {"SalesOrder": "1000004", "SalesOrderItem": "10", "Material": "CP-ES300", "RequestedQuantity": "4",
     "RequestedQuantityUnit": "PC", "ConfdDelivQtyInOrderQtyUnit": "1", "NetAmount": "24600.00"},
    {"SalesOrder": "1000005", "SalesOrderItem": "10", "Material": "CP-SK200", "RequestedQuantity": "40",
     "RequestedQuantityUnit": "PC", "ConfdDelivQtyInOrderQtyUnit": "40", "NetAmount": "0.00"},
]
PARTNERS = [{"SalesOrder": o["SalesOrder"], "PartnerFunction": "SP", "Customer": o["SoldToParty"]} for o in ORDERS]
TABLES = {"A_SalesOrder": ORDERS, "A_SalesOrderItem": ITEMS, "A_SalesOrderHeaderPartner": PARTNERS}
FILTER_TERM = re.compile(r"^\s*([A-Za-z]+)\s+(eq|ne)\s+'([^']*)'\s*$")


class ODataError(Exception):
    pass


def apply_filter(rows, text, fields):
    """Supports what the stand-in needs: Field eq 'x' or Field ne 'x', joined by 'and'."""
    for term in re.split(r"\s+and\s+", text.strip()) if text and text.strip() else []:
        m = FILTER_TERM.match(term)
        if not m:
            raise ODataError(f"Invalid filter term \"{term}\". This service accepts Field eq 'value' or "
                             "Field ne 'value', joined by and.")
        field, op, value = m.groups()
        if field not in fields:
            raise ODataError(f"Property {field} not found in type of this entity set")
        rows = [r for r in rows if (r.get(field, "") == value) == (op == "eq")]
    return rows


def call_backend(t, args):
    """What the generated server would send to SAP, answered from the stand-in tables."""
    http, args = t["http"], {**args, **t["http"].get("pins", {})}
    rows = TABLES.get(http["entity_set"])
    if rows is None or http["method"] != "GET":
        raise ODataError("The stand-in only answers GET on sales orders, items and header partners")
    out = t["outputSchema"]
    listing = "results" in out.get("properties", {})
    entity = out["properties"]["results"]["items"] if listing else out
    visible = [f for f, s in entity["properties"].items() if s.get("type") != "array"]   # navigation comes via $expand
    if http["kind"] == "get":
        keys = [k for k in t["inputSchema"]["required"]]
        rows = [r for r in rows if all(r.get(k) == str(args.get(k, "")) for k in keys)]
        if not rows:
            raise ODataError("Resource not found for the segment " + http["entity_set"])
    rows = apply_filter(rows, args.get("$filter", ""), visible)
    for field in reversed(args.get("$orderby", [])):
        name, _, desc = field.partition(" ")
        rows = sorted(rows, key=lambda r: r.get(name, ""), reverse=bool(desc))
    top = args.get("$top", 50)
    limit = t["inputSchema"]["properties"].get("$top", {}).get("maximum")
    if limit is not None and top > limit:
        raise ODataError(f"$top is {top}; this tool returns at most {limit} rows per call")
    shaped = [{f: r.get(f, "") for f in visible} for r in rows[:top]]
    for nav in args.get("$expand", []):
        child = {"to_Item": ITEMS, "to_Partner": PARTNERS}.get(nav, [])
        for s in shaped:
            s[nav] = [c for c in child if c["SalesOrder"] == s["SalesOrder"]]
    return {"results": shaped} if listing else shaped[0]


# ---------------------------------------------------------------- the MCP server (needs mcp 2.x)
def serve(path):
    import anyio
    import mcp_types as types
    from mcp.server.lowlevel import Server
    from mcp.server.stdio import stdio_server

    doc = json.loads(path.read_text(encoding="utf-8"))
    tools = {t["name"]: t for t in doc["tools"]}

    async def list_tools(ctx, params):
        return types.ListToolsResult(tools=[
            types.Tool(name=t["name"], title=t.get("title"), description=t["description"],
                       input_schema=t["inputSchema"], output_schema=t.get("outputSchema"),
                       annotations=types.ToolAnnotations(read_only_hint=t["annotations"]["readOnlyHint"]))
            for t in tools.values()])

    async def call_tool(ctx, params):
        t = tools.get(params.name)
        try:
            if t is None:
                raise ODataError(f"Tool {params.name} is not exposed by this server")
            data = call_backend(t, params.arguments or {})
        except (ODataError, TypeError, ValueError) as err:
            return types.CallToolResult(content=[types.TextContent(type="text", text=str(err))], is_error=True)
        return types.CallToolResult(content=[types.TextContent(type="text", text=json.dumps(data))],
                                    structured_content=data)

    server = Server(doc.get("server", doc["service"]), version="1.0.0", on_list_tools=list_tools,
                    on_call_tool=call_tool)

    async def main():
        async with stdio_server() as (read, write):
            await server.run(read, write, server.create_initialization_options())

    anyio.run(main)


async def demo_calls(only=None):
    from mcp import Client, StdioServerParameters

    params = StdioServerParameters(command=sys.executable, args=[str(Path(__file__).resolve()), "serve"])
    async with Client(params) as client:
        listed = await client.list_tools()
        print(f"The server offers {len(listed.tools)} tools:")
        for t in listed.tools:
            print(f"  {t.name:24} {t.description[:70]}...")
        calls = only or [("list_sales_orders", {"$filter": "DeliveryBlockReason ne ''"}),
                 ("list_sales_orders", {"$filter": "TotalCreditCheckStatus eq 'B'", "$top": 10}),
                 ("get_sales_order", {"SalesOrder": "1000004", "$expand": ["to_Item"]}),
                 ("list_sales_orders", {"$filter": "TotalNetAmount gt 10000"}),
                 ("list_sales_orders", {"$top": 500}),
                 ("delete_a_salesorder_for_api_sales_order_srv", {"SalesOrder": "1000002"})]
        for name, args in calls:
            try:
                result = await client.call_tool(name, args)
            except RuntimeError as err:        # the client checks results against the tool's output schema
                print(f"\n> {name} {json.dumps(args)}\n  CLIENT REFUSED THE RESULT: {str(err)[:200]}")
                continue
            print(f"\n> {name} {json.dumps(args)}")
            if result.is_error:
                print("  TOOL ERROR: " + (result.content[0].text if result.content else ""))
            elif only:
                print("  OK: " + json.dumps(result.structured_content)[:600])
            elif "results" in result.structured_content:
                rows = result.structured_content["results"]
                print(f"  OK: {len(rows)} order(s): " + ", ".join(
                    f"{r['SalesOrder']} ({r['SoldToParty']}, {r['TotalNetAmount']} {r['TransactionCurrency']})"
                    for r in rows))
            else:
                r = result.structured_content
                print(f"  OK: order {r['SalesOrder']}, requested {r['RequestedDeliveryDate']}, "
                      f"{r['TotalNetAmount']} {r['TransactionCurrency']}")
                for item in r.get("to_Item", []):
                    print(f"      item {item['SalesOrderItem']}: {item['Material']} ordered "
                          f"{item['RequestedQuantity']}, confirmed {item['ConfdDelivQtyInOrderQtyUnit']}")


# ---------------------------------------------------------------- commands
def load(path):
    if not path.exists():
        sys.exit(f"{path.name} not found. Run the earlier step first (see the topic).")
    return json.loads(path.read_text(encoding="utf-8"))


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("command", choices=["generate", "lint", "curate", "compare", "demo", "call", "sync",
                                            "serve", "fetch"])
    parser.add_argument("which", nargs="?", default="generated", choices=["generated", "final"])
    parser.add_argument("--metadata", type=Path, help="a $metadata file to use instead of the stand-in")
    parser.add_argument("--tool", help="call: the tool to call")
    parser.add_argument("--arg", action="append", default=[],
                        help="call: one argument as name=value; leave out the $ (filter=..., top=10, expand=to_Item)")
    args = parser.parse_args()

    if args.command == "generate":
        source = args.metadata or METADATA
        if args.metadata is None:
            write_metadata(METADATA, version=1)
        doc = generate_tools(source)
        GENERATED.write_text(json.dumps(doc, indent=1), encoding="utf-8")
        kinds = {}
        for t in doc["tools"]:
            kinds[t["http"]["kind"]] = kinds.get(t["http"]["kind"], 0) + 1
        print(f"Read {source.name}: service {doc['service']}")
        print(f"Wrote {GENERATED.name}: {len(doc['tools'])} tools: " +
              ", ".join(f"{v} {k}" for k, v in kinds.items()))
        first = doc["tools"][0]
        print(f"Example: {first['name']} - \"{first['description']}\", "
              f"{len(first['inputSchema']['properties'])} parameters, {definition_chars(first):,} characters")
    elif args.command == "lint":
        findings, _ = print_lint(args.which, load(GENERATED if args.which == "generated" else FINAL))
        sys.exit(1 if any(f[0] == "ERROR" for f in findings) else 0)
    elif args.command == "curate":
        final, problems = curate(load(GENERATED), load(CURATION))
        for p in problems:
            print("  CHECK", p)
        FINAL.write_text(json.dumps(final, indent=1), encoding="utf-8")
        print(f"Wrote {FINAL.name}: {len(final['tools'])} tools for server {final['server']}")
        for t in final["tools"]:
            print(f"  {t['name']:24} <- {t['http']['method']} {t['http']['path']}  "
                  f"({len(t['inputSchema']['properties'])} parameters, {definition_chars(t):,} characters)")
    elif args.command == "compare":
        rows = []
        for label, path in (("generated", GENERATED), ("final", FINAL)):
            doc = load(path)
            findings, total = lint(doc)
            writes = sum(1 for t in doc["tools"] if t["http"]["method"] != "GET")
            rows.append((label, len(doc["tools"]), writes, total,
                         sum(f[0] == "ERROR" for f in findings), sum(f[0] == "WARN" for f in findings)))
        print(f"{'':10} {'tools':>6} {'write':>6} {'characters':>11} {'errors':>7} {'warnings':>9}")
        for r in rows:
            print(f"{r[0]:10} {r[1]:>6} {r[2]:>6} {r[3]:>11,} {r[4]:>7} {r[5]:>9}")
        print(f"The final server is {100 - round(rows[1][3] * 100 / rows[0][3])}% smaller than the generated one.")
    elif args.command == "sync":
        v2 = WORK / "salesorder_metadata_v2.xml"
        write_metadata(v2, version=2)
        old, new = load(GENERATED), generate_tools(v2)
        old_tools = {t["name"]: t for t in old["tools"]}
        added = []
        for t in new["tools"]:
            before = old_tools.get(t["name"])
            if before and t["http"]["kind"] == "get":
                gone = set(before["outputSchema"]["properties"]) - set(t["outputSchema"]["properties"])
                came = set(t["outputSchema"]["properties"]) - set(before["outputSchema"]["properties"])
                if gone or came:
                    added.append(f"{t['http']['entity_set']}: removed {sorted(gone)}, added {sorted(came)}")
        print("Changes in the new metadata (a course-made change, not SAP's):")
        for line in added:
            print("  " + line)
        final, problems = curate(new, load(CURATION))
        print("Curation re-applied to the new generation:")
        for p in problems or ["no conflicts"]:
            print("  CHECK " + p if problems else "  " + p)
        print("New fields stay out of the final server until you add them to an output list.")
        sys.exit(1 if problems else 0)
    elif args.command == "demo":
        import anyio
        if not FINAL.exists():
            sys.exit("final_tools.json not found. Run the curate step first.")
        anyio.run(demo_calls)
    elif args.command == "call":
        import anyio
        if not (FINAL.exists() and args.tool):
            sys.exit("Run the curate step first, and name a tool with --tool.")
        tools = {t["name"]: t for t in load(FINAL)["tools"]}
        schema = tools.get(args.tool, {"inputSchema": {"properties": {}}})["inputSchema"]["properties"]
        call_args = {}
        for pair in args.arg:
            name, _, value = pair.partition("=")
            name = name if name in schema or "$" + name not in schema else "$" + name
            kind = schema.get(name, {}).get("type")
            call_args[name] = int(value) if kind == "integer" else value.split(",") if kind == "array" else value
        anyio.run(demo_calls, [(args.tool, call_args)])
    elif args.command == "fetch":
        import os
        import urllib.error
        import urllib.request
        try:
            from dotenv import load_dotenv
            load_dotenv()
        except ImportError:
            pass
        key = os.environ.get("SAP_API_KEY")
        if not key:
            sys.exit("SAP_API_KEY is not set. Put your SAP Business Accelerator Hub key in .env (see the setup topic).")
        url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SALES_ORDER_SRV/$metadata"
        request = urllib.request.Request(url, headers={"APIKey": key, "Accept": "application/xml"})
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                data = response.read()
        except urllib.error.HTTPError as err:
            sys.exit(f"The sandbox answered HTTP {err.code}. 401 means the key is missing or wrong.")
        except urllib.error.URLError as err:
            sys.exit(f"Could not reach sandbox.api.sap.com ({err.reason}). The stand-in still works.")
        target = WORK / "sandbox_metadata.xml"
        WORK.mkdir(parents=True, exist_ok=True)
        target.write_bytes(data)
        print(f"Saved {len(data):,} bytes to {target.relative_to(HERE.parent)}")
    elif args.command == "serve":
        serve(FINAL if FINAL.exists() else GENERATED)


if __name__ == "__main__":
    main()

Step 3: Generate the server

  1. Run the generator:

    python unit09/odata_to_mcp.py generate
  2. You should see:

    Read salesorder_metadata.xml: service API_SALES_ORDER_SRV
    Wrote generated_tools.json: 76 tools: 22 list, 22 get, 10 create, 10 update, 10 delete, 2 function
    Example: list_a_salesorder_for_api_sales_order_srv - "Get entities from A_SalesOrder", 7 parameters, 6,648 characters
  3. Open unit09/odata_mcp/salesorder_metadata.xml and find <EntitySet Name="A_SalesOrder". Then open generated_tools.json and find list_a_salesorder_for_api_sales_order_srv. Look at its $orderby parameter: every sortable field appears twice, once ascending and once with desc.

The tool names follow the pattern of the names in SAP's TechEd workshop (list_<entity>_for_<service>); the descriptions follow the OASIS mapping's summaries. Neither is SAP's generator.

Step 4: Check the generated server

  1. Run the agent-readiness check:

    python unit09/odata_to_mcp.py lint generated
  2. The output starts like this and ends with a count:

    generated: 76 tools, 97,234 characters of tool definitions
      ERROR R1 server: 76 tools; Integration Suite allows up to 50 per MCP server
      WARN  R3 list_a_salesorder_for_api_sales_order_srv: description says what the endpoint is, not when an agent should use it
      WARN  R5 list_a_salesorder_for_api_sales_order_srv: parameter $orderby offers 78 enum values
      WARN  R5 list_a_salesorder_for_api_sales_order_srv: parameter $select offers 39 enum values
      WARN  R8 list_a_salesorder_for_api_sales_order_srv: free-text $filter with no example of a valid filter
      ...
      ERROR R6 create_a_salesorder_for_api_sales_order_srv: POST tool lets the model change SAP data without an approval step
      ...
      WARN  R9 server: 97,234 characters of tool definitions; course budget is 20,000
      33 errors, 105 warnings

The rules:

Rule Checks Source of the threshold
R1 More than 50 tools is an error; more than 20 a warning 50: Integration Suite's limit; 20: SAP's TechEd workshop advice
R2 Names follow the MCP naming rules and are unique MCP specification
R3 Description is generic or under 40 characters Course rule
R4 Parameters without a description Course rule, after SAP's "fields lack descriptions"
R5 More than 20 enum values Course value
R6 Any non-GET tool Course rule: changes need a person's approval
R7 Description gives the model instructions Course rule, see prompt injection and tool poisoning
R8 $filter without a valid example Course rule
R9 Total characters of definitions above 20,000 Course value

Step 5: Save your curation

This file holds your decisions. It keeps two tools, renames them, writes descriptions, hides five query options, limits $top, restricts $expand and lists the output fields. Write tools are simply not listed, so they don't exist in the final server.

  1. In VS Code, right-click unit09/odata_mcp, choose New File, name it curation.json, paste and save.
{
 "server": "calder-sales-orders",
 "tools": [
  {
   "from": "list_a_salesorder_for_api_sales_order_srv",
   "name": "list_sales_orders",
   "title": "List sales orders",
   "description": "Find sales orders by status or block, for example orders on credit, delivery or billing block. Returns at most 50 orders, earliest requested delivery date first, with the fields a person needs to decide the next step. Read-only; it never changes an order. Use get_sales_order for one order's items.",
   "input": {
    "hide": ["$skip", "$inlinecount", "$orderby", "$select", "$expand"],
    "pin": {"$orderby": ["RequestedDeliveryDate"]},
    "describe": {
     "$filter": "Optional. Conditions joined by and, each Field eq 'value' or Field ne 'value'. Fields: SoldToParty, SalesOrganization, DistributionChannel, TotalCreditCheckStatus, DeliveryBlockReason, HeaderBillingBlockReason, CustomerPaymentTerms, OverallSDProcessStatus. Example: DeliveryBlockReason ne ''",
     "$top": "Optional. How many orders to return, 1 to 50. Default 50."
    },
    "max": {"$top": 50}
   },
   "output": {"show": ["SalesOrder", "SoldToParty", "SalesOrganization", "DistributionChannel",
                       "PurchaseOrderByCustomer", "RequestedDeliveryDate", "TotalNetAmount", "TransactionCurrency",
                       "CustomerPaymentTerms", "OverallSDProcessStatus", "TotalCreditCheckStatus",
                       "DeliveryBlockReason", "HeaderBillingBlockReason", "CustomerPurchaseOrderDate"]}
  },
  {
   "from": "get_a_salesorder_for_api_sales_order_srv",
   "name": "get_sales_order",
   "title": "Read one sales order",
   "description": "Read one sales order by its number, optionally with its items (to_Item: material, ordered and confirmed quantity, net value) or partners (to_Partner). Use it after list_sales_orders to see why an order is stuck. Read-only.",
   "input": {
    "hide": ["$select"],
    "enum": {"$expand": ["to_Item", "to_Partner"]},
    "describe": {
     "SalesOrder": "The sales order number, for example 1000004.",
     "$expand": "Optional. Add to_Item for the items, to_Partner for the partners."
    }
   },
   "output": {"show": ["SalesOrder", "SoldToParty", "PurchaseOrderByCustomer", "RequestedDeliveryDate",
                       "TotalNetAmount", "TransactionCurrency", "CustomerPaymentTerms", "TotalCreditCheckStatus",
                       "DeliveryBlockReason", "HeaderBillingBlockReason"]}
  }
 ]
}

Two parts are course extras that SAP's tool simplification doesn't document: pin (a hidden parameter with a fixed value) and max (an upper limit added to a parameter).

Step 6: Curate and compare

  1. Apply the curation:

    python unit09/odata_to_mcp.py curate
    Wrote final_tools.json: 2 tools for server calder-sales-orders
      list_sales_orders        <- GET /A_SalesOrder  (2 parameters, 2,082 characters)
      get_sales_order          <- GET /A_SalesOrder(SalesOrder='{SalesOrder}')  (2 parameters, 1,645 characters)
  2. Check it:

    python unit09/odata_to_mcp.py lint final
    final: 2 tools, 3,727 characters of tool definitions
      0 errors, 0 warnings
  3. Compare both:

    python unit09/odata_to_mcp.py compare
                tools  write  characters  errors  warnings
    generated      76     32      97,234      33       105
    final           2      0       3,727       0         0
    The final server is 96% smaller than the generated one.

Step 7: Serve the tools and call them

The demo command starts the final server as a subprocess over stdio, the way an agent host would, lists its tools and makes six calls.

  1. Run:

    python unit09/odata_to_mcp.py demo
  2. You should see:

    The server offers 2 tools:
      list_sales_orders        Find sales orders by status or block, for example orders on credit, de...
      get_sales_order          Read one sales order by its number, optionally with its items (to_Item...
    
    > list_sales_orders {"$filter": "DeliveryBlockReason ne ''"}
      OK: 1 order(s): 1000007 (10000001, 8400.00 USD)
    
    > list_sales_orders {"$filter": "TotalCreditCheckStatus eq 'B'", "$top": 10}
      OK: 1 order(s): 1000002 (10000002, 24288.00 USD)
    
    > get_sales_order {"SalesOrder": "1000004", "$expand": ["to_Item"]}
      OK: order 1000004, requested 2026-10-27, 24600.00 USD
          item 10: CP-ES300 ordered 4, confirmed 1
    
    > list_sales_orders {"$filter": "TotalNetAmount gt 10000"}
      TOOL ERROR: Invalid filter term "TotalNetAmount gt 10000". This service accepts Field eq 'value' or Field ne 'value', joined by and.
    
    > list_sales_orders {"$top": 500}
      TOOL ERROR: $top is 500; this tool returns at most 50 rows per call
    
    > delete_a_salesorder_for_api_sales_order_srv {"SalesOrder": "1000002"}
      TOOL ERROR: Tool delete_a_salesorder_for_api_sales_order_srv is not exposed by this server

The last three are the point. The tool errors tell the model what to do instead, and the delete tool simply doesn't exist on this server. Those answers come from the stand-in; a real SAP service returns its own OData error texts.

Step 8: Make a call of your own

  1. Read order 1000005 with its items and partners:

    python unit09/odata_to_mcp.py call --tool get_sales_order --arg SalesOrder=1000005 --arg expand=to_Item,to_Partner
  2. Find Hallam's orders (the filter goes in double quotes, which works in PowerShell and on macOS and Linux):

    python unit09/odata_to_mcp.py call --tool list_sales_orders --arg "filter=SoldToParty eq '10000002'" --arg top=5

    After the list of tools, you should see:

    > list_sales_orders {"$filter": "SoldToParty eq '10000002'", "$top": 5}
      OK: {"results": [{"SalesOrder": "1000005", ...}, {"SalesOrder": "1000002", ...}]}

    Leave out the $ in argument names; the script adds it, so PowerShell doesn't read $filter as a variable.

Step 9: The API changes

SAP releases a new version of the API (here a course-made change, not SAP's): CustomerPurchaseOrderDate is gone and a new field appears.

  1. Run the check:

    python unit09/odata_to_mcp.py sync
    Changes in the new metadata (a course-made change, not SAP's):
      A_SalesOrder: removed ['CustomerPurchaseOrderDate'], added ['OverallDeliveryBlockStatus']
    Curation re-applied to the new generation:
      CHECK list_sales_orders: output field(s) ['CustomerPurchaseOrderDate'] no longer exist
    New fields stay out of the final server until you add them to an output list.
  2. Open curation.json, remove "CustomerPurchaseOrderDate" from the show list of list_sales_orders (and the comma before it), and save.

  3. Run python unit09/odata_to_mcp.py sync again. It should end with no conflicts.

  4. Run python unit09/odata_to_mcp.py curate so final_tools.json matches your file.

The new field stays hidden until you choose to show it. An allow-list of output fields fails safe: new data never reaches the agent by accident.

Step 10 (optional): Generate from SAP's sandbox

This step reads the real $metadata of API_SALES_ORDER_SRV from the SAP Business Accelerator Hub sandbox, using the key from calling your first SAP API.

  1. Download it:

    python unit09/odata_to_mcp.py fetch
    Saved ... bytes to unit09/odata_mcp/sandbox_metadata.xml
  2. Generate and check from it:

    python unit09/odata_to_mcp.py generate --metadata unit09/odata_mcp/sandbox_metadata.xml
    python unit09/odata_to_mcp.py lint generated

    Expect more parameters and characters than with the stand-in, because the real service has all its fields. The tool count depends on which entity sets SAP marks as creatable, updatable and deletable.

  3. Run python unit09/odata_to_mcp.py generate (without --metadata) to go back to the stand-in before the exercise.

Step 11: Save your work in Git

  1. Run:

    git add unit09/odata_to_mcp.py unit09/odata_mcp/curation.json
    git commit -m "Unit 9: generate and curate an MCP server from OData metadata"

The generated files can be rebuilt at any time, so only the script and your curation need to be in Git. The curation file is the part worth reviewing in a pull request.

What the code does

Part What it does
SETS, HEADER, ITEM, PARTNER The stand-in service: SAP's entity set, key and field names with course labels
write_metadata Writes the stand-in as an OData V2 $metadata file; version 2 is the course-made change
read_metadata Parses any V2 $metadata: entity types, keys, labels, writable flags, navigation, function imports
generate_tools One tool per operation, with OASIS-style summaries and query options
lint The nine agent-readiness rules and the character count
curate Applies curation.json: keep, rename, describe, hide, pin, limit, restrict enums, allow-list output fields
call_backend Answers GET calls from Calder's stand-in orders, with a small $filter parser
serve The MCP server, built on the SDK's low-level Server, over stdio
demo_calls An MCP client that starts the server and calls it
sync Regenerates from the changed metadata and re-applies your curation

If something goes wrong

What you see What it means What to do
python is not recognized / command not found Python isn't on the path Follow the setup topic again; on macOS or Linux try python3
ModuleNotFoundError: No module named 'mcp' or 'mcp_types' The SDK is missing or the venv is off Check for (.venv), then pip install --upgrade "mcp[cli]"
cannot import name 'Server' or other import errors from mcp SDK version 1 pip install --upgrade "mcp[cli]" and check Step 1 again
generated_tools.json not found A step was skipped Run generate, then curate
json.decoder.JSONDecodeError on curate A typo in curation.json Paste the file again; check commas and quotes
CHECK ...: output field(s) [...] no longer exist Your curation names a field the API doesn't have Fix the show list, or the field name
CLIENT REFUSED THE RESULT The result doesn't match the tool's output schema Your show list or the stand-in data is out of step; run curate again
SAP_API_KEY is not set Step 10 needs your key Add it to .env as in the setup topic
HTTP 401 on fetch The key is wrong Copy it again from the Business Accelerator Hub
Could not reach sandbox.api.sap.com Network or proxy blocks the site Use another network or skip Step 10; the stand-in works offline

The SAP way

Joule Studio: generate, then pick tools per agent

As of 25 October 2026, SAP's reference architecture lists MCP servers as one of three assets you build in Joule Studio, beside agents and agent extensions: Joule Studio "can generate an MCP server from an existing SAP OData or REST API", which deploys to the SAP-managed runtime and attaches to any agent as a tool source (SAP Architecture Center). The page states no release status for this asset.

SAP's TechEd 2026 workshop shows the pro-code flow (AD263):

  1. Intent-based development (see intent-based development with Joule Studio) finds the API in SAP Knowledge Graph, where APIs carry ORD IDs such as sap.s4:apiResource:CE_PURCHASEORDER_0001:v1, and downloads its EDMX.
  2. It writes an MCP server asset with a mcp-translation/ folder holding translation.json, which "maps OData endpoints to named tools", and the API specification.
  3. The agent asset's asset.yaml lists which tools from each MCP server the agent sees. The workshop's fix for "Input is too long" is to cut that list to the tools the agent's instructions use.
  4. At runtime the agent reaches the tools through SAP's Agent Gateway (get_mcp_tools from sap_cloud_sdk.agentgateway); a backend error surfaces as "MCP Builder destination request failed".

The jl CLI's code (version 1.0.10) defines the MCP server asset as an "API-to-MCP tool mapping" with asset.yaml, mcp-translation/translation.json and mcp-translation/api-spec.json (the workshop's generated folder shows api-spec.edmx instead), and its asset.yaml declares an API of kind mcp-server with an ORD ID (npm). jl browse mcp lists the MCP servers on your tenant and their tools. SAP doesn't publish the translation.json format, so edit it through the coding agent and Joule Studio's skills rather than by hand, and review the result in Git.

Two warnings from the workshop matter in real projects. The Knowledge Graph can suggest APIs that exist in SAP's catalog but aren't active on your tenant, which fails at deployment; an API the backend user isn't authorized for answers 403. And the generated tools follow the API's data model exactly. The workshop shows an agent failing on the on-premise purchase order API, whose item entity has no Supplier field; the tenant offered only the cloud edition API.

SAP Integration Suite: generate, refine, synchronize

The MCP gateway creates a server from an OData or REST API artifact deployed on Integration Cell. The API needs an OpenAPI 3.0.0 to 3.0.3 description and OAuth-based authentication, and you select up to 50 resources as tools (Create an MCP Server from an API Artifact). Then, under Design > Integrations and APIs, you open the MCP server artifact, choose Edit, and on MCP Configuration > Tools add or delete tools, change Name, Title and Description, hide input and output attributes, and restrict enum values; composite types (allOf, oneOf, anyOf, not) can't be edited. Save, then Deploy (Refine and Streamline). Tool simplification, the 50-tool limit and support for the 2026-07-28 MCP specification are each GA since 18 October 2026 (What's New). Policies, identity and Developer Hub are in the MCP gateway topic.

Which descriptions the generators produce

Neither SAP source publishes its generator's description rules, so plan to read and rewrite them:

  • In Integration Suite, the documentation says generated schemas expose the full backend schema and many fields lack descriptions; descriptions are editable per tool and per attribute.
  • In Joule Studio, the workshop names tools like list_purchaseorder_for_sap_self and get_a_purchaseorder_for_api_purchaseorder_process_srv, which say which entity and service they read, not what job they serve. SAP's architecture page says Joule Studio MCP servers add semantic enrichment of business capabilities (SAP Architecture Center); how much shows up in the descriptions of your generated tools is something to check on your tenant.

Licensing

Integration Suite's MCP features depend on your service plan (SAP Note 2903776). For Joule Studio, the course's pricing custom agents page tracks what SAP has published. Check your contract before you plan production.

Build vs. SAP

Route Use it when Watch out for
Joule Studio generated server Your agent is a Joule Studio agent on the SAP-managed runtime Tool lists per agent in asset.yaml; generated names; tenant API availability; no published release status for the asset
Integration Suite MCP gateway Agents from several platforms need one governed server with policies Integration Cell, OAuth-only APIs, OpenAPI 3.0.x, 50 tools, service plan
Hand-written MCP server You need logic the API doesn't offer, such as a combined "why is this order stuck" tool You own security, hosting, upgrades and the API policy
Course generator and curation file Learning, reviewing generators, keeping curation as code Not an SAP product; stand-in data only

The course's generator isn't a production route. What carries over is the habit: keep the curation as a reviewed file, lint every regeneration, and never let a generated write tool reach a model without an approval step.

Architecture view

Where it sits. The generated server sits between the agent and a released API. With Joule Studio, both run on the SAP-managed runtime and calls pass the Agent Gateway; with Integration Suite, the server runs on Integration Cell and any MCP client can call it.

flowchart LR
  AG[Agent<br/>Joule Studio or other] --> GW[Agent Gateway or<br/>Integration Suite MCP gateway]
  GW --> MS[Generated and curated<br/>MCP server]
  MS --> API[Released OData API<br/>S/4HANA]
  KG[(Knowledge Graph<br/>or API artifact)] -. generate .-> MS

Non-functional requirements.

Requirement Typical target What breaks if missed
Tool count per agent About 20 read tools or fewer (SAP workshop advice) "Input is too long", wrong tool choice, cost
Characters of tool definitions A budget per agent, measured on every regeneration Slow, expensive calls
Write access None without a person's approval Unintended postings
Change control Curation in Git, lint on every regeneration Silent breakage after an API change
Latency and completeness One filtered call instead of loops or full listings SAP's workshop shows a per-order loop slowing down and a header-first listing that truncated and missed open items

Integration and identity. Data flows over the released API only, which keeps you inside SAP's API policy as described in SAP tools for agents. SAP's guidance says an MCP server must never pass the caller's token through to a downstream API and should use a token exchange that keeps the user context (SAP Architecture Center). Record whose identity reaches S/4HANA for each route before you build.

The decision to record (ADR form from writing a solution design doc):

  • Context: Calder's order-exception agent needs to read sales orders. Generating from API_SALES_ORDER_SRV yields about 80 tools, a third of them writes.
  • Options: A, expose the generated server as is; B, curate the generated server to read tools only; C, hand-write one combined tool.
  • Decision: B. Generate, keep two or three read tools, keep the curation in Git, lint every regeneration. Changes go through the approval flow in human approval in AI workflows.
  • Consequences: Fast to build and to update; someone owns the curation; a combined "why is it stuck" answer still needs the agent to reason over two calls.

What a design review will ask.

  1. Which generated tools were removed, and who approved the remaining list?
  2. Can any path reach a create, update, delete or action tool?
  3. Whose identity does S/4HANA see, and what does that user's role allow?
  4. What happens on the next API release, and which check fails if a field disappears?
  5. How many characters of tool definitions does each request carry?

Production concerns

  • Security and SAP authorizations. Curation isn't an access control. The user's or technical user's SAP roles decide what data comes back; restrict sales organizations there, not in a filter description. Treat descriptions as code: a change to one can steer the model, so review it like a code change.
  • Evaluation. Test the curated server with real questions, as in agent trajectory evaluation: did the agent pick the right tool with the right filter? Run the same tests after every regeneration.
  • Cost. Measure tool-definition size per agent. Every character is sent with every request.
  • Operations. Version the curation with the API version it was built against. Keep the linter in your pipeline so a regeneration that adds write tools fails the build.
  • Clean core. Generate only from released APIs. A generated server over an unreleased or custom service carries that service's upgrade risk into every agent that uses it; see ABAP Cloud and RAP for AI for building a released service when none fits.

Pitfalls

  • Shipping the generated server unchanged. The agent sees every tool, including deletes.
  • Trusting the catalog. An API in the catalog may not be active on your tenant.
  • Leaving $filter free-text without examples. The model invents syntax; give one valid example and the allowed fields.
  • Hiding a required parameter. It can't work; SAP's tool simplification shows such an attribute again on synchronization.
  • Editing generated files by hand. The next regeneration overwrites them. Keep decisions in a separate, reviewed file.
  • Listing everything, then looping. Filter the items you need in one call; SAP's workshop shows a header-first listing that was truncated and reported no open items.

Exercise: add an items tool

Give Calder's agent a third read tool for sales order items.

  1. Open unit09/odata_mcp/curation.json.
  2. After the get_sales_order entry, add a comma and a new entry with "from": "list_a_salesorderitem_for_api_sales_order_srv" and "name": "list_sales_order_items".
  3. Write a description of at least 40 characters that says when to use it (for example, to see which item holds an order back) and that it is read-only.
  4. Hide $skip, $inlinecount, $orderby, $select and $expand; describe $filter with the example SalesOrder eq '1000004'; set "max": {"$top": 50}.
  5. Add an output show list: SalesOrder, SalesOrderItem, Material, RequestedQuantity, RequestedQuantityUnit, ConfdDelivQtyInOrderQtyUnit, NetAmount.
  6. Run python unit09/odata_to_mcp.py curate, then python unit09/odata_to_mcp.py lint final.
  7. Call it: python unit09/odata_to_mcp.py call --tool list_sales_order_items --arg "filter=SalesOrder eq '1000004'".

Done when lint final reports 3 tools with 0 errors and 0 warnings, and the call returns item 10 of order 1000004 with CP-ES300, ordered 4 and confirmed 1. Keep the file: the order-exception agent in later Unit 9 topics can use the same three tools.

Going further

For readers who want to see how OData descriptions become tool schemas, and where the mapping loses meaning.

  • OData to OpenAPI Mapping, OASIS: the reference mapping and its converters. Read how query options, keys and navigation become parameters; Integration Suite's route needs an OpenAPI 3.0.x description, so this is the step before its generator.
  • SAP Annotations for OData Version 2.0: sap:label, sap:quickinfo, sap:filterable, sap:required-in-filter and the writable flags. A smarter generator would hide non-filterable fields from $filter descriptions and make required-in-filter fields required parameters.
  • MCP tools, 2026-07-28: naming rules, output schemas and annotations. Note that annotations such as readOnlyHint are untrusted unless the server is trusted, so a host must not rely on them alone.
  • MCP Server Tool Simplification: SAP's reasoning for agent-facing schemas, and the synchronization rule for hidden attributes that become required.

One open problem is meaning, not syntax. A V2 label like "Credit Status" doesn't say which codes mean "blocked", and code values vary by system. Generators can't fix that; a curated description, or a tool that returns explained statuses, can.

Check yourself

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

1What does a generator map an OData entity set to, when the set is not marked read-only?

Answer: D. Each operation becomes a tool, and the sap:creatable, sap:updatable and sap:deletable flags default to true. That is why the lab's stand-in yields 76 tools, 32 of them writes.

2Why did SAP's TechEd workshop agent fail with "Input is too long for requested model"?

Answer: D. Every tool definition goes to the model with every request. The workshop traces the error to 302 tool definitions and fixes it by listing only the tools the agent uses in asset.yaml.

3In the lab, why does a call to delete_a_salesorder_for_api_sales_order_srv fail on the final server?

Answer: D. The final server is built only from the tools named in curation.json. Write tools that are not listed don't exist on it, which is stronger than hiding parameters or relying on annotations.

4The sync check reports that an output field in your curation no longer exists. What should you do?

Answer: A. Curation is the reviewed source of truth, and generated files are rebuilt. Fixing the curation and re-running the checks keeps the change visible and repeatable.

5A new field appears in the API after synchronization. What happens in the lab's final server, and why is that good?

Answer: B. The output fields are an allow-list. New data reaches the agent only when someone chooses to show it, which fails safe.

6Your team wants to restrict Calder's agent to sales organization CPUS by writing that into the filter description. What is the better design?

Answer: D. Descriptions and schemas shape what the model sees, but they are not access control. SAP authorizations of the calling identity decide which sales organizations come back.

7How do you choose tools for a Joule Studio agent from a generated MCP server with many tools?

Answer: C. In SAP's workshop, the agent's asset.yaml controls which tools from each MCP server the agent sees. The fix for too many tools is to list only those its instructions use.

8Which Integration Suite constraint decides whether an API can become an MCP server at all?

Answer: C. The creation page requires an OData or REST API artifact on Integration Cell with an OpenAPI 3.0.0 to 3.0.3 description and OAuth-based authentication. The 50 limit applies to tools, not entity sets.

Sources

  • Joule Studio (SAP Architecture Center reference architecture, updated 25 October 2026) — read 2026-11-15; three deployable assets (agents, agent extensions, MCP servers); Joule Studio can generate an MCP server from an existing SAP OData or REST API; it deploys to the SAP-managed runtime and can be attached to any agent as a tool source; no release status shown for MCP servers
  • Third-Party MCP Access to SAP Solutions (SAP Architecture Center, updated 26 October 2026) — read 2026-11-15; MCP over raw transactional APIs without semantic enrichment gives weak entity discovery, high token use and, for writes, a risk of wrong business transactions; Joule Studio MCP servers are generated and their lifecycle managed by SAP; version tool manifests; never proxy the caller's token
  • AD263: Build a Supplier Disruption Response Agent on SAP S/4HANA (SAP-samples, SAP TechEd 2026, last commit 28 October 2026) — read 2026-11-15; IBD finds CE_PURCHASEORDER_0001 in the Knowledge Graph, downloads its EDMX and writes a translation.json that maps OData endpoints to named tools; mcp-translation folder; 80+ tools for the full service (228 shown in troubleshooting, 302 across two servers) cause '400 Input is too long'; the agent's asset.yaml lists the tools it uses; keep to roughly 20 or fewer read tools; tools reached through sap_cloud_sdk.agentgateway; 'MCP Builder destination request failed'; jl solution validate checks 9 rules
  • @sap/joule-studio-cli-core-v2 1.0.10 (npm, SAP) — read 2026-11-15 (package code read, not run); asset type mcp-server described as API-to-MCP tool mapping with asset.yaml, mcp-translation/translation.json and mcp-translation/api-spec.json; asset.yaml provides an API of kind mcp-server with an ORD ID customer.build:apiResource:<solution>.<name>:v1; jl browse mcp lists the tenant's MCP servers and their tools
  • MCP Server Tool Simplification (SAP Integration Suite documentation, SAP-docs on GitHub) — read 2026-11-15; servers generated from API artifacts expose the full backend schema; three kinds of noise (irrelevant fields, raw enum values, fields without descriptions); hide parameters and enum values, edit names, titles and descriptions; non-destructive; on synchronization a hidden attribute that became required is shown again
  • Refine and Streamline MCP Server Tool Definitions (SAP-docs on GitHub) — read 2026-11-15; add or delete tools; edit Name, Title and Description in the Details tab; hide or unhide input and output schema attributes; restrict enums; allOf, oneOf, anyOf and not can't be modified; up to 50 tools; save, then deploy
  • Create an MCP Server from an API Artifact, and Synchronize API Changes to Your MCP Server (SAP-docs on GitHub) — read 2026-11-15; only OData and REST API artifacts deployed on Integration Cell; OpenAPI 3.0.0 to 3.0.3; only APIs with OAuth-based authentication; feature availability depends on the service plan (SAP Note 2903776); the companion page synchronize-api-changes-to-your-mcp-server-bd93c74 lists tool, resource, authentication policy and schema changes to confirm, then save
  • What's New for SAP API Management, Cloud Foundry (SAP-docs on GitHub) — read 2026-11-15; MCP Server Tool Simplification, up to 50 tools per MCP server and MCP specification 2026-07-28 support, each generally available 2026-10-18
  • OData to OpenAPI Mapping (OASIS odata-openapi repository) — read 2026-11-15; the OASIS OData TC's mapping and proof-of-concept converters; generated summaries such as 'Get entities from Customers'; $top, $skip, $filter, $orderby (each property ascending and descending), $select and $expand as parameters; the XSLT converter also reads SAP's V2 annotations
  • SAP Annotations for OData Version 2.0 (SAP odata-vocabularies) — read 2026-11-15 (repository copy); sap:label required for properties; sap:creatable, sap:updatable, sap:deletable on entity sets; sap:filterable, sap:sortable, sap:required-in-filter on properties; sap:label on function imports
  • Tools, MCP specification 2026-07-28 — read 2026-11-15 (specification repository copy); tool fields name, title, description, inputSchema, outputSchema, annotations; names 1 to 128 characters from A-Z, a-z, 0-9, underscore, hyphen and dot, unique within a server; structuredContent conforms to outputSchema; annotations untrusted unless from trusted servers; readOnlyHint
  • @sap/cloud-sdk-vdm-sales-order-service 2.1.0 (npm, SAP Cloud SDK) — read 2026-11-15; generated model of API_SALES_ORDER_SRV; entity set names (A_SalesOrder, A_SalesOrderItem, A_SalesOrderHeaderPartner and 19 more), keys, field names and navigation properties used by the course's stand-in; function imports releaseApprovalRequest and rejectApprovalRequest

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