Four Mule 4 apps expose SAP ECC sales-order read and create as three fixed MCP tools (check_sap_connection, get_sales_order, create_sales_order) instead of a raw BAPI passthrough. A System API wraps BAPI_SALESORDER_GETSTATUS and BAPI_SALESORDER_CREATEFROMDAT2 over the SAP connector (JCo) with TESTRUN validation, then create plus BAPI_TRANSACTION_COMMIT in one LUW; a Process API rejects policy violations with 422 before SAP is called; an Experience API gives agents plain-language JSON. Covers JCo packaging pitfalls, 422 versus 503 semantics, on-prem network options, sample payloads and honest limits.
Tags: system-api, jco, sap-ecc, bapi, cross-industry, validate-then-commit, sap, manufacturing, mule-4, order-to-cash, order-management, mcp, api-led, ai-agents, process-api
SAP ECC Sales Orders as Governed MCP Tools for AI Agents: API-Led, Validate-Then-Commit
Deliverable: Four Mule 4 applications that put an SAP ECC sales order behind three fixed, named MCP tools (check_sap_connection, get_sales_order, create_sales_order). An agent can read and place orders in plain language, while a deterministic API-led chain runs the BAPI sequence: business policy first, SAP validation second, commit last.
Objective: Teams want agents to answer "what is on order 125640?" and "place this order" against SAP, and the shortcut is a generic RFC or BAPI caller, which leaves SAP data shapes, error codes and the decision to write to the model's judgment. This blueprint keeps the model out of the SAP sequence: three typed tools, policy in a Process API, SAP's own validation (TESTRUN) before any write, and different status codes for a business rejection and an SAP outage so callers know "do not retry" from "retry".
What's Getting Built
- sap-order-system-api (System API, port 8091) — the only app that talks to SAP, over the Mule SAP connector (JCo). Returns
201, 422 or 503 · GET /ping, GET /api/salesorders/{id}, POST /api/salesorders
- order-process-api (Process API, port 8081) — correlation ID, a line-quantity policy that rejects before SAP is called ·
GET /health, GET /orders/{id}, POST /orders
- order-experience-api (Experience API, port 8080) — plain-language contract for an agent ·
GET /status, GET /orders/{orderNumber}, POST /orders
- sap-order-mcp (agent tool server, port 8066) — MCP streamable-HTTP server, one
mcp:tool-listener flow per tool, each calling only the Experience API · /mcp: check_sap_connection, get_sales_order, create_sales_order
- SAP ECC (consumed) —
RFC_PING, BAPI_SALESORDER_GETSTATUS, BAPI_SALESORDER_CREATEFROMDAT2, BAPI_TRANSACTION_COMMIT/_ROLLBACK
Prerequisites
- An SAP ECC system (application server host, system number, client, language) and a dedicated technical user your SAP team authorizes for
RFC_PING and the BAPIs in the sales areas you need. Request it first. Review SAP licensing for non-dialog access with your SAP account team before production.
- SAP JCo (3.1.13 used here) and the IDoc library (3.1.4), with the native
sapjco3 library for each OS you build or run on. These are SAP-licensed: download them from SAP with your own entitlement, install them into your Maven repository, and never commit or redistribute them.
- Mule 4.11.2 or later, Maven, Mule Enterprise repository credentials in
~/.m2/settings.xml, connectors SAP 5.9.13, HTTP 1.11.1, MCP 1.3.1, and network reach from the System API to the SAP host (see "Choose your path").
- A confirmed-good sales area, plant, sold-to and material, and named SAP and business owners for the quantity policy.
Choose your path
- ECC via JCo and BAPI (as built here) — Choose this when the system is SAP ECC (or another release that exposes these BAPIs over RFC) and the Mule runtime can reach the SAP gateway. It is synchronous, and validate-then-commit maps to
TESTRUN.
- S/4HANA via OData or released APIs (not built here) — Choose this when the target is S/4HANA and you prefer its HTTP APIs to RFC. The layering, fixed tool surface and Process-layer policy carry over, but the System API internals, validation semantics (whether an equivalent of
TESTRUN exists), error mapping and authentication are yours to design and validate.
- Network options for an on-prem SAP — A CloudHub-hosted System API could not reach an SAP host on a private address; calls hung. Options: (1) run the apps on a runtime on a network with SAP reach, as the full chain was proven here; (2) connect CloudHub 2.0 to the SAP network with an Anypoint VPC plus VPN or Transit Gateway (org-level networking access and real infrastructure work); (3) advice, not built: put only the System API on a runtime close to SAP.
Architecture
1. Install JCo and build the System API shell
- Declare the SAP connector (
com.mulesoft.connectors:mule-sap-connector 5.9.13), JCo (com.sap.conn.jco:com.sap.conn.jco.sapjco3), the IDoc library, and a per-OS native library (libsapjco3, classifier external-library).
- Declare the three SAP libraries as
sharedLibraries in the mule-maven-plugin configuration. Never rename or shade the JCo jar: JCo rejects a repackaged archive with "Illegal JCo archive". The same error appears under MUnit and Studio when the dependency is mis-named (for example sapjco3-3.1.13.jar rather than sapjco3.jar).
- Use one Maven profile per target OS (
local for your workstation, ch2 for Linux x86_64 on CloudHub 2.0). A wrong-OS native library fails at startup, not at build.
- Keep non-secret connection values in
config.yaml and the password in a gitignored config-local.yaml loaded by a second <configuration-properties>. In CloudHub 2.0, pass it as a masked secure property.
<sap:sap-config name="SAP_Config">
<sap:simple-connection-provider-connection applicationServerHost="${sap.applicationServerHost}"
systemNumber="${sap.systemNumber}" client="${sap.client}"
username="${sap.user}" password="${sap.password}" language="${sap.language}"/>
</sap:sap-config>
2. Prove connectivity and the read path
GET /ping calls sap:synchronous-remote-function-call key="RFC_PING" and returns status: "OK". It is the cheapest proof of network, credentials and JCo packaging, and backs check_sap_connection.
GET /api/salesorders/{id} calls BAPI_SALESORDER_GETSTATUS with SALESDOCUMENT, zero-padded to 10 characters in DataWeave (as String { format: "0000000000" }). Return statusInfo (STATUSINFO rows) and messages (RETURN rows).
- The first RFC after idle can fail with a CPIC "connection broken" (stale pooled JCo connection); a retry succeeds, so plan a bounded retry.
3. Validate then commit in the System API
- Resolve the request once:
docType, salesOrg, distrChannel, division, poNumber, dates, soldTo and items[], numbering items 000010, 000020... when itemNo is omitted.
- Step 1, validate. Call
BAPI_SALESORDER_CREATEFROMDAT2 with TESTRUN: "X". SAP runs its checks and changes nothing. Read the RETURN rows. Any TYPE of E or A means reject: return 422 with validated: false, submitted: false and the messages, and stop.
- Step 2, submit. Rebuild the same request without
TESTRUN. Inside one <try transactionalAction="ALWAYS_BEGIN"> (create and commit must share one stateful JCo session), call the BAPI again, read SALESDOCUMENT, then call BAPI_TRANSACTION_COMMIT with WAIT: "X". If errors came back or no document number exists, call BAPI_TRANSACTION_ROLLBACK instead.
- Check whether your SAP connector version also commits when the transactional scope ends. If it does, drop the explicit
BAPI_TRANSACTION_COMMIT so the commit runs exactly once, and confirm in SAP that each create produces one document.
- Return
201 only when the commit ran and a document number exists; otherwise 422. A handler around the SAP section returns 503 with retryable: true.
- Carry the caller's product identity in
CUST_MAT35 (customer material number); SAP re-derives line descriptions from the material master.
4. Enforce business policy in the Process API
POST /orders evaluates policy.maxLineQuantity (default 1000 in config.yaml) in DataWeave before any downstream call. For every line over the limit, add an issue such as Line material B-7000 quantity 999999 exceeds policy maximum 1000.
- If there are issues, return
422 with accepted: false, reason: "POLICY_VIOLATION" and issues[]. The System API is never called, so an order your business has already refused costs no SAP round trip.
- Otherwise call the System API with an
http:request accepting 200..599 (success-status-code-validator), so this layer classifies 201, 422 and 503 itself. Do the same from the MCP flows so a rejection reaches the agent as content it can explain. Propagate the status and return correlationId, accepted, sapStatus, salesDocument, validated, submitted and merged messages. Map an unreachable System API to 502.
- The quantity limit is an example. Credit status, allowed materials and sold-to restrictions belong here too, versioned and shared by every consumer.
5. Shape the contract for agents in the Experience API
GET /status returns available plus a summary. GET /orders/{orderNumber} returns found, orderNumber, summary and lineItems[] (material, description, quantity, unit). POST /orders returns placed, orderNumber, summary, reasons[] and correlationId.
- Write summaries as sentences and keep BAPI field names (
DOC_NUMBER) out of this layer.
- Derive
placed from HTTP 201 plus accepted: true, never from message text.
- The HTTP requester already parses JSON, so pass
payload through between layers instead of read(payload, "application/json").
6. Expose three fixed MCP tools
- Add the MCP connector, an
mcp:server-config with mcp:streamable-http-server-connection, and one mcp:tool-listener flow per tool. Each flow calls the Experience API only.
check_sap_connection takes no arguments. get_sales_order requires orderNumber. create_sales_order requires items[], each with required material and quantity (string, "pattern": "^[1-9][0-9]*quot; so only positive whole numbers pass) and optional unit, plant, customerMaterial, plus optional poNumber and soldTo. Set additionalProperties: false on each schema.
- Write each description for the model, including the consequence: "...if it breaks an order policy or SAP rejects it, nothing is created and the reasons are returned."
- Return results with
<mcp:text-tool-response-content text="#[write(payload, 'application/json')]"/>; the text field needs a String.
- Design advice, why fixed tools: never expose a tool that takes a function name and parameters (
call_bapi). A raw passthrough lets the model plan and choose SAP calls, turns every BAPI into a write path, and leaves nothing to test. Three named tools give a closed, reviewable surface where every write takes the same deterministic path. Add another tool (change or cancel order) only with its own validate step and policy.
7. Security and compliance
- Credentials: only the System API holds the SAP password; layers 2 to 4 carry host and port only.
- Least privilege (advice): authorize the technical user only for
RFC_PING and the sales-order and transaction BAPIs, in the sales areas needed; consider separate read and create users.
- Authentication (advice): the four apps here listen on plain HTTP with no client enforcement. Before sharing, add API Manager policies (Client ID Enforcement or OAuth) and TLS, and bind caller identity to the sold-to parties they may order for.
- Writes: a created order is a real SAP document. Start in a sandbox client, require human confirmation for production creates (advice), and log each attempt with correlation ID, PO number, outcome and document number.
- Review SAP licensing for non-dialog access with your SAP account team. Do not redistribute JCo binaries.
Sample payload — create_sales_order, rejected then accepted
// MCP request (JSON-RPC) to {mcp-server-url}/mcp
{ "jsonrpc": "2.0", "id": 3, "method": "tools/call",
"params": { "name": "create_sales_order",
"arguments": { "poNumber": "DEMO-PO-001",
"items": [ { "material": "B-7000", "quantity": "999999", "unit": "ST" } ] } } }
// Tool result text: Process policy stop, SAP never called
{ "placed": false, "orderNumber": "",
"summary": "The order was not placed because it breaks an order policy.",
"reasons": [ "Line material B-7000 quantity 999999 exceeds policy maximum 1000" ],
"correlationId": "{correlationId}" }
// System API: POST /api/salesorders with a valid line ("quantity": "1") returns 201 Created
{ "validated": true, "submitted": true, "salesDocument": "{salesDocument}",
"validationMessages": [ /* SAP RETURN rows */ ], "submissionMessages": [ /* SAP RETURN rows */ ] }
// 422 from SAP validation (unknown material). Nothing created.
{ "validated": false, "submitted": false, "salesDocument": "",
"validationMessages": [ { "messageType": "E", "id": "V1", "number": "382",
"message": "Material ZZ-INVALID is not defined for sales org.1000, distr.chan.10, language DE" } ],
"submissionMessages": [] }
// 503 SAP unavailable: { "error": "SAP_UNAVAILABLE", "message": "{message}", "retryable": true }
Deterministic checks
GET /ping returns 200 with status: "OK" when SAP is reachable. GET /api/salesorders/{id} returns the same result for 126063 and 0000126063.
- Process
POST /orders with any line quantity above policy.maxLineQuantity returns 422 with reason: "POLICY_VIOLATION" and a non-empty issues array, and the System API receives zero requests.
- System
POST /api/salesorders with an unknown material returns 422, validated: false, submitted: false, and no sales document is created. Only the TESTRUN='X' call ran.
- A valid create returns
201 with submitted: true and a non-empty salesDocument that GET /api/salesorders/{salesDocument} can read back. A create returning E/A messages or no document number triggers BAPI_TRANSACTION_ROLLBACK and never returns 201.
- An SAP connectivity failure or timeout returns
503 with retryable: true; a business rejection never does, so circuit breakers can rely on the split.
- The MCP server lists exactly three tools with the schemas above, and
placed is true only when the Process response was 201 with accepted: true.
- Automated suite: this build has no MUnit tests. Write them, mocking the SAP connector operation, to cover every bullet above.
Testing and validation
- Prove each layer with
curl, then test the MCP layer from a real MCP client (Claude, Agentforce or MCP Inspector); curl cannot exercise it.
- Edge case that breaks a naive build: the Process policy casts quantity with
as Number default 0, so "ten" becomes 0 and passes the policy, leaving SAP as the only guard. Validate quantity as a positive integer in the MCP schema and the Process layer.
- Edge case: SAP validates the order as a unit; test a two-line order with one invalid material.
- Edge case: the System API handler catches
ANY and returns 503, so a defect looks like an outage and invites a retry. Narrow it before production.
- Edge case: create is not idempotent. A
503 after the commit but before the response arrives, then a blind retry, can duplicate the order. Check for an existing order with the same PURCH_NO_C before retrying (advice).
- Dates and master data: this build pinned document dates to values its SAP system supports. Set real dates and verify sales area, plant, sold-to and material for yours.
- Scope: one use case (sales order read and create), validated against a shared vendor demo SAP ECC system. The full chain ran locally; a CloudHub-deployed System API could not reach that SAP host, so a cloud-hosted path is untested.
Phased rollout
Phase 1 — Connect
- System API only: prove
/ping, one read and one validate-only rejection against a non-production SAP client. Fix JCo packaging and network reach here.
Phase 2 — Map and validate
- Add Process, Experience and MCP. Agree the policy rules with the business owner, write the MUnit suite, and connect an MCP client. Create only in a sandbox client and have SAP staff confirm each document.
Phase 3 — Production
- Add authentication, TLS, rate limits and human confirmation on creates, restrict the technical user, and settle hosting before promising a cloud path.
Success metrics
- Share of agent order requests by outcome (placed, policy rejection, SAP rejection, outage), with SAP rejection reasons grouped to expose master-data problems.
- Agent-created orders that SAP staff later correct or cancel, duplicate PO numbers, and the
503 rate, with thresholds from your own baseline.
Troubleshooting
- "Illegal JCo archive" at startup, in MUnit, or in Studio — Likely cause: the JCo jar was renamed, versioned, shaded or mis-named in the dependency. Fix: keep JCo as a shared library with its original filename and check the dependency name.
/ping hangs about a minute from CloudHub — Likely cause: the SAP host is on a private address the cloud runtime cannot reach. Fix: use one of the network options.
- First call after idle fails with "connection broken" — Likely cause: a stale pooled JCo connection. Fix: retry once.
- Order not persisted in SAP — Likely cause: create and commit ran outside one
transactionalAction="ALWAYS_BEGIN" scope. Fix: keep both in the same <try>.
- Body says
422 but the HTTP status is 200 or 500 — Likely cause: the listener status is not bound to vars.httpStatus. Fix: bind http:response and http:error-response to it.
- MCP tool fails with "No read or write handler" — Likely cause: the text response received an object. Fix: wrap it in
write(payload, 'application/json').
- CloudHub 2.0 rejects the runtime or asset — Likely cause: the runtime string is not fully qualified (
<base>:<tag>) or accepted by the target, or the asset is not in Exchange yet. Fix: publish with mvn deploy first and check the vCore quota (0.1 vCore, one replica was the minimum).