Skip to content
attilaberencsiPublic

About

WheelShop to demo the official CAP MCP Protocol Adapter + LangGraph

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Wheel Shop

A SAP Cloud Application Programming Model (CAP) Node.js/TypeScript project implementing the backend of a fictitious wheel & tire shop. It exposes a full product catalog (wheels/tires), procurement (manufacturers, purchase orders), sales (sales orders) and inventory (stock) data model as an OData v4 service and as an MCP (Model Context Protocol) server, so both classic consumers (e.g. SAP Fiori/UI5) and AI agents/LLMs can consume the same data.

Table of contents

Aim of this repository is to:

  • demonstrate how a CAP service can be exposed via MCP Protocol Adapter and consumed (by your favorite chat agent for example)
  • how LangGraph and a CAP Service can be combined (srv\stock-forecast) for agentic workflows accessing an LLM

Tech stack

Project structure

.env                    # demo local OpenAI-compatible LLM configuration
db/
  shop-schema.cds       # domain model (namespace `wheelshop`)
  data/                 # sample CSV data (incl. sap.common Countries/Currencies)
srv/
  wheel-service.cds     # WheelService: OData, MCP, entities, and actions
  wheel-service.ts      # CAP action handlers
  wheel-service-ui.cds  # Fiori Elements annotations for StockOverview
  stock-forecast/       # LangGraph stockout and procurement workflow
    baseline.ts          # deterministic demand and stockout calculation
    data-access.ts       # internal CAP service data reads
    formatted-text.ts    # sap.m.FormattedText-safe response rendering
    graph.ts             # LangGraph node and edge definition
    llm.ts               # OpenAI-compatible LLM integration and fallbacks
    procurement-actions.ts # replenishment and supplier-draft orchestration
    replenishment-plan.ts  # deterministic 90-day order quantities
    types.ts             # graph state and workflow contracts
@cds-models/            # generated TypeScript types (cds-typer)
test/
  out-of-stock-analysis.http # REST Client requests for all actions

Data model (ER diagram)

The domain model lives in db/shop-schema.cds, namespace wheelshop. Wheels and Tires share common fields (name, sku, description, weight, manufacturer, stock) via the Products aspect. Polymorphic "wheel-or-tire" references (PriceLists, PurchaseOrderItems, SalesOrderItems) use two nullable associations (wheel / tire), of which exactly one is populated per row.

