A single Mule 4 Process API that takes a pipeline nomination ID, pulls the nomination from the Pipeline Nominations API, checks Microsoft Sentinel for related security alerts, and asks an Azure OpenAI chat deployment for a CLEAR/FLAGGED compliance status and a STANDARD_APPROVAL / LEGAL_REVIEW / ESCALATE routing recommendation. Returns one JSON verdict with the AI rationale, alert count and the source nomination, so commercial and legal teams triage only the contracts that need a human. Includes the guardrails a delivery team must add: strict LLM output validation with fail-safe routing, input validation against injection, and secrets handling.
Tags: microsoft-sentinel, energy, pipeline, azure-openai, compliance, midstream, oil-and-gas, approval-routing, ai-agents, munit, process-api, contract-analysis, dataweave
AI Contract Analyst for Pipeline Nominations
Deliverable: One Mule 4 Process API, POST /api/contract-analysis, that turns a pipeline nomination ID into a machine-readable compliance verdict and an approval-routing recommendation, by combining the nomination record, security alerts from Microsoft Sentinel, and an Azure OpenAI analysis, so only contracts that need a human reach Legal.
Objective: In midstream and pipeline operations, every nomination and its service, transport or capacity-reservation contract has to be screened for compliance before it is approved. Today that screening is a manual read by a commercial analyst, and security signals that bear on the counterparty or the nomination sit in a separate tool nobody checks during approval. The result is slow approvals for clean contracts and inconsistent escalation for risky ones. Working looks like this: one call returns CLEAR or FLAGGED, one of three routes, a short rationale, and the evidence behind it.
What's Getting Built
- /api/contract-analysis (Process API, orchestration) — receives a nomination ID and optional contract type, calls three upstream systems in sequence, and returns a single verdict ·
POST /api/contract-analysis
- Pipeline Nominations API connector (System API consumer) — fetches the nomination being screened ·
GET /api/nominations/{nominationId}
- Microsoft Sentinel connector (security data source) — runs a KQL query against a Log Analytics workspace for alerts that mention the nomination ID ·
POST /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.OperationalInsights/workspaces/{workspace}/api/query
- Azure OpenAI connector (AI reasoning) — one chat-completions call that returns the verdict as JSON ·
POST /openai/deployments/{deployment}/chat/completions
Request: nominationId (string, required) and contractType (pipeline-service | transport | capacity-reservation, optional, default pipeline-service). Response fields: nominationId, contractType, analysisTimestamp, complianceStatus, routingRecommendation, aiAnalysis, sentinelAlertCount, nomination.
Prerequisites
- Anypoint Platform sandbox access, Secrets Manager (or secure properties), and API Manager.
- Read access to the Pipeline Nominations API, with a client ID and secret issued for this application.
- An Azure subscription with a Log Analytics workspace attached to Microsoft Sentinel, plus an identity allowed to run queries on it. Query access is usually the approval that takes longest, so ask for it first.
- An Azure OpenAI resource with a chat-completions deployment (a GPT-4o class deployment works). Confirm data-handling and regional terms with the customer's legal team before sending nomination data.
- A decision from the business on what each routing outcome means in their process: who receives
LEGAL_REVIEW, and what ESCALATE triggers. The API only recommends a route; the downstream approval workflow has to exist.
- Mule runtime 4.x (4.6.x is a sound baseline) and the HTTP connector; pin to your supported baseline.
Choose your path
- Nomination-record screening (this plan) — Choose this when the question is "does this nomination, with the security context around it, need a human?" The model sees the structured nomination and the alert list, never the contract document itself.
- Full document analysis — Choose this when the customer wants clause-level review of the executed contract text. Add a document source (an e-signature platform such as DocuSign) and text extraction, and chunk, because long contracts will not fit one prompt. This is a larger build; do not promise it from this plan.
Architecture
1. Contract, listener and request normalization
- Publish the API contract first (RAML or OAS). It defines a single resource,
/contract-analysis, with POST, a 200 response and 400 and 502 error responses. Build against it.
- Expose an HTTP listener on
/api/contract-analysis, POST only.
- Normalize input in a first DataWeave transform: payload
{ nominationId, contractType }, with contractType defaulting to pipeline-service. Keep the original request in a variable, because later steps replace the payload and the error handler still needs the ID.
- Validate before you call anything. Reject a missing or malformed
nominationId and any contractType outside the three enum values with a 400. Skipping this is the usual shortcut, and step 3 explains why it matters.
2. Fetch the nomination
- Call
GET /api/nominations/{nominationId} through an HTTPS request configuration, passing the ID as a URI parameter rather than concatenating a path. Authenticate with the client ID and secret headers read from secure properties.
- Store the response in a
nomination variable: it is both model input and part of the response.
- A
404 from this call is the one upstream failure that is the caller's problem, not an outage. Map it to 404 NOT_FOUND with a message naming the nomination. Everything else becomes a 502 (step 7).
3. Query Sentinel for security alerts
- Run a KQL query for alerts related to the nomination:
SecurityAlert | where AlertName contains '<id>' | limit 10. Send it as a JSON body { "query": ... } with api-version as a query parameter.
- Map the result with a null-safe expression:
payload.tables[0].rows default [], then each row to { alertName: row[0], severity: row[1] }, defaulting severity to "Unknown". A clean nomination returns no rows, and that must produce an empty list, not an error.
- Edge case that breaks a naive build: building the KQL string by concatenating the caller's
nominationId. An ID containing a quote can alter the query. This is why step 1 validates the ID against your nomination-ID pattern (the sample format is NOM-2026-00441) before it reaches Sentinel.
- The row mapping is positional, so project explicit columns in the KQL and change both together; otherwise
alertName and severity silently shift.
- Do not hardcode a static bearer token. Tokens expire, so acquire one at runtime with the Azure client-credentials flow and cache it until shortly before expiry. Also confirm that the Azure Resource Manager host is the right query endpoint for your workspace.
4. Ask the model for a structured verdict
- Make one chat-completions call with
temperature: 0.2 and max_tokens: 500. Low temperature makes repeated runs on the same inputs agree far more often. It is still not deterministic, so step 5 and the checks below enforce the contract in code.
- System prompt shape: the model is a pipeline contract compliance analyst and must return JSON with exactly three fields:
complianceStatus (CLEAR or FLAGGED), routingRecommendation (STANDARD_APPROVAL, LEGAL_REVIEW or ESCALATE), and analysis (a brief explanation).
- User message shape: the nomination serialized as JSON, a newline, then the Sentinel alert list serialized as JSON. Pass structured data, not prose, and keep the prompt to the fields the verdict needs. Nominations carry commercial terms, and every extra field is data leaving your boundary.
- Where supported, enable JSON-mode response formatting. It reduces malformed output but does not replace validation.
5. Validate the model output and fail safe
- The model's reply arrives as a string in
choices[0].message.content. Parse it into an object, then validate three things: it is valid JSON, complianceStatus is in {CLEAR, FLAGGED}, and routingRecommendation is in {STANDARD_APPROVAL, LEGAL_REVIEW, ESCALATE}.
- Edge case that breaks a naive build: models wrap JSON in a markdown code fence, add a preamble, or truncate at the token limit. The tempting shortcut is a parse with a default of
CLEAR / STANDARD_APPROVAL, which reports an unparseable answer as a clean contract. An unparseable model reply must fail closed (route to manual review), never default to CLEAR / STANDARD_APPROVAL. For a compliance control this is non-negotiable.
- Build the opposite behavior. Strip a surrounding code fence, attempt the parse once, and if it still fails or an enum value is out of range, return
FLAGGED with ESCALATE (or LEGAL_REVIEW, per your business owner) and put the raw model text in aiAnalysis. Add a finish_reason check so a response cut off by max_tokens is treated as invalid, not as complete.
- Add a model-independent rule: if
sentinelAlertCount is greater than zero, the verdict can never be CLEAR / STANDARD_APPROVAL. Agree the threshold with the compliance owner.
6. Assemble the response
- Build the final payload in one transform:
nominationId and contractType from the saved request, analysisTimestamp from now(), complianceStatus, routingRecommendation and aiAnalysis from the validated result, sentinelAlertCount as the size of the alert list, and the full nomination object.
- Returning the nomination and alert count with the verdict is deliberate: a reviewer who disagrees can see what the AI saw.
7. Error handling
- Add two propagate handlers:
HTTP:NOT_FOUND returns { error: "NOT_FOUND", message } with status 404, and a catch-all returns { error: "UPSTREAM_ERROR", message } with status 502.
- Map the status explicitly: storing it in a variable is not enough unless the listener's error response reads it, or the client sees a different status than the body claims. Wire it into the listener's error response and test it (see Deterministic checks).
- Do not echo
error.description to callers; upstream text can leak hostnames. Log it internally, return a generic message.
- Set explicit timeouts on every outbound request; worst-case latency is the sum of all three calls.
8. Security and compliance
- Standards: treat this as supporting evidence for the customer's internal controls and applicable regulations (for example FERC tariff rules, NERC CIP if alerts cover operational assets, SOX for approval trails). Confirm which apply with the compliance owner. The AI output is a recommendation; a person or a rules-based approval workflow remains the decision-maker.
- Secrets: every credential (nominations client ID and secret, Azure bearer token, subscription ID, OpenAI host and key) must come from secure properties (
${secure::...}), never from the plain properties file. That file should hold only non-secret values such as the port, workspace name and deployment name.
- Enforce client ID and a rate limit on the inbound API in API Manager, and do not expose the listener directly; it has no authentication of its own.
- All three upstreams are HTTPS. Confirm Azure OpenAI prompts are not retained or used for training, per your agreement.
- Logging: nomination ID, verdict, routing, alert count, deployment and correlation ID. Never log the prompt, nomination body or raw model reply at INFO. Keep an immutable record of each verdict for audit.
Sample payload — request and response
Request, POST /api/contract-analysis:
{
"nominationId": "NOM-2026-00441",
"contractType": "pipeline-service"
}
Response, 200:
{
"nominationId": "NOM-2026-00441",
"contractType": "pipeline-service",
"analysisTimestamp": "2026-04-23T22:00:00Z",
"complianceStatus": "CLEAR",
"routingRecommendation": "STANDARD_APPROVAL",
"aiAnalysis": "No compliance flags found. Contract aligns with standard pipeline service terms.",
"sentinelAlertCount": 0,
"nomination": {}
}
The nomination object is whatever the Nominations API returns for that ID; its shape is not constrained by the contract.
Deterministic checks
POST /api/contract-analysis with a valid ID returns 200 and a body whose complianceStatus is exactly CLEAR or FLAGGED and whose routingRecommendation is exactly one of STANDARD_APPROVAL, LEGAL_REVIEW, ESCALATE. Anything else is a defect, whatever the model said.
- A missing or malformed
nominationId, or a contractType outside the enum, returns 400 with { error, message } and makes zero upstream calls.
- Nominations API
404 produces HTTP 404 with error: "NOT_FOUND"; any other upstream failure (Nominations, Sentinel or Azure OpenAI) produces HTTP 502 with error: "UPSTREAM_ERROR". Assert the actual status code on the wire, not only the body.
- Fail closed: a model reply that is not valid JSON, is truncated, or has an out-of-enum value never yields
CLEAR / STANDARD_APPROVAL; it yields FLAGGED with a manual-review route (step 5). A code-fenced but otherwise valid reply is unwrapped and accepted.
- If
sentinelAlertCount > 0, the response is never CLEAR with STANDARD_APPROVAL.
- Empty Sentinel rows produce
sentinelAlertCount: 0, not an error.
- A
nominationId containing a single quote or KQL operators is rejected before any Sentinel call.
- No secret appears in the properties file; every credential is a
${secure::...} reference.
- MUnit: write the suite described under Testing, mocking only the three HTTP requests at the connector boundary, and run it with
mvn test. Agree a coverage gate with your platform team.
Testing and validation
- Happy path in a sandbox: a real nomination with no related alerts returns
200, CLEAR, sentinelAlertCount: 0, and a populated nomination.
- Flagged path: a nomination with a real related alert in a non-production workspace returns a matching count and a non-
CLEAR verdict.
- Malformed-model-output path: in MUnit, feed the Azure OpenAI step a fenced reply, a prose-wrapped reply, a truncated reply, and an out-of-enum value. Assert the fail-safe verdict in each.
- Oversized input: send a nomination with a very large body. The prompt embeds the whole nomination, so check token use against context and quota limits, and decide whether to trim fields or reject.
- Mapping correctness: compare
nomination against a direct Nominations API call, and sentinelAlertCount against the same KQL run in the Sentinel portal.
- Run already-decided nominations through the API to get the rollout agreement figure; never quote one you did not measure.
Phased rollout
Phase 1 — Connect
- Stand up the app in a sandbox and prove each credential against a real environment: one nomination fetched, one Sentinel query, one chat completion.
- Publish the API contract, put the API behind API Manager, and apply client ID enforcement and a rate limit.
Phase 2 — Map and validate
- Implement input validation, output validation and the Sentinel-alert rule. Write the MUnit suite.
- Run in shadow mode on historical nominations: humans decide as usual, the API's verdict is recorded beside theirs, and disagreements are reviewed with compliance and legal. Tune the prompt and rules from those cases.
Phase 3 — Production
- Connect routing to the real approval workflow, starting with
LEGAL_REVIEW and ESCALATE as advisory flags. Keep humans approving until agreement and miss rates hold.
- Confirm runtime token acquisition, alert on 502 rate and latency, and hand dashboards and a runbook to the platform team.
Success metrics
- Business: share of nominations auto-routed to
STANDARD_APPROVAL, and submission-to-approval time for that group. Baseline both before go-live.
- Quality: agreement between the API's routing and the final human decision on the shadow sample, and the count of
STANDARD_APPROVAL recommendations a reviewer later flagged. The second matters more.
- Platform: p95 end-to-end latency (sum of three upstream calls), 4xx and 5xx rates, count of fail-safe verdicts caused by unparseable model output, and Azure OpenAI token consumption per call.
Troubleshooting
- Every response is
CLEAR / STANDARD_APPROVAL even for risky nominations — Likely cause: parse failures defaulting to clean values, or max_tokens truncating the JSON. Fix: implement the step 5 fail-closed path, log finish_reason, and raise max_tokens if needed.
502 UPSTREAM_ERROR from Sentinel on a previously working deployment — Likely cause: expired bearer token, or the identity lost query rights. Fix: acquire tokens at runtime and check the workspace role.
- Client sees an unexpected status code on errors — Likely cause: the status was saved to a variable but not applied to the listener's error response. Fix: wire it in and assert the code in MUnit.
- Sentinel errors for some nomination IDs — Likely cause: characters that break the concatenated KQL. Fix: validate the ID format up front.
sentinelAlertCount is wrong or severities show Unknown — Likely cause: the positional row mapping no longer matches the query's columns. Fix: project explicit columns in the KQL and update the mapping together.
404 for a nomination you know exists — Likely cause: wrong Nominations API host for the environment, or the client lacks access. Fix: call the Nominations API directly with the same credentials.