# CAP in depth for architects: models, services, events and the design review

> Review a CAP application as an architecture board would, from its model, services, events, database, plugins and runtime, and fix Calder's draft.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/cap-for-architects/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

The SAP Cloud Application Programming Model (CAP) is SAP's framework for building business applications on SAP Business Technology Platform (BTP). Developers describe the data and the services in a short modeling language called CDS. CAP then serves those services, stores the data and checks who may see what, mostly without code.

That makes a CAP application unusually easy to review. Its design is written down in a few model files, not hidden in thousands of lines of code. An architect can read the model and answer the board's questions directly: what data the app keeps, which interfaces it offers, who may call them, which SAP systems it reads, and what happens when one of them is down.

This topic is about those questions. [CAP and side-by-side extensions for AI](https://erpfde.com/topics/cap-and-side-by-side-extensions/) showed how to build a CAP extension. Here you review one: Calder Pumpworks' (fictional) distributor order-status app, drafted by a partner, before it goes to production.

### Why it matters to the business

CAP makes a working application fast. The same speed lets a design flaw reach production quickly. Three of them cost the most:

- **Data shown to the wrong customer.** CAP's documentation says that by default a service has no access control: any signed-in user can read every entity. If Calder's distributors sign in to one service, Hallam Fluid Systems could read Brennock Water Utility's orders unless the model filters rows by customer.
- **An app that can't grow the way the business will.** Choosing PostgreSQL, or one database per microservice, can close doors later. CAP's documentation says multitenancy and extensibility aren't yet supported on PostgreSQL. That matters if Calder ever wants to offer the app to its distributors as a service.
- **A design that breaks a policy.** CAP ships an adapter that serves any CAP service to AI agents over the Model Context Protocol (MCP). Its documentation warns that the adapter is not an SAP-endorsed way to give agents access to SAP application APIs. An app that wraps S/4HANA's sales order API and serves it over MCP is a policy problem, not just a technical one.

A design review that reads the model catches all three in an afternoon, before any of them is in production.

### How SAP does it

As of November 2026, the CAP documentation (updated 18 November 2026) and the [SAP BTP Developer's Guide](https://github.com/SAP-docs/btp-developer-guide/blob/main/docs/sap-btp-cloud-foundry-and-sap-btp-kyma-runtimes-with-cap-0f9cfe9.md) describe CAP like this:

- **Two runtimes, one model.** Teams write custom code in Node.js or Java. The models are the same for both. CAP version 10 on npm ([`@sap/cds`](https://www.npmjs.com/package/@sap/cds) 10.2.2 on 27 November 2026) needs Node.js 22.12 or later; CAP Java's active version 5 needs Java 21 or later and works with Spring Boot 4, according to [CAP Java's versions page](https://cap.cloud.sap/docs/java/versions).
- **Databases.** SQLite (and H2 for Java) for development only. SAP HANA Cloud is the recommended production database. PostgreSQL is supported, with the limits above.
- **Platform services through plugins.** SAP and CAP teams maintain `@cap-js` plugins for audit logging, change tracking, attachments, telemetry, event brokers and more. Each plugin page says whether it exists for Node.js, Java or both.
- **Where it runs.** Cloud Foundry or Kyma on BTP. [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/) placed Calder's order-status app on Cloud Foundry.
- **Multitenancy and extensibility built in.** One application can serve many customers with separated data, and customers can add their own fields. Both are switched on, not built by hand. They are covered later in Unit 21.

CAP's libraries cost nothing. They come under the SAP Developer License Agreement (version 3.2 CAP, the `LICENSE` file shipped in the `@sap/cds` package). As read on 27 November 2026, it allows productive use only for applications deployed and run on SAP BTP or another platform licensed from SAP. You pay for the BTP runtime, database and services the app uses. Have your legal team read the agreement before you plan to run a CAP app elsewhere.

### What a design review asks of a CAP application

| Question | A good answer | A red flag |
| --- | --- | --- |
| Who may use each service? | Every service names a role, and partner services filter rows by the signed-in customer | "We'll add security later"; no `@requires` in the model |
| What data does it keep, and who changed it? | Own data only; S/4HANA data is read through released APIs, not copied | Orders copied nightly into the app's own tables |
| What does each service expose? | One service per group of users, with only the fields they need | One service that exposes everything to everyone |
| What happens when S/4HANA is slow or down? | Calls go through a destination; follow-up work is queued and retried | Remote calls inside the user's transaction, no retry |
| Which database, and why? | SAP HANA Cloud, or PostgreSQL with the trade-off written down | SQLite in production; no reason recorded |
| Node.js or Java? | Chosen for the team's skills and the features needed, written down | Chosen by whoever started the project |
| Microservices? | One deployable app until there is a real reason to split | Five services for a two-person team |
| Will agents use it? | Agents get their own reviewed interface; nothing wraps an SAP API | "Just turn on MCP for the whole service" |

> **Note** **For functional consultants:** the model is readable. The access file shows which business roles see which records, which is what your authorization test cases should cover. Ask for it when you write test scripts for a side-by-side extension.

### Questions to ask

Ask the team or partner who built the CAP application:

- Show me the file that says who may do what. Does every service have a role, and does every partner service filter by customer?
- Which S/4HANA APIs does the app call, through which destination, and with whose identity?
- What does the app store itself, and does any of it copy S/4HANA data?
- Why Node.js or Java? Which feature we need is only in one of them?
- Which database is used in production, and what does that choice rule out?
- Which plugins are used, who maintains them, and where would we raise a support case?
- If we later offer this app to other companies, what changes?
- Will any AI agent call this app? Through which interface, and has it been reviewed against SAP's API policy?
- Where will it run in production? If not on SAP BTP, has legal checked the license terms that ship with CAP?

### Common misconceptions

- **"CAP secures the services automatically."** CAP enforces the rules in the model, but there are none until someone writes them. Without them, any signed-in user reads everything.
- **"Each CAP service should be its own microservice."** CAP's guidance is the opposite: keep services in one deployable app, and split only for different scaling, runtimes or lifecycles.
- **"SQLite works in development, so it will do in production."** CAP's documentation says SQLite is for development and not fit for production.
- **"Node.js and Java CAP are identical."** The model is shared, but features differ. For example, Java has built-in retry and circuit breaking for remote calls; Node.js doesn't.
- **"An MCP adapter makes any data agent-ready."** CAP's own documentation rules out using it to proxy SAP application APIs.
- **"CAP is free, so it can run anywhere."** The libraries cost nothing, but the license that ships with them ties productive use to SAP BTP or another platform licensed from SAP.

### Key terms

- **CAP (SAP Cloud Application Programming Model):** SAP's framework for business applications on BTP, in Node.js or Java.
- **CDS (Core Data Services):** CAP's modeling language for data, services and rules.
- **CSN (Core Schema Notation):** the compiled form of a CDS model, a JSON file that tools can read.
- **Service:** a CAP interface for one group of users, usually a set of views on the data.
- **Aspect:** a reusable part of a model, or an addition made in a separate file, such as access rules.
- **Consumption view:** a projection of a remote API that keeps only the fields the app needs, under its own names.
- **Event queue (outbox):** CAP's way of saving follow-up work in the same database transaction and sending it after commit, with retries.
- **Plugin:** an npm or Maven package that adds a capability to CAP, such as audit logging.
- **Multitenancy:** one deployed application serving several customers with separated data.

### Check yourself

1. Calder's distributors will all sign in to one CAP service. What must the design show before go-live?
   - A. That the service runs on Kyma rather than on Cloud Foundry
   - B. Rules that filter every row by the signed-in distributor
   - C. That each distributor gets its own copy of the app
   - D. That the service is published over MCP for their agents

   Answer: B. CAP services have no access control until the model adds it, so any signed-in user would read every row. A partner service needs rules that tie each row to the signed-in customer.

2. Why is a CAP application easier to review than most custom apps?
   - A. Because SAP certifies every CAP application before it is deployed
   - B. Because CAP applications can't call any system outside BTP
   - C. Because its data, services and rules are in a few model files
   - D. Because CAP generates a design document during each build

   Answer: C. CAP serves services from the CDS model, so the design is written down in a few readable files. A reviewer reads the model rather than searching thousands of lines of code.

3. A partner proposes PostgreSQL as the production database. What should a leader ask?
   - A. Whether PostgreSQL can store more than one table per service
   - B. Whether CAP can run on PostgreSQL in development at all
   - C. Whether we might later need multitenancy or customer extensions
   - D. Whether PostgreSQL costs less than SQLite when used in production

   Answer: C. CAP's documentation says multitenancy and extensibility aren't yet supported on PostgreSQL. If Calder may offer the app as a service later, the choice rules that out unless the trade-off is accepted and written down.

4. The team wants five microservices for a small two-person app. What is CAP's guidance?
   - A. Keep one deployable app and split later only for a real reason
   - B. Split now, because CAP services must each be deployed alone
   - C. Split by team member, so each person owns one service
   - D. Split now, because microservices isolate errors for free

   Answer: A. CAP treats services as modules, not deployment units. Its documentation lists different scaling, runtimes or lifecycles as valid reasons to split, and modularization or isolation as false ones.

5. The partner wants to switch on CAP's MCP adapter for a service that reads S/4HANA sales orders. What is the risk?
   - A. MCP can't carry data from CAP services at all
   - B. CAP's docs say it is no endorsed path to SAP application APIs
   - C. The adapter only works with CAP Java applications
   - D. MCP needs its own SAP HANA Cloud instance for every single agent

   Answer: B. The CAP documentation limits the MCP adapter to custom CAP services and says it is not an SAP-endorsed way to expose or proxy SAP application APIs. Serving S/4HANA data through it is a policy question for the board.

6. Which question best tests the team's choice of Node.js or Java?
   - A. Which language has the newest version on its website
   - B. Which language SAP will keep supporting after the other one retires
   - C. Which language makes the CDS model files shorter
   - D. Which needed feature exists only in one, and who maintains it

   Answer: D. The model is the same for both, but features differ, such as built-in retry in Java and some plugins only for Node.js. The decision rests on needed features and team skills.

7. Calder's IT asks to run the order-status app on its own cloud account outside SAP BTP. What should a leader check first?
   - A. Whether CAP can compile its models without SAP HANA Cloud
   - B. Whether the license shipped with CAP allows production use there
   - C. Whether the app needs its own SAP S/4HANA system there
   - D. Whether Node.js runs on that cloud provider's machines

   Answer: B. CAP's libraries cost nothing, but the developer license that ships with them ties productive use to SAP BTP or another platform licensed from SAP. Legal should read the terms before the plan goes further.

## Deep layer

### Mental model

A CAP application is **a model with handlers attached**. The CDS model says what exists: entities, services, events and rules. CAP's generic providers serve it. Custom code only fills the gaps, as event handlers on services.

For an architect, this has one big consequence: **the compiled model is the design document.** `cds compile` turns the CDS files into CSN, a JSON file. Everything a design review asks about the app's structure is in it: which services exist, what each exposes, which remote APIs it projects, which rules guard each entity. What isn't in the model (remote calls in handlers, retries, data stamped by code) is exactly where the review has to read code.

So the review has two halves. Read the model for structure, and read the handlers for the few things the model can't say.

### How it works

```mermaid
flowchart LR
  subgraph Model[CDS model]
    D[db/ domain entities]
    E[srv/external/ imported SAP API]
    S[srv/ services: facades per user group]
    A[srv/access.cds: rules]
  end
  Model -->|cds compile| C[CSN]
  C --> G[Generic providers<br/>OData, REST]
  H[Handlers .js or .java] --> G
  G --> DB[(SQLite in dev<br/>SAP HANA Cloud in prod)]
  G -->|destination| S4[S/4HANA API]
  G --> Q[Event queue<br/>outbox, inbox, tasks]
```

#### Domain models and aspects

Domain entities sit in `db/`. Reusable aspects from `@sap/cds/common` add standard parts: `cuid` a UUID key, `managed` the fields `createdAt`, `createdBy`, `modifiedAt` and `modifiedBy`, filled from the signed-in user. Aspects also let a team put concerns in separate files: the domain model stays clean, and a file such as `access.cds` adds rules to it with `annotate`. The CAP documentation calls this separation of concerns, and uses the same mechanism for verticalization (a third party extends a model it doesn't own) and customization (a SaaS customer adds fields).

**What to look for:** own data only. Data that lives in S/4HANA should be read through an API, not copied into the app's tables.

#### Services as facades

A CAP service is an interface for one use case and one group of users, usually projections on the domain model. CAP's [core concepts](https://cap.cloud.sap/docs/get-started/concepts) call this a use-case oriented service. Calder's app has two: `DistributorService` for distributors and `DeskService` for Calder's customer service desk. Both read the same `Inquiries` table, each with its own projection and rules.

A remote API is imported with `cds import` into `srv/external/` and marked `@cds.external`. A service then projects only the fields it needs, renamed into the app's own words. That projection is a **consumption view**. It keeps the app's interface stable when SAP adds fields, and it keeps out fields the user group shouldn't see, such as order values for a distributor.

**Not microservices.** CAP's documentation draws a hard line: CAP services are modules, microservices are deployment units. Its [late-cut guidance](https://cap.cloud.sap/docs/get-started/features#late-cut-microservices) is to start as one deployable app (a "modulith") and split later. Valid reasons to split are different scaling needs, different runtimes, and coarse-grained subsystems with separate lifecycles. Distributed development, modularization and isolation are listed as false reasons. SAP's BTP Developer's Guide adds that microservices bring complexity and performance losses.

#### Events and event queues

Everything in a CAP runtime is an event: a `READ` request, a custom action, a message from a broker. Services declare their own events in CDS (`event InquiryRaised {...}`) and emit them; other services subscribe. The same code works in one process, through a file-based broker in development, or through SAP Event Mesh and SAP Integration Suite, advanced event mesh in production. S/4HANA's business events arrive the same way; [event-driven agents with SAP events](https://erpfde.com/topics/event-driven-agents-with-sap-events/) shows that side.

The design question is what happens on failure. CAP's [transactional event queues](https://cap.cloud.sap/docs/guides/events/event-queues) store follow-up work in the same database transaction as the business data and send it after commit, with retries and a dead letter queue. The guide describes three uses: an outbox for outbound calls and messages, an inbox for inbound messages, and scheduled tasks. They are on by default. In Node.js a remote service is wrapped with `cds.queued(...)`; in Java with `OutboxService.outboxed(...)`. A sketch of the pattern from the guide, in Node.js:

```javascript
// Sketch (pattern from CAP's event queue guide): send a follow-up only after commit.
const s4notify = cds.queued(await cds.connect.to('CalderNotify'))
this.after('CREATE', 'Inquiries', async (_, req) => {
  await s4notify.send('POST', '/notifications', { inquiry: req.data.ID })
})
```

Two rules from the guide belong in every review: queued handlers must be **idempotent**, because a crash can repeat them; and queued outbound calls must not carry tokens, personal data or secrets in headers, because CAP stores and forwards the headers. A synchronous answer, such as the user waiting for S/4HANA's reply, can't be queued.

#### Access rules

CAP's [authorization guide](https://cap.cloud.sap/docs/guides/security/authorization) states the default plainly: without rules, authenticated users reach all entities. Rules come in three kinds:

- `@requires: 'Distributor'` on a service: only that role may enter.
- `@restrict` with `grant` and `to` on an entity: which role may read, create, update or delete.
- `where` in a restriction: instance-based access, such as `customer = $user.customer`. It filters `READ` results and rejects `UPDATE` and `DELETE` on other rows.

Two details decide real designs. First, user attributes such as `$user.customer` come from the user's token. If the attribute is empty, the user sees nothing, which is safe. Adding `or $user.customer is null` makes an empty attribute mean "everything"; the guide warns that such unrestricted attributes need very careful design. Second, the runtimes differ on `CREATE`: Java checks the `where` condition against the input data, while Node.js supports only static expressions there. In Node.js, code must set the customer from the user rather than trust the request body.

#### Reuse and composition

CAP projects can import other CAP projects as packages: models, code, initial data and texts. CAP's [service composition guide](https://cap.cloud.sap/docs/guides/integration/reuse-and-compose) describes reuse services, prebuilt extension packages, prebuilt integration packages (for example for S/4HANA or SuccessFactors) and business data packages such as country and currency lists, combined into a composite application. The importing project adapts what it reuses with its own projections and `extend` statements, without changing the package.

For an architect, a reuse package is a dependency with an owner and a release cycle. Ask who maintains it, how a breaking change reaches the apps that import it, and whether the package's access rules travel with it or each app adds its own.

#### Databases and schema changes

| Database | Use | What to know |
| --- | --- | --- |
| SQLite, H2 (Java) | Development and tests | In memory, created from the model on start. CAP says not fit for production |
| SAP HANA Cloud | Recommended for production | Deployed through HDI containers; full schema evolution and multitenancy |
| PostgreSQL | Production, with limits | Through `@cap-js/postgres`, on BTP via the hyperscaler option; no multitenancy or extensibility yet |

In development CAP drops and recreates tables. Production can't do that without losing data. For SAP HANA, HDI handles the change when the new model is deployed. For other databases, CAP's schema evolution guide generates a migration script from the old and new model (`cds deploy --script --delta-from ...`) for someone to review, and lists model changes it disallows because they would lose data. Either way, a review asks who approves model changes that touch stored data.

#### Plugins

A plugin is an npm package (Node.js) or Maven dependency (Java) that adds a capability by configuration. The [plugins page](https://cap.cloud.sap/docs/plugins/) lists the `@cap-js` plugins maintained with SAP teams. Two review points: availability differs by runtime (as read on 27 November 2026, Data Privacy, in beta, and ABAP RFC are listed for Node.js only, and the AI plugin's Java version is in alpha), and support differs by origin (SAP support covers SAP's plugins; community plugins are out of scope for incidents).

#### Node.js or Java

| | Node.js | Java |
| --- | --- | --- |
| Current version (27 Nov 2026) | `@sap/cds` 10, Node.js 22.12 or later | CAP Java 5, Java 21 or later (25 recommended), Spring Boot 4 |
| Remote call resilience (retry, circuit breaking) | Not in CAP; build or add it | Built in |
| `where` checked on `CREATE` input | Static expressions only | Yes |
| Plugins listed for one runtime only | Data Privacy (beta), ABAP RFC, GraphQL adapter, WebSocket | None found in the list |
| Team fit | JavaScript teams, fast local start | Java and Spring teams |

The model and the architecture are the same either way. The [features overview](https://cap.cloud.sap/docs/get-started/feature-matrix) is the page to check for the feature your design needs, on the day you decide.

#### Multitenancy and extensibility hooks

`cds add multitenancy` adds `@sap/cds-mtxs` and an MTX sidecar. The app then waits for subscriptions: SAP BTP's SaaS Provisioning service sends a subscribe event, and the MTX services create the tenant's database container through Service Manager. `cds add extensibility` lets subscribers add their own fields and entities, and needs a multitenant app. Neither is needed for Calder's single-company app, but a review should ask whether they might be, because the database choice and the model's structure decide whether they can be added later. The multitenancy topic later in Unit 21 builds one.

### Build it yourself: review Calder's order-status app

You will build Calder's distributor order-status app as the partner drafted it, compile its model, and run a design review script that reads the compiled model and the app's configuration. The draft fails eight checks. You fix the model, run the review again, add the handlers, and prove the access design against the running app.

```mermaid
flowchart LR
  F[order-status<br/>CDS files] -->|cds compile| C[review/srv.csn]
  C --> R[cap_review.py<br/>rules R01-R08]
  P[package.json] --> R
  R --> M[cap_review.md]
  F -->|cds watch| W[App on port 4004<br/>S/4HANA mocked]
  T[try_order_status.py] -->|hallam, brennock, desk| W
```

**Before you start:** finish [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/), which install Node.js and the CAP development kit (`cds`). [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/) is not needed for this topic. This walkthrough doesn't repeat those steps.

> **Note** New words in this section:
> - **CSN:** the compiled model, a JSON file. The review script reads it instead of the `.cds` files.
> - **Mocked user:** a test user CAP accepts in development, with a name, password, roles and attributes set in `package.json`.
> - **Destination:** a BTP setting that holds a remote system's URL and credentials, so the app doesn't. [Connectivity](https://erpfde.com/topics/btp-connectivity/) covers it.
> - **Profile:** a set of settings CAP uses in one situation, such as `[development]` or `[production]`.

#### What you need

- Your course folder with Node.js 22 or later and `@sap/cds-dk` version 10 (from the Unit 5 setup), and Python 3.
- About 60 minutes.
- Cost: free. Everything runs on your computer; S/4HANA is mocked with five made-up orders.
- No SAP system or BTP account.

#### Step 1: Open the course folder and check the tools

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. Check the tools (the same on every system):

   ```bash
   node --version
   cds version
   ```

   You should see `v22` or `v24` for Node.js, and `@sap/cds-dk` with a version starting `10`.

#### Step 2: Create the project

1. Make the `unit21` folder if you don't have it, and create the CAP project in it:

   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit21
     cd unit21
     cds init order-status --add nodejs
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit21
     cd unit21
     cds init order-status --add nodejs
     ```

   **What success looks like:**

   ```text
   Successfully initialized CAP project
   ```

2. Install the project's libraries (the same on every system):

   ```bash
   cd order-status
   npm install
   cd ..
   ```

   Warnings about funding are normal. You stay in `unit21` from now on.

#### Step 3: Write the partner's draft

These files are the draft as the partner handed it over. Create each one inside `unit21/order-status`, paste and save.

1. `db/schema.cds`, the app's own data:

```cds
// Calder's own data for the distributor order-status app (fictional company).
// Sales orders stay in S/4HANA; this app stores only what distributors add.
namespace calder.orderstatus;
using { cuid, managed } from '@sap/cds/common';

entity Inquiries : cuid, managed {
  customer   : String(10);   // the distributor's customer number in CP10
  salesOrder : String(10);
  question   : String(500);
  status     : String(10) default 'OPEN';   // OPEN or ANSWERED (course values)
  answer     : String(1000);
}

entity StatusNotes {
  key salesOrder : String(10);
      note       : String(500);
}
```

2. Create the folder `srv/external`, and in it `API_SALES_ORDER_SRV.cds`. It is a hand-written slice of SAP's Sales Order API with the real field names; on a project you would generate the full file with `cds import`:

```cds
// A hand-written slice of SAP's Sales Order API (API_SALES_ORDER_SRV, entity A_SalesOrder).
// On a project you generate the full model with "cds import"; this keeps only the
// fields this topic uses, under the names the real API uses.
@cds.external : true
service API_SALES_ORDER_SRV {
  entity A_SalesOrder {
    key SalesOrder              : String(10);
        SalesOrganization       : String(4);
        DistributionChannel     : String(2);
        SoldToParty             : String(10);
        PurchaseOrderByCustomer : String(35);
        RequestedDeliveryDate   : Date;
        TotalNetAmount          : Decimal(16, 3);
        TransactionCurrency     : String(5);
        OverallSDProcessStatus  : String(1);
        OverallDeliveryStatus   : String(1);
        DeliveryBlockReason     : String(2);
  }
}
```

3. Create the folder `srv/external/data`, and in it `API_SALES_ORDER_SRV-A_SalesOrder.csv`. CAP loads it as the mocked S/4HANA's data. Hallam is customer `10000002`, Brennock `10000001`:

```text
SalesOrder,SalesOrganization,DistributionChannel,SoldToParty,PurchaseOrderByCustomer,RequestedDeliveryDate,TotalNetAmount,TransactionCurrency,OverallSDProcessStatus,OverallDeliveryStatus,DeliveryBlockReason
1000002,CPUS,20,10000002,HFS-PO-7760,2026-11-06,24288.000,USD,A,A,
1000005,CPUS,20,10000002,HFS-PO-7771,2026-11-09,3800.000,USD,A,A,
1000007,CPUS,10,10000001,BWU-PO-5598,2026-11-12,8400.000,USD,A,A,HC
1000011,CPUS,10,10000001,BWU-PO-5633,2026-11-13,67200.000,USD,A,A,
1000014,CPUS,20,10000002,HFS-PO-7781,2026-11-20,5700.000,USD,A,A,
```

> **Warning** The status values `A` and the block code `HC` are made up for this lab. Status and block codes are configured in each SAP system; read them from your own system, never from a tutorial.

4. `srv/distributor-service.cds`, what a distributor sees. `@audience: 'partner'` is a course annotation that tells the review script that people outside Calder use this service; CAP ignores it:

```cds
// What a distributor sees: its orders from S/4HANA and its own inquiries.
using { API_SALES_ORDER_SRV as S4 } from './external/API_SALES_ORDER_SRV';
using { calder.orderstatus as my } from '../db/schema';

@path: '/distributor'
@audience: 'partner'        // course annotation: people outside Calder use this service
@mcp                        // the partner wants agents to read order status too
service DistributorService {

  @readonly
  entity Orders as projection on S4.A_SalesOrder;

  entity Inquiries as projection on my.Inquiries;

  event InquiryRaised { inquiry: UUID; salesOrder: String(10); customer: String(10); }
}
```

5. `srv/desk-service.cds`, what Calder's customer service desk uses:

```cds
// What Calder's customer service desk uses: every inquiry, and a way to answer it.
using { calder.orderstatus as my } from '../db/schema';

@path: '/desk'
service DeskService {
  entity Inquiries as projection on my.Inquiries actions {
    action answer(text: String(1000)) returns Inquiries;
  };
  entity StatusNotes as projection on my.StatusNotes;
}
```

6. Replace the whole of `package.json` with the draft's configuration:

```json
{
  "name": "order-status",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "@sap/cds": "^10"
  },
  "devDependencies": {
    "@cap-js/sqlite": "^3"
  },
  "scripts": {
    "start": "cds-serve"
  },
  "private": true,
  "cds": {
    "requires": {
      "API_SALES_ORDER_SRV": {
        "kind": "odata-v2",
        "model": "srv/external/API_SALES_ORDER_SRV"
      },
      "[production]": {
        "db": "sqlite",
        "auth": "xsuaa"
      }
    }
  }
}
```

#### Step 4: Create the review script

1. In `unit21` (not inside `order-status`), create `cap_review.py`, paste this and save. It uses only Python's built-in modules.

```python
"""Design review of a CAP application from its compiled model (CSN) and package.json.

Reads the model that "cds compile ... --to csn" writes, checks it against eight
course rules an architecture board would ask about, prints the findings and
writes cap_review.md. Built-in modules only; no randomness.

  python cap_review.py --sample              # the partner's draft, built in
  python cap_review.py                       # review/srv.csn + order-status/package.json
  python cap_review.py --csn FILE --package FILE

Rules R01-R08 are course rules for Calder Pumpworks (fictional), drawn from the
CAP documentation; they are not an SAP checklist.
"""
import argparse
import json
import sys
from pathlib import Path

READ_LIKE = {"READ", "UPDATE", "DELETE", "*", "WRITE"}

# The partner's draft of the distributor order-status app, as the compiler
# writes it (only the parts the rules read).
SAMPLE_CSN = {
    "definitions": {
        "calder.orderstatus.Inquiries": {"kind": "entity", "elements": {
            "ID": {"key": True}, "createdAt": {}, "createdBy": {}, "modifiedAt": {},
            "modifiedBy": {}, "customer": {}, "salesOrder": {}, "question": {},
            "status": {}, "answer": {}}},
        "calder.orderstatus.StatusNotes": {"kind": "entity", "elements": {
            "salesOrder": {"key": True}, "note": {}}},
        "API_SALES_ORDER_SRV": {"kind": "service", "@cds.external": True},
        "API_SALES_ORDER_SRV.A_SalesOrder": {"kind": "entity", "elements": {
            "SalesOrder": {"key": True}, "SoldToParty": {}, "TotalNetAmount": {}}},
        "DistributorService": {"kind": "service", "@path": "/distributor",
                               "@audience": "partner", "@mcp": True},
        "DistributorService.Orders": {"kind": "entity", "@readonly": True,
            "projection": {"from": {"ref": ["API_SALES_ORDER_SRV.A_SalesOrder"]}}},
        "DistributorService.Inquiries": {"kind": "entity",
            "projection": {"from": {"ref": ["calder.orderstatus.Inquiries"]}}},
        "DistributorService.InquiryRaised": {"kind": "event"},
        "DeskService": {"kind": "service", "@path": "/desk"},
        "DeskService.Inquiries": {"kind": "entity",
            "projection": {"from": {"ref": ["calder.orderstatus.Inquiries"]}},
            "actions": {"answer": {"kind": "action"}}},
        "DeskService.StatusNotes": {"kind": "entity",
            "projection": {"from": {"ref": ["calder.orderstatus.StatusNotes"]}}},
    }
}
SAMPLE_PACKAGE = {
    "name": "order-status",
    "dependencies": {"@sap/cds": "^10"},
    "cds": {"requires": {
        "API_SALES_ORDER_SRV": {"kind": "odata-v2",
                                "model": "srv/external/API_SALES_ORDER_SRV"},
        "[production]": {"db": "sqlite", "auth": "xsuaa"}}},
}


def load(path):
    try:
        return json.loads(Path(path).read_text(encoding="utf-8-sig"))
    except FileNotFoundError:
        sys.exit(f"Not found: {path}. Run the compile step first (Step 5), or use --sample.")
    except json.JSONDecodeError as err:
        sys.exit(f"Not valid JSON: {path} ({err}).")


def as_list(value):
    if value is None:
        return []
    return value if isinstance(value, list) else [value]


class Model:
    def __init__(self, csn):
        self.defs = csn.get("definitions", {})
        self.external = {n for n, d in self.defs.items()
                         if d.get("kind") == "service" and d.get("@cds.external")}
        self.services = sorted(n for n, d in self.defs.items()
                         if d.get("kind") == "service" and n not in self.external)

    def members(self, service, kind):
        prefix = service + "."
        return [n for n, d in self.defs.items()
                if n.startswith(prefix) and "." not in n[len(prefix):]
                and d.get("kind") == kind]

    def source(self, entity):
        proj = self.defs[entity].get("projection") or \
            (self.defs[entity].get("query") or {}).get("SELECT") or {}
        ref = (proj.get("from") or {}).get("ref") or []
        return ref[0] if ref else None

    def is_external(self, name):
        return any(name and name.startswith(s + ".") for s in self.external)

    def own_entities(self):
        out = []
        for n, d in self.defs.items():
            if d.get("kind") != "entity" or n.startswith("sap.") or self.is_external(n):
                continue
            if any(n.startswith(s + ".") for s in self.services):
                continue
            if n.endswith(".texts"):
                continue
            out.append(n)
        return out


def short(name):
    return name.split(".")[-1]


def check(model, pkg):
    """Return a list of (rule, status, subject, message)."""
    f = []
    requires = (pkg.get("cds") or {}).get("requires") or {}
    prod = requires.get("[production]") or {}

    # R01: every service says who may use it.
    for s in model.services:
        d = model.defs[s]
        if d.get("@requires") or d.get("@restrict") or d.get("@protocol") == "none":
            f.append(("R01", "OK", s, f"requires {as_list(d.get('@requires') or 'restrict')}"))
            continue
        open_parts = [short(e) for e in model.members(s, "entity")
                      if not (model.defs[e].get("@restrict") or model.defs[e].get("@requires"))]
        open_parts += [short(a) for a in model.members(s, "action")
                       if not model.defs[a].get("@requires")]
        if open_parts:
            f.append(("R01", "FAIL", s, "no @requires and nothing restricted in "
                      + ", ".join(open_parts) + "; any signed-in user can use it"))
        else:
            f.append(("R01", "OK", s, "every entity and action is restricted"))

    # R02: services for people outside Calder filter rows by the user.
    for s in model.services:
        if model.defs[s].get("@audience") != "partner":
            continue
        for e in model.members(s, "entity"):
            rules = as_list(model.defs[e].get("@restrict"))
            if not rules:
                f.append(("R02", "FAIL", e, "partner service, but no @restrict: every "
                          "distributor sees every row"))
                continue
            gaps, creates = [], False
            for r in rules:
                grants = {g.upper() for g in as_list(r.get("grant", "*"))}
                if "CREATE" in grants:
                    creates = True
                if grants & READ_LIKE and "$user" not in json.dumps(r.get("where", "")):
                    gaps.append("/".join(sorted(grants)))
            if gaps:
                f.append(("R02", "FAIL", e, "grant " + ", ".join(gaps)
                          + " has no where condition on $user"))
            else:
                note = " (CREATE: Node.js doesn't check where on input; set the field in a handler)" if creates else ""
                f.append(("R02", "OK", e, "rows filtered by the user" + note))

    # R03: remote APIs come in through consumption views that list their fields.
    for s in model.services:
        for e in model.members(s, "entity"):
            src = model.source(e)
            if not model.is_external(src):
                continue
            proj = model.defs[e].get("projection") or {}
            cols = proj.get("columns")
            if not cols or "*" in cols:
                f.append(("R03", "FAIL", e, f"projects all of {src}; list only the fields this use case needs"))
            else:
                f.append(("R03", "OK", e, f"consumption view of {short(src)} with {len(cols)} fields"))

    # R04: no MCP or agent protocol on top of an SAP application API.
    for s in model.services:
        d = model.defs[s]
        if not any(k.startswith(("@mcp", "@agent")) and d[k] for k in d):
            continue
        remote = [short(e) for e in model.members(s, "entity") if model.is_external(model.source(e))]
        if remote:
            f.append(("R04", "FAIL", s, "served over MCP or A2A but reads an SAP API ("
                      + ", ".join(remote) + "); CAP's docs say the adapter is not an endorsed path "
                      "for SAP application APIs"))
        else:
            f.append(("R04", "OK", s, "agent protocol on own data only"))
    if not any(x[0] == "R04" for x in f):
        f.append(("R04", "OK", "(all services)", "no MCP or agent protocol declared"))

    # R05: own entities record who changed them.
    for e in model.own_entities():
        els = model.defs[e].get("elements") or {}
        if {"createdBy", "modifiedAt"} <= set(els):
            f.append(("R05", "OK", e, "managed: who and when are recorded"))
        else:
            f.append(("R05", "WARN", e, "no createdBy/modifiedAt; add the managed aspect"))

    # R06: the production database.
    db = prod.get("db")
    kind = db.get("kind") if isinstance(db, dict) else db
    if kind == "hana":
        f.append(("R06", "OK", "package.json", "production database SAP HANA"))
    elif kind == "postgres":
        f.append(("R06", "WARN", "package.json", "PostgreSQL: CAP doesn't support multitenancy "
                  "or extensibility on it yet; record why"))
    elif kind in ("sqlite", "sql"):
        f.append(("R06", "FAIL", "package.json", "production database SQLite; CAP says SQLite "
                  "is for development, not for production"))
    else:
        f.append(("R06", "WARN", "package.json", "production database not stated"))

    # R07: every remote service has a destination in production.
    for ext in sorted(model.external):
        conf = requires.get(ext)
        if not conf:
            f.append(("R07", "FAIL", ext, "not configured in cds.requires"))
            continue
        dest = ((conf.get("[production]") or {}).get("credentials") or {}).get("destination") \
            or ((prod.get(ext) or {}).get("credentials") or {}).get("destination")
        if dest:
            f.append(("R07", "OK", ext, f"production calls go through destination {dest}"))
        else:
            f.append(("R07", "FAIL", ext, "no destination for production; credentials "
                      "would end up in the app's own configuration"))

    # R08: multitenancy and extensibility need SAP HANA.
    flags = [k for k in ("multitenancy", "extensibility")
             if requires.get(k) or prod.get(k)]
    if not flags:
        f.append(("R08", "OK", "package.json", "single-tenant, no extensibility"))
    elif kind == "hana":
        f.append(("R08", "OK", "package.json", " and ".join(flags) + " on SAP HANA"))
    else:
        f.append(("R08", "FAIL", "package.json", " and ".join(flags)
                  + f" on {kind or 'an unstated database'}; CAP supports them on SAP HANA"))
    return f


def facts(model, pkg):
    deps = sorted({**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})})
    plugins = [d for d in deps if d.startswith(("@cap-js/", "@sap/cds-"))]
    return {
        "runtime": "Node.js" if pkg.get("dependencies", {}).get("@sap/cds") else "unknown",
        "services": ", ".join(short(s) for s in model.services),
        "remote APIs": ", ".join(sorted(model.external)) or "none",
        "plugins": ", ".join(plugins) or "none",
    }


def report(findings, info, name):
    counts = {s: sum(1 for x in findings if x[1] == s) for s in ("FAIL", "WARN", "OK")}
    lines = [f"# CAP design review: {name}", "",
             "Course rules R01-R08 (Calder Pumpworks, fictional). Not an SAP checklist.", "",
             "| Fact | Value |", "| --- | --- |"]
    lines += [f"| {k} | {v} |" for k, v in info.items()]
    lines += ["", "| Rule | Status | Where | Finding |", "| --- | --- | --- | --- |"]
    lines += [f"| {r} | {s} | `{w}` | {m} |" for r, s, w, m in findings]
    lines += ["", f"Result: {counts['FAIL']} FAIL, {counts['WARN']} WARN, {counts['OK']} OK", ""]
    return "\n".join(lines), counts


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--sample", action="store_true", help="review the partner's built-in draft")
    ap.add_argument("--csn", default="review/srv.csn")
    ap.add_argument("--package", default="order-status/package.json")
    ap.add_argument("--out", default="cap_review.md")
    args = ap.parse_args()

    csn, pkg = (SAMPLE_CSN, SAMPLE_PACKAGE) if args.sample else (load(args.csn), load(args.package))
    model = Model(csn)
    findings = check(model, pkg)
    name = pkg.get("name", "app") + (" (sample draft)" if args.sample else "")
    text, counts = report(findings, facts(model, pkg), name)

    print(f"CAP design review: {name}")
    for r, s, w, m in findings:
        print(f"  {r} {s:<4}  {w}: {m}")
    print(f"Result: {counts['FAIL']} FAIL, {counts['WARN']} WARN, {counts['OK']} OK")
    Path(args.out).write_text(text, encoding="utf-8")
    print(f"Report written to {args.out}")
    return 1 if counts["FAIL"] else 0


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 5: Compile the draft and review it

1. Compile the model into the `review` folder (the same on every system, run in `unit21`):

   ```bash
   cds compile order-status/srv --to csn -o review
   ```

   **What success looks like:** one line ending in `review/srv.csn` (on Windows, `review\srv.csn`).

2. Run the review:

   - **Windows (PowerShell):**

     ```powershell
     python cap_review.py
     ```

   - **macOS / Linux:**

     ```bash
     python3 cap_review.py
     ```

   **What success looks like** (the draft is meant to fail):

   ```text
   CAP design review: order-status
     R01 FAIL  DeskService: no @requires and nothing restricted in Inquiries, StatusNotes; any signed-in user can use it
     R01 FAIL  DistributorService: no @requires and nothing restricted in Orders, Inquiries; any signed-in user can use it
     R02 FAIL  DistributorService.Orders: partner service, but no @restrict: every distributor sees every row
     R02 FAIL  DistributorService.Inquiries: partner service, but no @restrict: every distributor sees every row
     R03 FAIL  DistributorService.Orders: projects all of API_SALES_ORDER_SRV.A_SalesOrder; list only the fields this use case needs
     R04 FAIL  DistributorService: served over MCP or A2A but reads an SAP API (Orders); CAP's docs say the adapter is not an endorsed path for SAP application APIs
     R05 OK    calder.orderstatus.Inquiries: managed: who and when are recorded
     R05 WARN  calder.orderstatus.StatusNotes: no createdBy/modifiedAt; add the managed aspect
     R06 FAIL  package.json: production database SQLite; CAP says SQLite is for development, not for production
     R07 FAIL  API_SALES_ORDER_SRV: no destination for production; credentials would end up in the app's own configuration
     R08 OK    package.json: single-tenant, no extensibility
   Result: 8 FAIL, 1 WARN, 2 OK
   Report written to cap_review.md
   ```

   The script gives the same result every time. Read each line as a board's question: who may use the desk service? Can Hallam read Brennock's orders? Why does a distributor receive order values? Why would agents read S/4HANA through this app?

#### Step 6: Fix the design

Each change answers one or more rules. Make them inside `unit21/order-status`.

1. **R05:** in `db/schema.cds`, change the line `entity StatusNotes {` to:

   ```cds
   entity StatusNotes : managed {
   ```

2. **R03 and R04:** replace the whole of `srv/distributor-service.cds` with a consumption view that keeps only what a distributor needs, and without `@mcp`:

```cds
// What a distributor sees: its orders from S/4HANA and its own inquiries.
using { API_SALES_ORDER_SRV as S4 } from './external/API_SALES_ORDER_SRV';
using { calder.orderstatus as my } from '../db/schema';

@path: '/distributor'
@audience: 'partner'        // course annotation: people outside Calder use this service
service DistributorService {

  // A consumption view: only the fields a distributor needs, in our own words.
  @readonly
  entity Orders as projection on S4.A_SalesOrder {
    key SalesOrder              as salesOrder,
        SoldToParty             as customer,
        PurchaseOrderByCustomer as customerReference,
        RequestedDeliveryDate   as requestedDate,
        OverallDeliveryStatus   as deliveryStatus
  };

  entity Inquiries as projection on my.Inquiries {
    ID, customer, salesOrder, question, status, answer, createdAt, createdBy
  };

  event InquiryRaised { inquiry: UUID; salesOrder: String(10); customer: String(10); }
}
```

3. **R01 and R02:** create `srv/access.cds`. All rules sit in one file, added to the services with `annotate`, so a reviewer reads them in one place:

```cds
// Who may do what. Kept apart from the services, so a reviewer reads it in one place.
using { DistributorService } from './distributor-service';
using { DeskService } from './desk-service';

annotate DistributorService with @(requires: 'Distributor');

annotate DistributorService.Orders with @(restrict: [
  { grant: 'READ', to: 'Distributor', where: 'customer = $user.customer' }
]);

annotate DistributorService.Inquiries with @(restrict: [
  { grant: 'READ',   to: 'Distributor', where: 'customer = $user.customer' },
  { grant: 'CREATE', to: 'Distributor' }   // the handler stamps the customer
]);

annotate DeskService with @(requires: 'DeskAgent');
```

4. **R06 and R07:** replace the whole of `package.json`. Production now uses SAP HANA and reaches S/4HANA through the destination `S4_ODATA` from [the connectivity topic](https://erpfde.com/topics/btp-connectivity/). The `[development]` block adds three mocked users for Step 8:

```json
{
  "name": "order-status",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "@sap/cds": "^10"
  },
  "devDependencies": {
    "@cap-js/sqlite": "^3"
  },
  "scripts": {
    "start": "cds-serve"
  },
  "private": true,
  "cds": {
    "requires": {
      "API_SALES_ORDER_SRV": {
        "kind": "odata-v2",
        "model": "srv/external/API_SALES_ORDER_SRV",
        "[production]": {
          "credentials": { "destination": "S4_ODATA", "path": "/sap/opu/odata/sap/API_SALES_ORDER_SRV" }
        }
      },
      "[development]": {
        "auth": {
          "kind": "mocked",
          "users": {
            "hallam":   { "password": "lab", "roles": ["Distributor"], "attr": { "customer": "10000002" } },
            "brennock": { "password": "lab", "roles": ["Distributor"], "attr": { "customer": "10000001" } },
            "desk":     { "password": "lab", "roles": ["DeskAgent"] }
          }
        }
      },
      "[production]": {
        "db": "hana",
        "auth": "xsuaa"
      }
    }
  }
}
```

> **Warning** The passwords `lab` exist only for mocked users on your own computer. In production, users sign in through the identity provider and CAP reads roles and the `customer` attribute from their token. Never put real passwords or keys in `package.json`.

#### Step 7: Review again

1. Compile and review again (in `unit21`):

   ```bash
   cds compile order-status/srv --to csn -o review
   ```

   then `python cap_review.py` (Windows) or `python3 cap_review.py` (macOS/Linux).

   **What success looks like:**

   ```text
   CAP design review: order-status
     R01 OK    DeskService: requires ['DeskAgent']
     R01 OK    DistributorService: requires ['Distributor']
     R02 OK    DistributorService.Orders: rows filtered by the user
     R02 OK    DistributorService.Inquiries: rows filtered by the user (CREATE: Node.js doesn't check where on input; set the field in a handler)
     R03 OK    DistributorService.Orders: consumption view of A_SalesOrder with 5 fields
     R04 OK    (all services): no MCP or agent protocol declared
     R05 OK    calder.orderstatus.Inquiries: managed: who and when are recorded
     R05 OK    calder.orderstatus.StatusNotes: managed: who and when are recorded
     R06 OK    package.json: production database SAP HANA
     R07 OK    API_SALES_ORDER_SRV: production calls go through destination S4_ODATA
     R08 OK    package.json: single-tenant, no extensibility
   Result: 0 FAIL, 0 WARN, 11 OK
   Report written to cap_review.md
   ```

2. Open `cap_review.md` in VS Code. It is the review record: the facts (runtime, services, remote APIs, plugins) and every finding in one table.

The R02 note is the review's hand-off to the code: the model can't prove that new inquiries carry the right customer, so the next step writes and tests the handler.

#### Step 8: Add the handlers and prove the access design

1. Create `order-status/srv/distributor-service.js`:

```javascript
// The code behind DistributorService: read orders from S/4HANA, stamp new inquiries.
import cds from '@sap/cds'

export default class DistributorService extends cds.ApplicationService {
  async init() {
    const { Orders, Inquiries } = this.entities
    const s4 = await cds.connect.to('API_SALES_ORDER_SRV')

    // Orders live in S/4HANA. CAP has already added the row filter from access.cds.
    this.on('READ', Orders, req => s4.run(req.query))

    // Node.js doesn't check a where condition on CREATE input, so the code sets
    // the customer from the signed-in user instead of trusting the request body.
    this.before('CREATE', Inquiries, req => {
      req.data.customer = req.user.attr.customer
      req.data.status = 'OPEN'
    })

    // Tell the rest of the app; the desk service listens for this event.
    this.after('CREATE', Inquiries, async (_, req) => {
      const { ID, salesOrder, customer } = req.data
      await this.emit('InquiryRaised', { inquiry: ID, salesOrder, customer })
    })

    return super.init()
  }
}
```

2. Create `order-status/srv/desk-service.js`:

```javascript
// The code behind DeskService: note each new inquiry, and answer one.
import cds from '@sap/cds'

export default class DeskService extends cds.ApplicationService {
  async init() {
    const { Inquiries } = this.entities
    const distributor = await cds.connect.to('DistributorService')

    distributor.on('InquiryRaised', msg => {
      console.log(`[desk] new inquiry on order ${msg.data.salesOrder} from ${msg.data.customer}`)
    })

    this.on('answer', Inquiries, async req => {
      const [{ ID }] = req.params
      await UPDATE(Inquiries, ID).with({ answer: req.data.text, status: 'ANSWERED' })
      return SELECT.one.from(Inquiries, ID)
    })

    return super.init()
  }
}
```

3. Start the app (the same on every system):

   ```bash
   cd order-status
   cds watch
   ```

   **What success looks like** (shortened):

   ```text
   [cds] - using auth strategy { kind: 'mocked' }
   [cds] - serving DeskService { at: [ '/desk' ], ... }
   [cds] - serving DistributorService { at: [ '/distributor' ], ... }
   [cds] - mocking API_SALES_ORDER_SRV { at: [ '/odata/v4/api-sales-order-srv' ], ... }
   [cds] - server listening on { url: 'http://localhost:4004' }
   ```

   On Node.js 22 you may also see `ExperimentalWarning: SQLite is an experimental feature`; that is normal. Leave this terminal running.

4. Open a second terminal (**Terminal > New Terminal**), turn on `.venv` as in Step 1, and go to `unit21`. Create `try_order_status.py` there:

```python
"""Prove the order-status app's access design against the running server.

Start the app first (cds watch in unit21/order-status), then run:
  python try_order_status.py
Uses the mocked users from package.json (password "lab"). Built-in modules only.
"""
import base64
import json
import sys
import urllib.error
import urllib.request

BASE = "http://localhost:4004"


def call(user, path, body=None):
    req = urllib.request.Request(BASE + path, method="POST" if body else "GET")
    if user:
        token = base64.b64encode(f"{user}:lab".encode()).decode()
        req.add_header("Authorization", "Basic " + token)
    if body:
        req.add_header("Content-Type", "application/json")
        req.data = json.dumps(body).encode()
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status, json.loads(resp.read() or b"{}")
    except urllib.error.HTTPError as err:
        return err.code, {}


def main():
    try:
        call("hallam", "/distributor/Orders")
    except urllib.error.URLError:
        sys.exit("No server on port 4004. Start it with: cds watch (in unit21/order-status)")

    results = []

    def expect(label, ok, seen):
        results.append(ok)
        print(f"  {'OK  ' if ok else 'FAIL'}  {label}: {seen}")

    status, data = call("hallam", "/distributor/Orders")
    orders = sorted(o["salesOrder"] for o in data.get("value", []))
    expect("Hallam sees only its orders", orders == ["1000002", "1000005", "1000014"], orders)

    status, data = call("brennock", "/distributor/Orders")
    orders = sorted(o["salesOrder"] for o in data.get("value", []))
    expect("Brennock sees only its orders", orders == ["1000007", "1000011"], orders)

    status, _ = call("hallam", "/distributor/Orders('1000007')")
    expect("Hallam can't open Brennock's order", status == 404, status)

    status, _ = call(None, "/distributor/Orders")
    expect("No sign-in is refused", status == 401, status)

    status, _ = call("desk", "/distributor/Orders")
    expect("The desk can't use the distributor service", status == 403, status)

    status, data = call("hallam", "/distributor/Inquiries",
                        {"salesOrder": "1000014", "question": "When does HFS-PO-7781 ship?",
                         "customer": "10000001"})
    expect("A new inquiry is stamped with the signed-in customer",
           status == 201 and data.get("customer") == "10000002",
           f"{status}, customer {data.get('customer')}")

    status, data = call("brennock", "/distributor/Inquiries")
    expect("Brennock doesn't see Hallam's inquiry", len(data.get("value", [])) == 0,
           f"{len(data.get('value', []))} rows")

    status, data = call("desk", "/desk/Inquiries")
    expect("The desk sees every inquiry", status == 200 and len(data.get("value", [])) >= 1,
           f"{status}, {len(data.get('value', []))} rows")

    print(f"{sum(results)} of {len(results)} checks passed")
    return 0 if all(results) else 1


if __name__ == "__main__":
    sys.exit(main())
```

5. Run it: `python try_order_status.py` (Windows) or `python3 try_order_status.py` (macOS/Linux).

   **What success looks like:**

   ```text
     OK    Hallam sees only its orders: ['1000002', '1000005', '1000014']
     OK    Brennock sees only its orders: ['1000007', '1000011']
     OK    Hallam can't open Brennock's order: 404
     OK    No sign-in is refused: 401
     OK    The desk can't use the distributor service: 403
     OK    A new inquiry is stamped with the signed-in customer: 201, customer 10000002
     OK    Brennock doesn't see Hallam's inquiry: 0 rows
     OK    The desk sees every inquiry: 200, 1 rows
   8 of 8 checks passed
   ```

   The sixth check sends `"customer": "10000001"` as Hallam, pretending to be Brennock; the handler overwrites it. The first terminal shows `[desk] new inquiry on order 1000014 from 10000002`, the event reaching the other service. `cds watch` keeps data in memory, so each restart starts empty and "The desk sees every inquiry" shows 1 row after one run.

6. Stop the app with **Ctrl+C** in the first terminal.

> **Note** These results come from made-up orders and mocked users on your computer. They show the method, not the behavior of a real S/4HANA system or identity provider.

**No Node.js?** Run `python cap_review.py --sample` (or `python3`). It reviews the partner's draft from a copy built into the script and prints the same eight failures as Step 5.

#### What the code does

| Part | What it does |
| --- | --- |
| `cds compile ... --to csn -o review` | Writes the compiled model to `review/srv.csn`, the file the review reads |
| `Model` in `cap_review.py` | Finds the services, the remote services marked `@cds.external`, and the app's own entities |
| `check()` | Applies rules R01-R08 to the model and to `cds.requires` in `package.json` |
| `@audience: 'partner'` | A course annotation that marks services used outside Calder, so R02 applies |
| `access.cds` | Adds every access rule with `annotate`, separate from the services |
| `on('READ', Orders, ...)` | Passes the distributor's query, with CAP's row filter already added, to S/4HANA |
| `before('CREATE', Inquiries, ...)` | Sets the customer from the signed-in user, because Node.js doesn't check `where` on create input |
| `emit('InquiryRaised', ...)` | Publishes the event the desk service subscribes to |
| `try_order_status.py` | Calls the running app as each mocked user and checks what each may see and do |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` or `python3` not found | Python isn't on your path | Repeat the Python step of [Set up your computer](https://erpfde.com/topics/set-up-your-computer/) |
| `cds` not found | The CAP development kit isn't installed | Repeat Step 3 of [Set up for Unit 5](https://erpfde.com/topics/set-up-for-unit-05/) |
| `Cannot find module '@sap/cds'` | The project's libraries aren't installed | Run `npm install` inside `order-status` |
| `Can't find local module` when compiling | A file path in a `using` line is wrong | Check that `access.cds` imports `./distributor-service` and `./desk-service` |
| `Not found: review/srv.csn` | You haven't compiled, or you are in the wrong folder | Run the compile command in `unit21` |
| The review still shows FAIL after Step 6 | The model wasn't compiled again | Run the compile command again, then the review |
| `No server on port 4004` | The app isn't running, or uses another port | Start `cds watch` in `order-status` and leave it running |
| Hallam sees all five orders | `access.cds` is missing or wasn't loaded | Check the file name and that `cds watch` restarted after you saved |
| `npm install` fails with a network error | A proxy blocks npm | Ask IT for the proxy settings and set them with `npm config set proxy` |

### The SAP way

What SAP provides around CAP, as of 27 November 2026:

- **Tools.** The `cds` command line tool from `@sap/cds-dk`, SAP Business Application Studio ([SAP Build Code](https://erpfde.com/topics/sap-build-code/)) and extensions for VS Code. SAP's [features overview](https://cap.cloud.sap/docs/get-started/feature-matrix) lists the commands for multitenant apps too (`cds subscribe`, `cds upgrade-tenant`, `cds pull` and `cds push` for extensions).
- **BTP services CAP connects to by configuration.** SAP's [BTP Developer's Guide](https://github.com/SAP-docs/btp-developer-guide/blob/main/docs/sap-btp-cloud-foundry-and-sap-btp-kyma-runtimes-with-cap-0f9cfe9.md) names SAP HANA Cloud for persistence, the Authorization and Trust Management service (XSUAA) for identity and authorization, and the destination and connectivity services for SAP and third-party systems. CAP services can appear in SAP Build Work Zone, be consumed by SAP Build Apps and drive SAP Build Process Automation.
- **Plugins.** `@cap-js` plugins for audit logging (with the SAP Audit Log service), data privacy (beta, with SAP Data Privacy Integration), change tracking, attachments, telemetry, SAP Cloud Application Event Hub, advanced event mesh, notifications and more, listed on the [plugins page](https://cap.cloud.sap/docs/plugins/) with the runtimes each supports.
- **AI.** The `@cap-js/mcp` plugin (1.5.0 on npm, 27 November 2026) serves custom CAP services over MCP, under the [API policy caution](https://cap.cloud.sap/docs/guides/ai/cap-mcp) above. The `@cap-js/agents` plugin (0.9.11 on npm) serves CAP services as agents over the A2A protocol, with human-in-the-loop actions; its chat preview is marked alpha. Version numbers below 1.0 are worth noting in a design.
- **Licensing.** CAP has no license fee. The SAP Developer License Agreement shipped in `@sap/cds` (version 3.2 CAP, read 27 November 2026) allows productive use for apps deployed and run on SAP BTP or another platform licensed from SAP, and says support for productive apps follows your SAP licensing agreement. Production costs come from the runtime, SAP HANA Cloud and the bound services; [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/) shows Calder's runtime cost for this app. This is not legal advice; have the terms read for your contract.

### Build vs. SAP

| Need | CAP gives it | Build it yourself |
| --- | --- | --- |
| OData or REST service from a model | Generic providers | Only for unusual protocols |
| Access rules per role and row | `@requires`, `@restrict`, `where` | Checks that depend on remote data, such as "is this order yours?" |
| Who changed what | `managed` aspect, change tracking plugin | Business-specific history |
| Retries for follow-up calls | Event queues (outbox, inbox, tasks) | Compensation when a call fails for good |
| Retry and circuit breaking on synchronous calls | Built in for Java | In Node.js, through your own code or a library |
| Multitenancy and customer extensions | MTX services and `cds add` | Nothing, unless you leave SAP HANA |
| Agent access to your own app | `@cap-js/mcp`, `@cap-js/agents` (pre-1.0) | Agent access to SAP APIs through SAP's endorsed paths, not CAP |

### Architecture view

**Where it sits.** Calder's order-status app (workload W02 in [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/)) runs on Cloud Foundry in the *Ext Prod* subaccount from [the account model](https://erpfde.com/topics/btp-account-model/), and reaches `CP10`'s S/4HANA through the Cloud Connector:

```mermaid
flowchart LR
  D[Distributors<br/>Hallam, others] -->|sign in| IdP[Identity provider]
  IdP --> App[order-status CAP app<br/>Cloud Foundry, Ext Prod]
  Desk[Calder customer service desk] --> App
  App --> H[(SAP HANA Cloud<br/>inquiries, notes)]
  App -->|destination S4_ODATA<br/>Cloud Connector| S4[S/4HANA CP10<br/>API_SALES_ORDER_SRV]
```

**Non-functional requirements that decide the design:**

| Requirement | Typical target | What breaks if it's missed |
| --- | --- | --- |
| Data separation | A distributor sees only its own rows, tested per release | One customer reads another's orders and prices |
| Data volume | Calder's order volume read live, no copies | A nightly copy drifts from S/4HANA and needs its own security |
| Latency | Order list in about 2 seconds, S/4HANA included | Distributors call the desk instead |
| Availability | Two app instances; S/4HANA outages shown as a clear message | A slow S/4HANA ties up every request |
| Change | Model changes reviewed before they touch stored data | A dropped column loses inquiry history |

**Integration and identity.** Distributors and desk staff sign in through the subaccount's identity provider ([the BTP security model](https://erpfde.com/topics/btp-security-model/) has the role collections and groups). CAP reads the role and the `customer` attribute from the token. The app calls S/4HANA's sales order API through the destination `S4_ODATA`, which in [the connectivity design](https://erpfde.com/topics/btp-connectivity/) uses a technical user for this app. That makes CAP's row filter the only control on which distributor sees which order: S/4HANA sees one technical user, not Hallam. The review rules R02 and the handler's customer stamp carry that weight, and the tests prove it.

**The decision to record** (short ADR form from [the design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context:** Calder's team built its earlier CAP extension in Node.js; the app needs one synchronous S/4HANA read and one internal event; no multitenancy planned.
- **Options:** Node.js; Java; Node.js now and Java if resilience needs grow.
- **Decision:** Node.js. The `where` check on create is done in the handler and tested; S/4HANA timeouts are handled with a clear error to the user.
- **Consequences:** no built-in circuit breaker, so a slow S/4HANA shows up as slow pages and must be monitored; a test per release proves data separation; a move to Java later keeps the model and changes only the handlers.

**What a design review will ask:**

1. Show the access file. Which test proves that Hallam can't see Brennock's orders?
2. With a technical user towards S/4HANA, what stops the app from showing every order?
3. What does the app store that S/4HANA already has, and why?
4. What happens to an inquiry and its event when the database commit fails?
5. If agents need order status, which reviewed interface will they use?

### Production concerns

- **Security and authorizations.** Map the CAP roles `Distributor` and `DeskAgent` to role collections and groups, and the `customer` attribute to the user's identity. Never add `$user.customer is null` to a partner rule. Test data separation in every release, as `try_order_status.py` does.
- **Evaluation.** Treat the review script's rules as a gate in the pipeline: compile, review, and stop the build on any FAIL. Add a rule when a review finds a new kind of flaw.
- **Cost.** One small Cloud Foundry app and an SAP HANA Cloud instance, shared with other apps where the account design allows. Splitting into microservices multiplies both.
- **Operations.** Keep `@sap/cds` and plugins current; CAP Java recommends taking the latest minor version every month. Watch the event queue's dead letters. Make queued handlers idempotent.
- **Clean core.** The app reads S/4HANA only through a released API and keeps its own data on BTP, so S/4HANA upgrades don't touch it. [The integration platform and clean core topic](https://erpfde.com/topics/integration-platform-and-clean-core/) explains the rating.

### Where AI fits

AI changes three things for a CAP architecture as of November 2026.

- **Agents as consumers.** `@cap-js/mcp` and `@cap-js/agents` make it easy to put a CAP service in front of agents. The review question is which data they reach. CAP's own documentation rules out using the MCP adapter to expose or proxy SAP application APIs; [SAP API policy and third-party agents](https://erpfde.com/topics/sap-api-policy-and-third-party-agents/) covers the endorsed paths. An agent may read Calder's own inquiries through CAP; order data from S/4HANA goes through SAP's agent paths, such as [the Integration Suite MCP gateway](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/).
- **AI features in the app.** The CAP AI plugin adds field recommendations and an SAP AI Core service; [CAP and side-by-side extensions for AI](https://erpfde.com/topics/cap-and-side-by-side-extensions/) builds an AI action in CAP. For an architect, the model call is one more remote dependency: it needs a destination, a timeout and a fallback.
- **Coding agents.** SAP's `@cap-js/mcp-server` package serves CAP knowledge to coding assistants during development; it is a development tool, not part of the running app. A model written with AI help still needs the review: generated models tend to skip access rules, as the partner's draft did.

### Pitfalls

- **No access rules.** CAP's default is open to every signed-in user. Put rules in the model from the first commit.
- **Trusting the request body on create.** In Node.js, a `where` rule doesn't check create input; set ownership fields in a handler.
- **Projecting the whole SAP API.** Without a consumption view, every new field SAP adds appears in your interface, values included.
- **Dropping managed fields in a projection.** In our test, a projection without `createdBy` left `createdBy` empty on new rows. Keep the fields the audit needs in the projection.
- **Copying S/4HANA data to make reads fast.** The copy needs its own security, refresh and reconciliation. Read live first; measure before you copy.
- **Cutting microservices early.** Each one adds a deployment, a database question and network calls. Split for scale, runtime or lifecycle only.
- **SQLite or an unstated database in production.** Write the production database into the configuration and the decision record.
- **Turning on MCP for a service that wraps an SAP API.** Ask first which data the agent reaches and on which endorsed path.

### Exercise

The model can't see one flaw: Hallam can raise an inquiry on Brennock's order `1000007`, because nothing checks that the order belongs to the distributor. Close the gap in the handler and prove it.

1. Open `unit21/order-status/srv/distributor-service.js`.
2. Replace the `before('CREATE', ...)` block with this one, which reads the order through the same filtered query a distributor would make:

   ```javascript
   this.before('CREATE', Inquiries, async req => {
     req.data.customer = req.user.attr.customer
     req.data.status = 'OPEN'
     // The order must belong to the same customer.
     const order = await s4.run(SELECT.one.from(Orders)
       .where({ salesOrder: req.data.salesOrder, customer: req.data.customer }))
     if (!order) return req.reject(400, `Order ${req.data.salesOrder} isn't one of yours`)
   })
   ```

3. Save. `cds watch` restarts by itself; start it again if you stopped it.
4. In `try_order_status.py`, add a ninth check just before the `print(f"{sum(results)} ...` line:

   ```python
   status, data = call("hallam", "/distributor/Inquiries",
                       {"salesOrder": "1000007", "question": "Is this one late?"})
   expect("Hallam can't raise an inquiry on Brennock's order", status == 400, status)
   ```

5. Run `python try_order_status.py` (or `python3`). Expected: `9 of 9 checks passed`.
6. Add a line to `cap_review.md` under the table: `Handler check: inquiries only on the distributor's own orders (tested, check 9).` The review record feeds the multitenancy topic later in Unit 21, where the same app serves more than one company.

**Done when** `try_order_status.py` reports 9 of 9, the ninth line shows `400`, and `cap_review.md` records the handler check next to the eleven OK findings.

### Going further

For architects who want to judge where CAP's patterns end and their own design must start.

- **Consistency across systems.** CAP's [event queue guide](https://cap.cloud.sap/docs/guides/events/event-queues) explains why two-phase commit across a database and a remote service is impractical in the cloud, and how the outbox gives eventual consistency instead. It also contrasts event queues with pub/sub and with event sourcing. Read it before you design any flow where S/4HANA and the app must agree.
- **The modulith first.** CAP's [features page](https://cap.cloud.sap/docs/get-started/features#late-cut-microservices) argues for late-cut microservices and explains how co-deployed services and mocks let a team delay the cut until it knows where to make it. The trade-off behind any later split is the classic one between deployment independence and data consistency.
- **Unrestricted attributes.** The [authorization guide](https://cap.cloud.sap/docs/guides/security/authorization) works through an example of how an unrestricted user attribute, combined with customer-defined roles, can widen access beyond what anyone intended. It is short and worth reading before you design attribute-based rules for partners.
- **Runtime parity.** The [features overview](https://cap.cloud.sap/docs/get-started/feature-matrix) marks each feature as available, in progress or planned per runtime. Read it as a roadmap, and date any parity claim you put in a design.

### Check yourself

1. Why does the review script read the compiled CSN rather than the handler code?
   - A. Because CAP doesn't allow handlers in production apps
   - B. Because services, projections and rules are all in the model
   - C. Because the CSN also contains the source code of every handler
   - D. Because the CSN is the only file CAP deploys to BTP

   Answer: B. CAP serves services from the model, so structure and access rules are in the CSN. What the model can't say, such as stamping the customer on create, is where the review has to read and test code.

2. In Calder's draft, DistributorService had no rules. What could Hallam do?
   - A. Nothing at all, because CAP denies access when no rules exist
   - B. Only read its own orders, because CAP filters by customer automatically
   - C. Read every distributor's orders and inquiries once signed in
   - D. Only call the service anonymously, without signing in

   Answer: C. CAP's authorization guide says that without rules, authenticated users reach all entities. Row filtering exists only when a where condition on the user is modeled.

3. Why does the handler set req.data.customer from the user on CREATE in Node.js?
   - A. Because Node.js forbids where conditions on any CREATE grant
   - B. Because Node.js doesn't check the where condition against create input
   - C. Because the managed aspect needs the customer field to be filled
   - D. Because S/4HANA rejects inquiries without a customer number

   Answer: B. CAP's guide says Java checks create input against the condition, while Node.js supports only static expressions there. Without the handler, Hallam could create an inquiry claiming to be Brennock, as check six tries.

4. The draft projected all of A_SalesOrder into the distributor service. What is the main risk?
   - A. CAP can't serve a projection of a remote entity at all
   - B. The projection makes S/4HANA copy all of its orders into the app's database
   - C. The projection turns off the row filter for that entity
   - D. Distributors get every field, order values included, now and later

   Answer: D. Without a consumption view, the interface carries every field of the API, and new fields SAP adds appear too. Listing the needed fields keeps the interface small and stable.

5. The app calls S/4HANA through destination S4_ODATA with a technical user. What follows for security?
   - A. CAP's row filter alone decides which orders each distributor sees
   - B. S/4HANA filters the orders by the distributor who signed in to the app
   - C. The destination service checks the customer number of each distributor
   - D. The Cloud Connector removes orders that belong to other customers

   Answer: A. S/4HANA sees one technical user, not Hallam, so it returns any order the query asks for. The filter in access.cds, and tests that prove it, carry the separation.

6. Which choice does CAP's documentation give as a valid reason to split into microservices?
   - A. So that each developer can own and deploy one service
   - B. So that every module is isolated from errors in the others
   - C. So that a part with very different load can scale on its own
   - D. So that each CAP service gets a clean code structure

   Answer: C. CAP lists different scaling, different runtimes and separate lifecycles as valid reasons. Distributed development, modularization and isolation are listed as false reasons with better solutions.

7. An order inquiry must notify an external system only if the database commit succeeds. Which CAP feature fits?
   - A. A synchronous call in the after handler, before the commit
   - B. A scheduled report that compares both systems every night
   - C. An event queue (outbox) that sends the call after commit, with retries
   - D. A second database transaction that is opened inside the external system

   Answer: C. CAP's event queues store the call in the same transaction and send it after commit, retrying on failure. A direct call can reach the other system even when the local transaction rolls back.

8. A partner proposes PostgreSQL and says Calder may later sell the app to other pump makers' distributors. What do you record?
   - A. Nothing, since CAP supports every feature on every production database it lists
   - B. That CAP doesn't support multitenancy or extensibility on PostgreSQL yet
   - C. That PostgreSQL can only be used in Cloud Foundry development spaces
   - D. That PostgreSQL forces the team to write the app in CAP Java

   Answer: B. CAP's PostgreSQL guide says multitenancy and extensibility aren't yet supported there. Selling the app as a service would need both, so the trade-off belongs in the decision record.

9. The partner adds @mcp to the distributor service so agents can read order status. What is the review's verdict?
   - A. Accept it, because the row filter also applies to every agent that calls
   - B. Accept it, because @cap-js/mcp is an SAP-maintained plugin
   - C. Reject it, because MCP can't carry OData data from CAP services
   - D. Reject it, because it proxies an SAP API, which CAP's docs rule out

   Answer: D. The CAP documentation limits the MCP adapter to custom CAP services and says it is not an endorsed path for SAP application APIs. Agents reach S/4HANA order data through SAP's endorsed paths instead.

## Sources

- [Core Concepts of CAP (CAP documentation, read from its source on GitHub, updated 18 November 2026)](https://cap.cloud.sap/docs/get-started/concepts): CDS models compiled to CSN fuel generic runtimes; aspects for separation of concerns, verticalization and customization; services as facades and use-case oriented interfaces; services react to events; CAP services are modules, not microservices
- [Features Overview (CAP documentation)](https://cap.cloud.sap/docs/get-started/feature-matrix): Node.js and Java availability per feature; resilience (retry, circuit breaking) available in Java, not scheduled for Node.js; SQLite and H2 for development only; HANA, HANA Cloud and PostgreSQL for production; tenant-specific extensions; Kyma and Cloud Foundry deployment
- [Late-cut Microservices (CAP documentation, Features)](https://cap.cloud.sap/docs/get-started/features#late-cut-microservices): start as a modulith with CAP services, cut later; valid reasons for microservices are different scaling, different runtimes and coarse-grained subsystems with separate lifecycles; distributed development, modularization and isolation are false reasons
- [Transactional Event Queues (CAP documentation)](https://cap.cloud.sap/docs/guides/events/event-queues): outbox, inbox and scheduled tasks persisted in the same transaction as business data; retries with backoff and a dead letter queue; enabled by default; cds.queued() in Node.js, OutboxService.outboxed() in Java; handlers must be idempotent; no tokens, personal data or secrets in headers of queued outbound calls
- [CAP-level Authorization (CAP documentation)](https://cap.cloud.sap/docs/guides/security/authorization): by default services have no access control and authenticated users reach all entities; @requires and @restrict; where conditions filter READ and reject UPDATE and DELETE; Java also checks CREATE and UPDATE input, Node.js only static expressions on CREATE; empty user attributes mean no access, and "is null" makes them unrestricted
- [Using PostgreSQL (CAP documentation)](https://cap.cloud.sap/docs/guides/databases/postgres): @cap-js/postgres for production on PostgreSQL, hyperscaler option on BTP; multitenancy and extensibility aren't yet supported on PostgreSQL; the SQLite and SAP HANA guides state SQLite is not fit for production and SAP HANA Cloud is the recommended production database with full schema evolution and multitenancy
- [Deploy Multitenant SaaS Applications (CAP documentation)](https://cap.cloud.sap/docs/guides/multitenancy/): @sap/cds-mtxs; cds add multitenancy adds an MTX sidecar; SaaS Provisioning service sends subscribe events, MTX services create the tenant's database container through Service Manager; extensibility (cds add extensibility) needs a multitenant app
- [CAP Plugins & Enhancements (CAP documentation)](https://cap.cloud.sap/docs/plugins/): @cap-js plugins maintained with SAP teams; support order: plugin repository issue, SAP Community, SAP support (community plugins out of scope for incidents); per-plugin Node.js and Java availability; Data Privacy in beta; ABAP RFC Node.js only; AI plugin's Java version in alpha
- [Model Context Protocol Adapter (CAP documentation)](https://cap.cloud.sap/docs/guides/ai/cap-mcp): @cap-js/mcp exposes CAP services with @mcp; intended only for custom CAP application services; not an SAP-endorsed path for exposing or proxying SAP application APIs under section 2.2.2 of the SAP API Policy
- [SAP BTP, Cloud Foundry and SAP BTP, Kyma Runtimes with CAP (SAP BTP Developer's Guide, SAP-docs on GitHub)](https://github.com/SAP-docs/btp-developer-guide/blob/main/docs/sap-btp-cloud-foundry-and-sap-btp-kyma-runtimes-with-cap-0f9cfe9.md): development, hybrid and production profiles; Node.js or Java; integration with SAP HANA Cloud, XSUAA, destination and connectivity services; microservices bring complexity and performance losses; multitenancy keeps each tenant's identity, configuration and data isolated