erDiagram
  MANUFACTURERS ||--o{ WHEELS : supplies
  MANUFACTURERS ||--o{ TIRES : supplies
  MANUFACTURERS ||--o{ PURCHASEORDERS : "receives"

  CARRIERS |o--o{ SALESORDERS : delivers

  WHEELS ||--|| STOCKS : has
  TIRES ||--|| STOCKS : has

  WHEELS ||--o{ PRICELISTS : "priced (wheel)"
  TIRES ||--o{ PRICELISTS : "priced (tire)"

  PURCHASEORDERS ||--o{ PURCHASEORDERITEMS : contains
  PURCHASEORDERITEMS }o--o| WHEELS : references
  PURCHASEORDERITEMS }o--o| TIRES : references

  SALESORDERS ||--o{ SALESORDERITEMS : contains
  SALESORDERITEMS }o--o| WHEELS : references
  SALESORDERITEMS }o--o| TIRES : references

  MANUFACTURERS {
    string name
    string contactPerson
    string country
    integer deliveryTimeInDays
  }

  CARRIERS {
    string name
    integer deliveryTimeInDays
  }

  WHEELS {
    string name
    string sku
    decimal diameterInch
    decimal widthInch
    string boltPattern
    integer offsetMm
    string material
    boolean discontinued
  }

  TIRES {
    string name
    string sku
    integer widthMm
    integer aspectRatio
    decimal rimDiameterInch
    string season
    boolean discontinued
  }

  STOCKS {
    integer quantity
    integer reorderLevel
  }

  PRICELISTS {
    string priceType
    decimal price
    string currency
    date validFrom
    date validTo
  }

  PURCHASEORDERS {
    string orderNo
    date orderDate
    date expectedDeliveryDate
    string status
  }

  PURCHASEORDERITEMS {
    integer quantity
    decimal unitPrice
    string currency
  }

  SALESORDERS {
    string orderNo
    string customerName
    date orderDate
    date requestedDeliveryDate
    string status
  }

  SALESORDERITEMS {
    integer quantity
    decimal unitPrice
    string currency
  }
Loading

Entity overview

Entity Purpose
Manufacturers Procurement master data; supplies wheels & tires; lead time (deliveryTimeInDays)
Carriers Logistics carriers used to deliver sales orders to customers
Wheels / Tires Product catalog (extendsProducts aspect: cuid, managed, name, sku, manufacturer, stock)
Stocks Own-storage quantity per wheel/tire (1:1 composition)
PriceLists Time-dependent Retail/Wholesale price per wheel or tire (temporal aspect)
PurchaseOrders / PurchaseOrderItems Orders placed with manufacturers to replenish stock
SalesOrders / SalesOrderItems Customer orders fulfilled from stock and shipped via a carrier

Getting started

Install node libraries and run the service which is available at http://localhost:4004/

npm install
npm run watch       # cds watch (auto-detects TypeScript)
# or
npm run watch:tsx   # cds-tsx watch

Scenario 1 - MCP Server

The interesting part is the MCP Protocol Adapter (aka. Server) running at this path:

http://localhost:4004/mcp/wheel

Use it as MCP Server in your favorite chat Agent and ask questions ( or consume it another app)

To turn the CAP service listening to MCP requests, we simply activate that protocol - like always - with the corresponding annotation. Since we added @mcp, therefore @odata is also required if you want to have it exposed as odata V4 as well. To describe the purpose of your MCP Server use the @mcp.instructions annotation

// Serve via OData v4 (full CRUD, non-draft) and MCP for agent/LLM consumption.
annotate WheelService with @odata @mcp;

// Guidance shown to MCP clients/agents when they connect to this server.
annotate WheelService with @mcp.instructions: 'This MCP server exposes the Wheel Shop CAP service. Use the `describe` tool first to discover the available entities (Manufacturers, Carriers, Wheels, Tires, StockOverview, PriceLists, Stocks, PurchaseOrders, PurchaseOrderItems, SalesOrders, SalesOrderItems) and their fields. Use the `query` tool to answer: (1) procurement questions, e.g. manufacturer lead times, open purchase orders, low or zero stock articles; (2) sales questions, e.g. current retail/wholesale prices, sales order status, discontinued articles that are still sellable because stock quantity is greater than zero; (3) technical/catalog questions, e.g. wheel bolt patterns and diameters, or tire sizes and load/speed ratings. Call `outOfStockAnalysisNextMonths` with `monthCount` from 1 to 60 to forecast products at risk. Call `proposeReplenishmentPlan` with the same period to get deterministic 90-day supplier order quantities. Call `draftSupplierPurchaseRequests` to get LLM-assisted, approval-ready supplier requests; it does not send messages or create orders. Prices in PriceLists are time-dependent: filter by validFrom/validTo (or compare against the current date) to find the price that is currently valid, since multiple historical price entries may exist per wheel or tire.';

As developer you definitely want to examine your MCP server, therefore simply launch the MCP Inspector, for that we have a script prdedfined in package,json. It will launch your playground. For more check out MCP Inspector.

    "inspect": "mcp-inspector --transport http http://localhost:4004/mcp/wheel",

To enumerate your unbound actions as separate tools, you need to configure it explicitly in package.json.

  "cds": {
    "mcp": {
      "per_action_tool": true
    }
  }

Database

The dev database is in-memory SQLite and is re-bootstrapped from db/data/*.csv on every cds watch/cds-serve run (see cds.requires.db in package.json).

WheelService

Defined in srv/wheel-service.cds: plain CRUD projections over every entity in the data model, served as:

  • OData v4 (non-draft, full CRUD) — suitable for SAP Fiori/UI5 apps
  • MCP at /mcp/wheel — so AI agents/LLMs can discover (describe) and query (query) the same data without extra implementation effort

Scenario 2 - LangGraph Procurement Workflow

WheelService provides three unbound CAP action wrapping LangGraph workflows and LLM calls. Each accepts monthCount as an integer from 1 to 60 and is also exposed as a dedicated MCP tool when cds.mcp.per_action_tool is enabled. All action responses contain only sap.m.FormattedText-compatible tags: p, ul, li, strong, and br.

Hint:

  • use 6 months as forecast/simulation period
  • these LLM backed actions are also available via the MCP Protocol, try it out in your chat client

1785006740952

Local LLM Configuration

The tracked demo .env file is loaded automatically by npm start, npm run watch, and npm run watch:tsx on Windows, macOS, and Linux. Its values override the fallback defaults in srv/stock-forecast/llm.ts. LLM_TIMEOUT_MS is measured in milliseconds; the demo value is five minutes. LLM_SUPPLIER_DRAFT_TIMEOUT_MS controls the shorter timeout used only for supplier purchase-request wording, which falls back to deterministic text by default after 20 seconds. Adjust the .env values for a different local OpenAI-compatible server or model.

Action: Out-of-stock Forecast

Purpose: identify wheels and tires projected to run out of stock during the requested period.

Input: outOfStockAnalysisNextMonths(monthCount).

Workflow: loadCapData reads product, stock, supplier, sales, and purchase data through CAP; calculateBaseline derives average daily demand and stockout dates; forecastWithLlm optionally improves the explanation; and renderFormattedText returns the formatted result.

Output: product name, projected stockout date, supplier, delivery time, latest order date, and procurement proposal.

LLM role and fallback: the LLM may refine dates and proposal text. When the model is unavailable or returns invalid JSON, the deterministic forecast remains the response.

Action: Replenishment Plan

Purpose: create buyer-ready replenishment quantities for products projected to run out of stock.

Input: proposeReplenishmentPlan(monthCount).

Workflow: reuses the shared stockout forecast, groups products by supplier, and calculates a target stock level of 90 days of demand plus the product reorder level.

Output: supplier, product, target stock, proposed order quantity, and latest date to place the order.

LLM role and fallback: no LLM is used. Quantities and deadlines remain deterministic and auditable.

Action: Supplier Purchase-request Drafts

Purpose: create supplier-specific, buyer-reviewable purchase-request drafts from the deterministic replenishment plan.

Input: draftSupplierPurchaseRequests(monthCount).

Workflow: builds the deterministic supplier plan, sends fixed quantities and deadlines to the LLM for wording, then renders one request draft per supplier.

Output: supplier recipient, email address, request subject, and draft body.

LLM role and fallback: the LLM improves communication only; it cannot alter quantities or dates. If it is unavailable or returns invalid JSON, a deterministic draft is returned. This action never sends an email or creates a purchase order.

Scenario 3 - Budget Fiori UI to Invoke an MCP Action of the CAP Service

What can I say, SAP Fiori has no Agentic / Chat control 😄. Sooooo I placed buttons and I did what you should not do 🪓 ; I returned HTML from my CAP Action exposed via MCP, then displayed it via sap.m.FormattedText control...

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

WheelShop to demo the official CAP MCP Protocol Adapter + LangGraph

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages