Operational Ontology Primitives: Declared Action Types, Multi-Role Link Types, Polymorphic Interfaces & Deterministic Functions
An open, vendor-neutral engineering specification for operational AI ontologies: unifying Data, Logic, Action, and Security across SAP S/4HANA, Logo Tiger, Netsis, and Odoo without ad-hoc SQL mutations or collapsed foreign-key graphs.
- 01Passive metadata catalogs and read-only OLAP semantic views model static tables rather than enterprise decisions; production AI requires a 4-pillar operational ontology integrating Data, Logic, Action, and Security enforced identically across human operators and MCP agents.
- 02Constraining AI agents to declared
ActionTypecontracts (Draft -> Human Evaluation -> ERP Import) replaces arbitrary SQL/REST mutations with typed parameter schemas, deterministic pre-flight validators, cryptographic human approval nonces, and official ERP business-object adapters. - 03Automated schema crawlers routinely collapse multiple foreign keys between the same table pair into one edge—silently dropping ship-to consignees (
TESLIMCARIREF/ SAPVBPAWE) alongside bill-to accounts (CLIENTREF/RE); named, bidirectional, repeatableLinkTypes eliminate multi-reference ambiguity permanently. - 04Polymorphic
Interfacecontracts (Facility,CommercialOrder,Party) decouple agentic workflows from tenant-specific ERP tables while deterministicFunctions enforce the golden rule: the LLM gathers typed inputs, deterministic code computes exact fixed-point math.
1. Why Data-Only Ontologies Fail in Production: The Data + Logic + Action + Security Architecture
Most enterprise AI failures begin with a category error: equating an ontology with a passive data catalog or a read-only SQL semantic view. Knowing which column stores NET_REVENUE allows a dashboard or chatbot to summarize yesterday’s ledger, yet leaves operational workflows completely ungrounded the moment an engineer or AI agent asks: "Can we divert Lot L-408 to fulfill this export order without violating quality holds, credit limits, or sealed fiscal ledgers—and execute the reallocation safely?"
As documented in Palantir’s public Ontology architecture specification (Why create an Ontology?, Retrieved 2026-12-05 23:14 UTC), an operational ontology "represents the decisions in an enterprise, not simply the data," combining semantic elements (ObjectType, Property, LinkType, Interface) with kinetic elements (ActionType, Function, dynamic security) so humans and AI agents operate over a shared operational substrate.
In an open, self-hosted Model Context Protocol (MCP) stack sitting over live ERP, MES, WMS, and QMS databases, Security & Audit cannot be treated as an external API gateway afterthought or a polite system-prompt instruction. Security must stand as Pillar 4 of every operational decision—enforcing read-only replica isolation (BEGIN READ ONLY), transaction-scoped row/column RBAC (SET LOCAL RLS policies and property masks), mandatory security markings propagation across derived rollups, and immutable W3C traceparent decision-lineage records identically whether the caller is a plant controller or an autonomous background agent.
- Pillar 1 —
Data(Operational Truth + Decision Lineage): Integrates live relational records from ERPs, MES, and WMS alongside decision data—capturing which options were evaluated, atop which exact snapshot/version of enterprise state, and what downstream state transition was committed. - Pillar 2 —
Logic(Codified Heuristics, Algorithms & Models): Pairs deterministic business rules, pricing/tax calculators, and evaluated forecasting or optimization models as callable runtime primitives rather than burying formulas inside prompt prose. - Pillar 3 —
Action(Governed Transactional Execution): Encodes every permitted state change as a single atomic transaction (ActionType) with explicit submission criteria, validation gates, official ERP application adapters, and downstream side effects. - Pillar 4 —
Security(Policy Enforcement & Auditability): Enforces caller identity (Human ∩ Agentprivilege intersection), row-level territory/plant scopes, column-level cost/PII masking, and cryptographic human-in-the-loop (HITL) approval proofs before any system-of-record mutation.
| Architectural Dimension | Passive Metadata Catalog | Read-Only OLAP Semantic Layer | 4-Pillar Operational Ontology (Data + Logic + Action + Security) |
|---|---|---|---|
| Primary Abstraction | Table, Column, Lineage metadata artifacts | Measure, Dimension, GROUP BY SQL rollups | Semantic (ObjectType, LinkType, Interface) + Kinetic (ActionType, Function) 1 |
| Decision & State Representation | None; describes schema ownership offline | Historical analytical aggregates only | Models full enterprise decisions (Data, Logic, Action, Security) + decision lineage 2 |
| Computational Logic | Static prose glossary descriptions | SQL aggregation expressions (SUM, COUNT) | Callable deterministic Functions & wrapped ML/optimization models over typed objects |
| System-of-Record Mutation | Metadata tag edits only; zero ERP execution | Strictly read-only query generation | Declared ActionType transactions (Draft -> Human Evaluation -> ERP Import) |
| Security & Audit Model | Catalog UI visibility permissions | Warehouse service-account or view grants | Mandatory markings + row/property RBAC + read-replica isolation + traceparent audit 3 |
2. Declared Action Types: Modeling Draft -> Human Evaluation -> ERP Import as Typed Transactions
The fastest way to corrupt an enterprise ERP is exposing generic CRUD endpoints (execute_sql_mutation, patch_odata_entity, or auto-converted OpenAPI POST routes) as MCP tools. When an LLM improvises multi-table updates directly, it bypasses application-tier Abstract Data Type (ADT) invariants—skipping inventory costing queues, statutory UBL-TR e-Invoice Schematron checks, SAP ENQUEUE lock ordering, and Idempotency-Key deduplication.
In an operational ontology, agents never edit raw columns or tables; they submit or stage declared ActionTypes. Formally, an ActionType defines a single governed transaction over one or more object instances, property values, and links, bundled with explicit submission_criteria, deterministic pre_flight_validators, a stateful approval_gate (DRAFT_STAGED -> PENDING_HUMAN_EVALUATION -> ERP_COMMITTED), an erp_adapter_target, and post-commit side_effects.
Separating staging (Draft) from commit (ERP Import) behind a cryptographic Human Evaluation gate solves the MCP bearer-token authority illusion: even though the agent runs inside an authenticated finance controller’s session, the LLM cannot self-approve its own staged ActionType because the one-time CSPRNG/HMAC approval nonce is rendered exclusively inside an isolated out-of-band / read-only approval surface and omitted from JSON tool responses.
- Typed Object & Parameter Binding (
parameters): Accepts domain object references (SalesOrder,MaterialLot) and constrained business inputs (release_reason,verified_pricing_quote_id) rather than fragile raw foreign-key integers or SQL fragments. - Deterministic
submission_criteria& RBAC Intersection: EvaluatesHuman Role ∩ Agent Capability Ceilingalongside object state invariants (e.g.,order.creditHoldStatus == "BLOCKED"andcaller.plantScopecontainsorder.fulfillmentPlantId) inO(1)time before staging. - Multi-System
pre_flight_validators: Runs read-replica checks across ERP, QMS, and statutory tax state (verifying zero allocated lots sit inQUARANTINE, target fiscal monthe-Defter BeratisOPEN, andIdempotency-Keyhas not already executed). - Official
erp_adapter_targetExecution: Commits approved transactions exclusively through pooled vendor business-object APIs (SAP BAPI_SALESORDER_CHANGE,Logo Objects REST,Nebim V3 Integrator,Odoo XML-RPC/JSON-RPC) and writes an immutable decision-lineage record into the ontology writeback log.
apiVersion: ontology.open-spec/v1
kind: ActionType
metadata:
id: release_credit_blocked_sales_order
version: "2026.12.1"
displayName: "Release Credit-Blocked Sales Order for Dispatch"
domain: order_to_cash
parameters:
sales_order:
type: ObjectReference<SalesOrder>
required: true
verified_exposure_calc:
type: FunctionOutputRef<calculate_account_credit_headroom_v2>
required: true
override_ceiling_try:
type: Decimal(18, 2)
required: true
audit_reason:
type: String
minLength: 15 # Blocks blank or LLM-boilerplate "" audit strings
submission_criteria:
principal_rbac:
anyOfRoles: ["FINANCE_CONTROLLER", "CREDIT_COMMITTEE_LEAD"]
requireAgentScope: "ontology:action:stage"
mandatoryMarkings: ["PII_CLEARED", "FIN_INTERNAL"]
object_predicates:
- "sales_order.status == 'CREDIT_HOLD'"
- "sales_order.fulfillment_facility.plant_code in principal.authorized_plants"
pre_flight_validators:
- id: check_sealed_ledger_period
invariant: "edefter_period_status(sales_order.accounting_date) == 'OPEN'"
onFailure: REJECT_HARD
- id: check_qms_lot_quarantine
invariant: "count(sales_order.allocated_lots[qms_status == 'QUARANTINE']) == 0"
onFailure: REJECT_HARD
- id: check_deterministic_exposure_signature
invariant: "verify_hmac(verified_exposure_calc.signature) && verified_exposure_calc.projected_exposure_try <= override_ceiling_try"
onFailure: REJECT_HARD
approval_gate:
lifecycle: ["DRAFT_STAGED", "PENDING_HUMAN_EVALUATION", "ERP_IMPORTED", "REJECTED"]
requireHumanPresenceProof: true
nonceTransport: "OUT_OF_CONTEXT_UI_AND_SIGNED_WEBHOOK" # Never serialized into LLM JSON!
ttlSeconds: 300
requireDistinctApproverAboveTry: 250000.00
erp_adapter_target:
idempotencyKeyTemplate: "rel_hold:{sales_order.canonical_id}:{verified_exposure_calc.snapshot_txid}"
dispatchBySystem:
sap_s4hana:
protocol: RFC_BAPI_PRINCIPAL_PROPAGATION
operation: BAPI_SALESDOCUMENT_CHANGE
commitWork: BAPI_TRANSACTION_COMMIT
logo_tiger:
protocol: LOGO_OBJECTS_REST_V1
endpoint: "PATCH /api/v1/salesOrders/{sales_order.native_ref}"
payloadMapping: { APPROVE: 1, GENEXP4: "{audit_reason}" }
side_effects:
- type: WRITEBACK_DECISION_LOG
table: ontology_audit.decision_commits
includeW3cTraceparent: true
- type: EMIT_DOMAIN_EVENT
topic: "logistics.dispatch.credit_released.v1"Even if an untrusted supplier PDF or inbound email injects adversarial instructions into an agent’s context window, the agent has zero tool surface to alter bank IBANs (LG_XXX_CLCARD.IBAN / LFBK) or delete ledger rows when the MCP server exposes only declared ActionTypes.
3. Named, Bidirectional & Repeatable Link Types Between the Same Object Pair
A subtle, high-severity modeling bug lurks inside automated SQL-to-Graph crawlers, naive ORM introspectors, and lightweight semantic layers: they index relationships as an unordered or single-edge tuple (SourceTable, TargetTable). Whenever one operational table holds two or more distinct foreign keys pointing to the exact same target table, naive graph builders either overwrite the first join condition with the second or merge them into an ambiguous OR join.
In production ERPs, distinct real-world business roles between the exact same pair of object types are the norm, not an edge case. In Logo Tiger, a single sales order (LG_XXX_YY_ORFICHE) or sales invoice (LG_XXX_YY_INVOICE) simultaneously references CLIENTREF (bill-to account / legal debtor) and RECVREF / TESLIMCARIREF (ship-to consignee account receiving the physical steel coils or pallets), while movement lines (STLINE) carry parallel references to both the originating order (ORDFICHEREF / SIPREF) and the dispatch note (STFICHEREF / IRSREF). In SAP S/4HANA and ECC, partner table VBPA binds up to four separate Customer (KNA1) links onto a single SalesOrder (VBAK): AG (Sold-to), WE (Ship-to), RE (Bill-to), and RG (Payer).
Collapsing (SalesOrder, Account) into one unnamed customer link causes regional delivery agents to ship goods to headquarters billing addresses while finance agents book receivables against third-party logistics consignees! An operational ontology resolves this permanently through named, bidirectional, repeatable LinkType declarations:
- One
LinkType= Two Explicitly Named Traversal Sides: EveryLinkTypeis intrinsically bidirectional—defining both forward and reverse API names on a single edge (e.g.,SalesOrder.billedToAccount↔Account.billedOrders). You never create a redundant second reverseLinkTypejust to traverse back fromAccounttoSalesOrder. - Multiple Distinct
LinkTypes Between Identical Object Pairs: For each separate real-world role between(SalesOrder, Account), declare an independent two-sidedLinkTypewith unique API names (billedToAccount↔billedOrders,shippedToConsignee↔consignedShipments,settledByPayer↔payerObligations). - Self-Referential & Many-to-Many Backing:
LinkTypes also relate anObjectTypeto itself (Employee.directManager↔Employee.directReports, or parent-childProductionLotgenealogy splits) and bind explicit join/allocation tables (NestingAllocation,VBPA) when cardinality isM:N.
export interface BidirectionalLinkTypeDef<SourceObj extends string, TargetObj extends string> {
linkTypeId: string;
description: string;
cardinality: 'MANY_TO_ONE' | 'ONE_TO_MANY' | 'MANY_TO_MANY';
// Single link type exposes two independently traversable sides with unique API names:
sourceSide: { objectType: SourceObj; apiName: string; displayName: string };
targetSide: { objectType: TargetObj; apiName: string; displayName: string };
physicalBindings: Record<string, string>;
}
// LINK TYPE #1 between (SalesOrder, Account): Legal Billing & AR Debtor Relationship
export const OrderBilledToAccountLink: BidirectionalLinkTypeDef<'SalesOrder', 'Account'> = {
linkTypeId: 'sales_order_billed_to_account',
description: 'Legal debtor receiving the e-Invoice and carrying AR credit exposure.',
cardinality: 'MANY_TO_ONE',
sourceSide: {
objectType: 'SalesOrder',
apiName: 'billedToAccount', // order.billedToAccount.get() -> Account
displayName: 'Bill-To Account',
},
targetSide: {
objectType: 'Account',
apiName: 'billedOrders', // account.billedOrders.all() -> ObjectSet<SalesOrder>
displayName: 'Billed Sales Orders',
},
physicalBindings: {
logo_tiger: 'ORFICHE.CLIENTREF = CLCARD.LOGICALREF AND ORFICHE.CANCELLED = 0',
sap_s4hana: "VBPA.VBELN = VBAK.VBELN AND VBPA.POSNR = '000000' AND VBPA.PARVW = 'RE' AND VBPA.KUNNR = KNA1.KUNNR",
},
};
// LINK TYPE #2 between the EXACT SAME (SalesOrder, Account) pair: Physical Consignee / Ship-To
export const OrderShippedToConsigneeLink: BidirectionalLinkTypeDef<'SalesOrder', 'Account'> = {
linkTypeId: 'sales_order_shipped_to_consignee',
description: 'Physical consignee / drop-ship recipient where goods are unloaded.',
cardinality: 'MANY_TO_ONE',
sourceSide: {
objectType: 'SalesOrder',
apiName: 'shippedToConsignee', // order.shippedToConsignee.get() -> Account
displayName: 'Ship-To Consignee',
},
targetSide: {
objectType: 'Account',
apiName: 'consignedOrders', // account.consignedOrders.all() -> ObjectSet<SalesOrder>
displayName: 'Consigned Inbound Orders',
},
physicalBindings: {
logo_tiger: 'COALESCE(NULLIF(ORFICHE.RECVREF, 0), ORFICHE.CLIENTREF) = CLCARD.LOGICALREF',
sap_s4hana: "VBPA.VBELN = VBAK.VBELN AND VBPA.POSNR = '000000' AND VBPA.PARVW = 'WE' AND VBPA.KUNNR = KNA1.KUNNR",
},
};Whenever two ObjectTypes have >= 2 declared LinkType edges between them, the ontology query compiler must reject shorthand JOIN Account requests that omit the explicit link API name (billedToAccount vs. shippedToConsignee), preventing silent role conflation.
4. Polymorphic Interfaces (Facility, CommercialOrder, Party) Across Heterogeneous ERPs
Industrial groups and multi-brand holding companies rarely run a homogeneous database landscape. Corporate headquarters may run SAP S/4HANA, a metal-fabrication subsidiary runs Logo Tiger, a chemical plant runs Netsis, and an European distribution entity runs Odoo. Even inside one ERP, ManufacturingPlant, BondedCustomsWarehouse, and RegionalCrossDock exist as separate concrete object types with specialized attributes.
Without object type polymorphism, every cross-company executive query and every MCP agent workflow fractures into N brittle ERP-specific branches. Ontology Interfaces solve this cleanly: an Interface is an abstract ontology contract defining a shared shape (interface properties, link-type constraints, and action-type constraints) that concrete ObjectTypes implement.
Crucially, ObjectTypes remain concrete (backed by physical SQL/API datasources and instantiated as concrete records carrying all native ERP fields), whereas Interfaces remain abstract (unbacked by any separate duplicated warehouse table). Workflows, RBAC policies, and AI agents interact uniformly with CommercialOrder or Facility—and when a newly acquired subsidiary’s ERP ObjectType implements CommercialOrder, every existing agent workflow becomes compatible immediately with zero prompt or tool refactoring.
- Interface Inheritance & Multi-Interface Composition: Child interfaces can extend parent interfaces (
TaxableDocument->CommercialOrder), and a single concrete object type (LogoWholesaleOrder) can implement multiple interfaces (CommercialOrder,CreditControlled,ExportCustomsTracked) simultaneously for different departmental workflows. - Link & Action Constraints on Interfaces: An interface specifies not just scalar properties (
orderNumber,netAmountEur,promisedDeliveryDate), but requiredLinkTyperoles (Facility,Party) and supported polymorphicActionTypes (place_operational_hold). - Zero-Copy Multi-ERP Federation: Querying over an
Interfacecompiles unioned or per-tenant pushdown SQL acrossSAP,Logo,Netsis, andOdooread replicas at runtime—preserving zero-copy data sovereignty.
// 1. Abstract Interfaces (No backing table; pure shape + link + action contract)
interface Facility {
facilityId: String @primary
facilityName: String
countryIso2: String
timezone: String
activePowerFeeders: Link<EnergyFeeder>[]
}
interface CommercialOrder {
canonicalOrderId: String @primary
documentNumber: String
orderDate: Date
normalizedNetEur: Decimal(18, 2)
fulfillmentState: Enum<OPEN | PARTIAL | HOLD | COMPLETED | CANCELLED>
// Polymorphic Link & Action Constraints:
originFacility: Link<Facility>
billedToParty: Link<Party>
shippedToParty: Link<Party>
requiresAction: ActionType<release_credit_blocked_sales_order>
}
// 2. Concrete Object Types Implementing CommercialOrder Over Heterogeneous ERPs
objectType SapSalesOrder implements CommercialOrder, ExportCustomsTracked {
backingSource: sap_s4_read_replica ("VBAK JOIN VBAP")
map {
canonicalOrderId: concat("SAP:", MANDT, ":", VBELN)
documentNumber: VBELN
orderDate: AUDAT
normalizedNetEur: fx_to_eur(NETWR, WAERK, AUDAT)
fulfillmentState: map_sap_gbsta(GBSTK, CMGST)
}
}
objectType LogoTigerSalesOrder implements CommercialOrder {
backingSource: logo_mssql_replica ("LG_301_01_ORFICHE")
map {
canonicalOrderId: concat("LOGO:301:01:", LOGICALREF)
documentNumber: FICHENO
orderDate: DATE_
normalizedNetEur: fx_to_eur(NETTOTAL - TOTALVAT, TRCURR, DATE_)
fulfillmentState: map_logo_orstatus(STATUS, CANCELLED)
}
}
objectType NetsisSalesOrder implements CommercialOrder {
backingSource: netsis_mssql_replica ("TBLSIPAMAS")
map {
canonicalOrderId: concat("NETSIS:", SUBE_KODU, ":", FATIRS_NO)
documentNumber: FATIRS_NO
orderDate: TARIH
normalizedNetEur: fx_to_eur(GENELTOPLAM - KDV, DOVIZTIPI, TARIH)
fulfillmentState: map_netsis_kapali(KAPALI, ONAYTIPI)
}
}
objectType OdooSalesOrder implements CommercialOrder {
backingSource: odoo_pg_replica ("sale_order")
map {
canonicalOrderId: concat("ODOO:", company_id, ":", id)
documentNumber: name
orderDate: date_order
normalizedNetEur: fx_to_eur(amount_untaxed, currency_id, date_order)
fulfillmentState: map_odoo_state(state, delivery_status)
}
}5. "Model Gathers Inputs, Deterministic Code Does the Math": Pairing Ontology Functions with Action Types
Large language models are exceptional semantic routers: they resolve ambiguous human phrasing ("Quote 45 tons of 3mm pickled hot-rolled sheet for Bursa Otomotiv with their Q4 volume tier and check if Gebze Plant can ship Friday"), disambiguate billedToAccount from shippedToConsignee, and gather structured parameters. Conversely, LLMs are fundamentally unfit for multi-step decimal arithmetic, tax withholding fractions, currency triangulation, or inventory netting.
Operational ontologies enforce a strict division of labor: "The model gathers typed inputs; deterministic ontology Functions do the math; declared ActionTypes commit verified outputs." An ontology Function is versioned, sandboxed code natively bound to Object and ObjectSet types. Rather than letting the LLM calculate VAT withholding (KDV tevkifat), unit-of-measure weight conversions (MT -> KG), or Available-to-Promise (ATP) stock in token space, the agent invokes a deterministic Function that reads live object properties in fixed-point Decimal arithmetic and returns a cryptographically signed calculation envelope.
Because the downstream ActionType schema accepts only a verified FunctionOutputRef signature rather than raw LLM-typed numbers, neither model arithmetic errors nor prompt-injected price overrides can ever reach the ERP adapter.
- Step 1 — Non-Deterministic Semantic Extraction (LLM): Maps user prompt to
Account,MaterialItem, targetFacilityinterface, requested delivery date, and commercial terms. - Step 2 — Deterministic Ontology
Function(Fixed-Point Sandbox): ReadsAccountcontract tier,TCMBofficial FX rate,MaterialItemITMUNITAweight factors, statutory VAT/withholding rules (0.01penny residual allocation), and netATP(physicalStock - quarantineHold - hardReservations), emitting a signedPricingAndAtpEnvelope. - Step 3 — Governed
ActionTypeStaging (Draft -> Human Evaluation -> ERP Import): Verifies theFunctionHMAC digest, stages the exact line totals for human nonce sign-off, and dispatches to the target ERP business-object API.
| Ontology Primitive | Concrete vs. Abstract | Runtime Responsibility in MCP Stack | Primary Reference & Failure Prevented |
|---|---|---|---|
ObjectType & Property | Concrete (dataset / replica backed) | Maps physical ERP/MES rows & status codes into canonical, RBAC-filtered domain instances | Core semantic noun; stops TRCODE / raw column hallucination |
LinkType (Two-Sided) | Concrete (FK or join-table backed) | Declares named, bidirectional, repeatable relationships between object pairs | Two-sided traversal 4; stops CLIENTREF vs TESLIMCARIREF / VBPA collapse |
Interface | Abstract (polymorphic shape contract) | Unifies heterogeneous ERP object types (SAP, Logo, Netsis, Odoo) under one contract | Object polymorphism 5; eliminates N-way per-ERP agent branching |
Function | Deterministic code over objects | Executes exact fixed-point pricing, FX, VAT withholding, and ATP inventory math | Code-based logic; eliminates LLM arithmetic & float drift |
ActionType | Transactional write + side effects | Enforces submission criteria, pre-flight checks, human nonce gate & official ERP API commit | Atomic object transaction 6; stops ad-hoc SQL DML corruption |
import { createHmac } from 'node:crypto';
import Decimal from 'decimal.js'; // Strict base-10 fixed-point arithmetic (zero IEEE-754 float drift)
export interface QuoteAndAtpInput {
accountId: string;
shipToConsigneeId: string;
facilityId: string;
itemId: string;
requestedQtyKg: string; // Passed as exact decimal string from LLM intent extraction
}
export async function computeVerifiedOrderQuoteAndAtp(
input: QuoteAndAtpInput,
ontologyRepo: {
getAccountTierDiscountPct(id: string): Promise<string>;
getBasePricePerKgUsd(itemId: string): Promise<string>;
getOfficialTcmbUsdSellingRate(): Promise<string>;
getStockSnapshotKg(facilityId: string, itemId: string): Promise<{
grossPhysicalKg: string;
qmsQuarantineKg: string;
hardReservedKg: string;
}>;
},
signingSecret: string,
) {
const qtyKg = new Decimal(input.requestedQtyKg);
if (qtyKg.lte(0)) throw new Error('INVALID_QUANTITY: Requested quantity must exceed 0 kg.');
// 1. Deterministic ATP Netting (Gross - Quarantine - Hard Reservations)
const stock = await ontologyRepo.getStockSnapshotKg(input.facilityId, input.itemId);
const netAtpKg = new Decimal(stock.grossPhysicalKg)
.minus(stock.qmsQuarantineKg)
.minus(stock.hardReservedKg);
const isAtpSufficient = netAtpKg.gte(qtyKg);
// 2. Exact Base-10 Tier Pricing + Official TCMB FX + Statutory 20% VAT & 4/10 Withholding
const unitUsd = new Decimal(await ontologyRepo.getBasePricePerKgUsd(input.itemId));
const discountPct = new Decimal(await ontologyRepo.getAccountTierDiscountPct(input.accountId));
const fxRate = new Decimal(await ontologyRepo.getOfficialTcmbUsdSellingRate());
const netUnitTry = unitUsd
.mul(new Decimal(1).minus(discountPct.div(100)))
.mul(fxRate)
.toDecimalPlaces(4, Decimal.ROUND_HALF_UP);
const lineTaxExclusiveTry = netUnitTry.mul(qtyKg).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
const grossVatTry = lineTaxExclusiveTry.mul('0.20').toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
const vatWithholding4_10Try = grossVatTry.mul('0.40').toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
const payableTotalTry = lineTaxExclusiveTry.plus(grossVatTry).minus(vatWithholding4_10Try);
const payload = {
accountId: input.accountId,
shipToConsigneeId: input.shipToConsigneeId,
facilityId: input.facilityId,
itemId: input.itemId,
requestedQtyKg: qtyKg.toFixed(3),
netAtpKg: netAtpKg.toFixed(3),
isAtpSufficient,
netUnitTry: netUnitTry.toFixed(4),
lineTaxExclusiveTry: lineTaxExclusiveTry.toFixed(2),
grossVatTry: grossVatTry.toFixed(2),
vatWithholding4_10Try: vatWithholding4_10Try.toFixed(2),
payableTotalTry: payableTotalTry.toFixed(2),
computedAtUtc: new Date().toISOString(),
};
// 3. Sign deterministic output so stage_sales_order ActionType rejects tampered/LLM-invented numbers
const signature = createHmac('sha256', signingSecret)
.update(JSON.stringify(payload))
.digest('hex');
return { ...payload, signature };
}Frequently Asked Technical Questions
Why can’t we expose validated REST/OData POST endpoints directly as MCP tools instead of defining Ontology Action Types?
Raw REST or OData endpoints validate single-system syntax, not cross-system operational readiness or human presence. A declared ActionType binds caller RBAC (Human ∩ Agent), multi-system pre-flight invariants (such as checking QMS lot quarantine before releasing an ERP order), cryptographic human approval nonces (Draft -> Human Evaluation -> ERP Import), Idempotency-Key deduplication, and traceparent decision-lineage logging into one atomic contract.
Do we need to define two separate Link Types (Order -> Account and Account -> Order) to enable bidirectional graph traversal?
No. A single LinkType is inherently bidirectional and declares two named traversal sides at once (for example, SalesOrder.billedToAccount and Account.billedOrders). You only create a second LinkType between (SalesOrder, Account) when modeling a genuinely distinct business relationship—such as shippedToConsignee (TESLIMCARIREF / SAP VBPA WE) alongside billedToAccount (CLIENTREF / RE).
How does an Ontology Interface differ from building a centralized ETL union table in a cloud data warehouse?
A warehouse union table physically copies data out of plant ERPs—introducing CDC lag, stripping native ERP columns not included in the common schema, and severing transactional write-back context. An Ontology Interface is an abstract, zero-copy polymorphic contract: concrete ObjectTypes (SapSalesOrder, LogoTigerSalesOrder, OdooSalesOrder) retain all native properties and ERP adapters while exposing a unified shape and action contract to agents at runtime.
How do we prevent an LLM from bypassing a deterministic Ontology Function and passing hallucinated totals directly into an Action Type?
Never type financial or inventory action parameters as raw number scalars populated by the model. Instead, have the deterministic Ontology Function persist or HMAC-sign its computed Decimal result struct (FunctionOutputRef), and configure the ActionType pre-flight validator to verify that cryptographic signature and snapshot transaction ID before staging any draft.
Glossary Concepts Referenced in This Guide
FOREIGN KEY constraints—common across mature ERP and manufacturing databases.UPDATE/INSERT statements on ERP/CRM databases, requiring typed action proposals validated against preconditions and approved by a named human role.Free to reference in engineering docs, ADRs, articles, and course syllabi with attribution.
[Operational Ontology Primitives: Declared Action Types, Multi-Role Link Types, Polymorphic Interfaces & Deterministic Functions — Ontoloji.org](https://ontoloji.org/en/guides/operational-ontology-action-types-multi-role-links-and-interfaces)