Case study · client delivery for a pest-control multinational · Apr – May 2026 · in pilot

Flick: supplier invoices reconciled by agents, decided by people

Finance analysts were proving every line of every supplier invoice by hand, against contracts, purchase orders and meter data. Flick lets them ask in Teams instead. Specialist agents gather the evidence, a second AI model challenges the result, and anything that moves money in a way that is hard to undo waits for a named person.

My role

Principal AI Engineer, forward-deployed. Architecture, agents, MCP servers, evaluation harness and production hardening, inside the client's Azure tenant.

Stack

Python 3.12 · LangGraph · Claude Opus (primary) · Azure OpenAI (fallback) · MCP · Copilot Studio · Azure Container Apps · AI Search · Azure SQL · Bicep · OpenTelemetry

Who approves what

Built for the sponsor, the architect and finance operations, with three tiers of approval. Nothing posts automatically above NZD 25,000 a line; disputes need an analyst, reversals need a manager.

Watch first · about a minute

One supplier invoice, from the Teams chat to a decision.

Plain-English captions, no sound needed. Switch to For tech for the architecture, guardrails and evaluation detail.

▶ Explainer · about a minute · captions on screenGIF
Business view shows the story and results; tech view adds every engineering section.
The analyst's problem

Every invoice line is a claim someone has to prove.

A consumption invoice says: you used this much, at this rate, under this clause, in this billing window. To close one line, an analyst checks the reading against a meter, the rate against the latest contract amendment, the dates against the billing calendar and the total against a purchase order.

By hand, one invoice takes 30 to 90 minutes. The mistakes are quiet and expensive: paying money the business does not owe, or damaging a supplier relationship with a dispute that turns out to be wrong. And every analyst re-learns the same patterns, because the knowledge sits in inboxes rather than in a system.

  • What goes wrongTariff amendments not carried into billing · meter reads missing from the market feed · misapplied network charges · the same charge billed in two cycles.
  • What the business neededEvery decision recorded with the evidence behind it, the variance tolerated and the outcome, so patterns and supplier trends roll up instead of disappearing.
  • What could not changePeople keep the decisions that are hard to undo: disputes, reversals and anything above the approval threshold.
How it works

One invoice, from the Teams chat to the ledger.

In plain English: a manager agent hands the invoice to specialists with one job each. They read the evidence through tightly scoped connections to the systems of record, a second model argues with the result, and the invoice takes one of three routes.

Follow one invoice from the Teams chat to the ledger
0 / 11
front doororchestrationspecialist agentsmcp tool layerthree routesTeams chatCopilot Studio · TeamsIngestion queueemail · API · folderManager agentplan → dispatch → aggregateParserreads every lineMatcherfinds the evidenceAnomalyflags variancesReconcilervariance + tierReportercited summaryCriticsecond LLM vendorcontracts-mcppurchase-mcpmeter-mcpledger-mcpdispute-mcpGreen · auto-postbelow threshold · idempotentAmber · analyst queueevidence attachedRed · dispute draftheld for human release
—

The three routes

The harder a step is to undo, the more a person decides.

Review is placed by blast radius, not by habit. Routine approvals take seconds because reviewers see a variance table and citations, not a transcript.

RouteWhenWhat happensWho decides
GreenThe evidence lines up and the amount is below the approval thresholdPosts to the ledger automatically. The write carries a key from the run, so a retry or a double click cannot post twiceThe system, inside limits finance set; it is low-value and reversible
AmberSomething needs judgement: a variance, an ambiguous match, an unfamiliar invoice formatWaits in the analyst queue with the variance table and citations attachedAn analyst
RedThe supplier appears to have billed wronglyA dispute is drafted and held; nothing is sentA named person releases it. Reversing a ledger posting needs a manager
The controls

What keeps it honest with money on the line.

Each control is named after the failure it prevents, and each was walked before the pilot took live traffic.

No source, no claimThe citation contract

No agent may state anything it cannot support with a source retrieved in this run, and no agent may edit another agent's citations.

A second opinionA critic on another vendor

The Critic runs on a different LLM vendor and starts from disagreement: unsupported claims, weak citations, a tier that is too generous.

Least privilegeEach agent sees only what its job needs

The Parser reaches no system at all; the Matcher sees contracts and purchase orders; each MCP server has its own narrow service account.

No double postingWrites that cannot repeat

Every write carries an idempotency key from the run, and is versioned and reversible. A re-run or a double click is a no-op.

Untrusted text stays dataInvoices cannot give orders

Content Safety screens every prompt and response, personal data is redacted on the way in, and invoice text is tagged as data, never as instruction.

Changes earn productionTested before anyone sees them

Every prompt, model or agent change is replayed overnight against past invoices the analysts labelled, then tried on a small slice of live traffic with automatic rollback.

Under the hood · architecture

Six layers, one typed contract between each.

For the engineers in the room. Each layer is replaceable in isolation: the Copilot front door can become a REST client, agents can move to a different LLM, MCP servers can be re-implemented against another system of record.

Front door
Copilot Studio bot · Teams · web · RESTIngestion queue · email · API · watched folderAnalyst approval queue · cards · SLA timers
↓
Orchestration
Manager Agent · state machine · plan → dispatch → aggregate → emit · durable checkpoint
↓
Domain agents
ParserMatcherAnomalyReconcilerReporterCritic
↓
MCP tool layer
contracts-mcppurchase-mcpmeter-mcpledger-mcpdispute-mcp
↓
Data · knowledge
Azure SQLAI Search (vector + hybrid)Blob (immutable)Metrics DB
↓
Foundation
Claude Opus (primary) · Azure OpenAI (fallback) · Entra ID · Key Vault · Content Safety · App Insights · Purview
Under the hood · MCP integration

Systems of record behind a stable, typed boundary.

Each enterprise system is fronted by one MCP server with a small typed surface, four to eight tools, mapped to that system's bounded context. The model sees a stable schema; the server owns the source system's quirks.

Scoped, not sprawling

Each agent sees only the servers its job needs: Parser sees none, Matcher sees contracts and purchase, Reconciler sees meter and ledger. Tool surfaces are audited for capability bloat before every release, because every unused tool is routing noise, attack surface and tokens.

Idempotent and versioned

Every write carries an idempotency key derived from the reconciliation run identifier, so a re-drive or a double click is a no-op, never a duplicate. A new tool version is a schema change the model can see; old versions keep serving until every caller has moved.

Identity at every endpoint

Agents reach servers via Managed Identity; each server holds its own least-privilege service account for the system behind it. Every call carries a correlation ID into Application Insights, so a failure three hops downstream is traced back to its cause.

Under the hood · the agents

One job each, one clean handoff between.

The contract: no agent may emit a claim it cannot support with a cited chunk retrieved this run. No agent may edit another agent's citations. Every mutating action is idempotent, versioned and reversible.

Managerthe supervisortrigger + invoice → ReconciliationRun

Plans the agent chain, dispatches each stage, tracks state through a durable checkpoint, owns token budgets per run, per agent, per model.

Parserreads every invoicePDF · CSV · EDI → normalised line items

Preserves page and paragraph anchors for every field; handles supplier quirks; returns per-field confidence. F1 0.94 across 40+ formats.

Matchercorrelates lines to evidenceline + retrieval hits → ranked candidates

Emits a ranked list, not a hard pick, so downstream tiers can factor in ambiguity. Precision@1 0.91, recall@3 0.98.

Anomaly Detectorflags variancesmatched line + evidence → typed variances

Rules engine plus statistical classifier for tail cases. False-positive rate 3.1% at 95% recall.

Reconcilercomputes tier and confidencematched line + anomalies → tier · action

Composes match strength, severity and historical calibration into green / amber / red. Brier 0.06, ECE 0.02.

Reportercomposes the narrativereconciled set → narrative · card · citations

Every factual claim carries a citation. Teams Adaptive Cards natively; Markdown elsewhere.

Criticadversarial gatecandidate → approve · route to review

Runs on a different LLM vendor. Looks for unsupported claims, weak citations, tier inflation. True-reject 0.88, false-reject 0.04.

Under the hood · evaluation harness

Quality is measured, not asserted.

Every prompt change, model bump and agent revision runs against a golden set before it reaches production traffic.

The golden dataset

Two hundred historical reconciliations hand-labelled by finance analysts across twelve months of production data. Weighted toward the tail: 40% straightforward, 40% amber-tier variances, 20% red-tier disputes. Each item carries ground-truth tier, variance category and a short human rationale.

200labelled cases
96%variance-detection recall
22%human-touch rate · target 15%

How a change reaches production

  • Unit testsDeterministic checks on parsers, coercers, schema repairs, MCP contracts. Blocks the merge on any red.
  • Golden-set regressionRuns overnight against all 200 items. Alarms when any per-agent metric drops more than 2 points week-on-week.
  • Canary slot5% of production traffic for 24 hours, metrics paired against baseline.
  • Human review sampleA rolling 10% of production runs is human-reviewed; corrections feed the golden set monthly.
  • Ramp5% → 25% → 50% → 100% over four hours, automatic rollback on any regression beyond the change budget.
AgentWhat is measured, on the golden setResult
ParserHow accurately line items are extracted (F1, where 1.0 is perfect)F1 0.94
MatcherHow often the top candidate is the right evidence; how often it is in the top threeP@1 0.91 · R@3 0.98
AnomalyFalse alarms raised while still catching 95% of real variances3.1% false positives
ReconcilerWhether stated confidence matches reality (Brier and calibration error; lower is better)Brier 0.06 · ECE 0.02
ReporterRubric scoring across five dimensions for each of the four tiers5 × 4 rubric
CriticHow often it rejects what should be rejected, and wrongly rejects what is fine0.88 · 0.04
Under the hood · production hardening

Hardened for the tail, not the demo.

The unhappy paths decide whether a system is trusted with money. Every control below is named after the failure it prevents, and each one was walked before the pilot took live traffic.

The platform is run as a production service, not as a model with a chat window. It has latency and error-rate objectives per stage, a health check per agent, and breakers that degrade rather than fail: a tripped MCP server returns a cached read or defers the run, it never stalls the queue. Binary-correctness work, variance arithmetic, tier thresholds and ledger postings, is plain code. Model weights, prompt versions, tool definitions and runtime configuration are pinned per run, so any reconciliation can be replayed exactly.

Reliability

  • Circuit breakers on every external tool call; open breaker → cached read or deferral
  • Retries with exponential backoff and shared jitter on 429 / 502 / 503 / 504
  • Idempotency keys on every mutating call; a re-drive is a no-op
  • Timeouts at every layer, decreasing client → tool; slow tools raise specific errors, not stalls
  • Two-provider LLM strategy; fallback on credit exhaustion, quota block or auth revocation, logged per event
  • Model version pinned per run; structured error taxonomy on every failure

Security & identity

  • Managed Identity between every layer; zero long-lived secrets; Key Vault 30-day rotation
  • Conditional Access; MFA for mutating actions
  • Content Safety on every prompt and response: jailbreaks, injection in invoice text, PII exfiltration
  • PII redaction at ingress: names, phones, tax identifiers scrubbed before embedding
  • Least-privilege MCP tokens; each server its own service account
  • Prompt-injection defence: untrusted text enters tagged as data, never as instruction

Cost & governance

  • Per-user daily cost caps
  • Per-run budget accounting: input, output, cache reads and writes, per agent and model; the Manager halts a run that exceeds its budget
  • Prompt versioning in an immutable store; rollback is one commit
  • Approval gates above threshold; no action executes without the gate
  • Data residency: at rest and in transit, the customer's home region
  • Retention: 7 years financial, 90 days run bundles; GDPR erasure path

Deployment & DR

  • Bicep infrastructure as code; dev → prod parity
  • Blue/green slots; ramp over 30 minutes with auto-rollback on error-rate regression
  • Cross-region replication; MCP servers active-active
  • RTO 4 h · RPO 15 min; failover exercised quarterly
  • Nightly restore tests against a scratch environment
  • Network egress restricted; container-based execution
Under the hood · governance & guardrails

Four layers of guardrail, sized to the blast radius of a mistake.

A reconciliation that posts to a ledger can move real money. So the input is filtered, the prompt is constrained, the output is validated and the tools are limited in code, and the heaviest control sits where the action is hardest to undo.

Input guardrails
Entra identity on every requestContent Safety on every promptPII redaction at ingressInvoice text tagged as untrusted dataParser keeps a source span per field across 40+ supplier formats
↓
System-prompt constraints
No claim without a chunk retrieved this runNo agent edits another agent's citationsRanked candidates, not hard picks, when ambiguousAmber and red are valid outcomes
↓
Output guardrails
Typed state between every agentCritic on a second LLM vendor, default position: disagreementConfidence tier calibrated on six months of history (Brier 0.06, ECE 0.02)Every factual claim in the report carries a citation
↓
Programmatic controls
Least-privilege MCP tokens per serverIdempotent, versioned, reversible writesNo auto-post above NZD 25,000 a lineNo dispute release without analyst sign-offNo ledger reversal without manager approvalPer-run budget halts

Humans where it is irreversible

Review is an architectural decision, not a checkbox. Green-tier OpEx posts automatically because it is reversible and low-value. Amber waits in an analyst queue with the evidence attached. Red, disputes and reversals need a named person's approval in a Teams card. Reviewers see the variance table and citations, not a transcript, so routine approvals take seconds and real decisions get attention.

Failure modes, designed for

  • Hallucination — the citation contract plus the Critic; true-reject 0.88
  • Prompt injection via invoice text — Content Safety and data tagging; the parser never executes instructions
  • Out-of-distribution input — unfamiliar formats fall to amber, not to a guess; false-positive rate 3.1% at 95% recall
  • Over-reliance — a rolling 10% of production runs is human-reviewed and corrections feed the golden set monthly

Compliance and transparency

  • Data stays in the customer's region at rest and in transit
  • Financial records retained 7 years; run bundles 90 days; GDPR erasure path
  • Purview for lineage, PII discovery and audit export
  • Every decision is a datum: evidence used, variance tolerated, outcome recorded
  • Per-supplier dispute-rate trends are reported, so uneven outcomes are visible rather than buried in inboxes
Failure mode
Control
Evidence
MCP server down mid-run
Breaker opens; cached read or deferral; run resumes from durable checkpoint
no duplicate postings in pilot
Primary LLM provider blocked
Automatic fallback to Azure OpenAI; Critic degrades to single-vendor mode, logged
each fallback logged per event
Analyst double-clicks Approve
Idempotency key from the run identifier; second click is a no-op
idempotent on every path
Tariff drift the rules miss
Statistical classifier for tail cases; amber tier; human review sample
96% variance-detection recall
Prompt or model regression
Golden-set regression overnight; 5% canary; ramp with auto-rollback beyond change budget
2-point per-agent alarm
Where it stands

Programme 75% delivered. The audit-blocking spine is complete.

Remaining: meter-market certification, CapEx ledger routing, supplier-portal handoff, reporter polish, a DR drill and a third-party penetration review.

Parser · Matcher · Reconciler · CriticDone
Copilot front door · evaluation harness · observabilityDone
Anomaly Detector ML classifier80% · build
Reporter · Adaptive Cards60% · build
meter-mcp market feed70% · build
ledger-mcp CapEx routing40% · build
dispute-mcp supplier handoff50% · build
DR drill · load test · pen reviewPlanned
What changed

Analysts ask in Teams instead of opening invoices one by one.

Figures from the pilot, against the analysts working by hand.

How much it handles. In the pilot, the agents reconcile this many supplier invoices every month.

1,200
invoices a month · pilot

How often it is right first time. The share of invoices the agents reconcile correctly on their first pass. The target at general availability is 90%.

87%
first-pass reconciliation

How long one invoice takes. From the request in Teams to a closed reconciliation, against about 47 minutes for an analyst working by hand.

~4 min
4.2 minutes measured · was 47

How many real problems it catches. Of the variances the analysts marked in their labelled set, the share Flick detects.

96%
variance-detection recall

What every change must pass first. Past invoices hand-labelled by the analysts, weighted toward the hard cases. Every prompt, model or agent change runs against all of them overnight.

200
analyst-labelled invoices · release gate

How a change reaches everyone. It first serves this share of live traffic for 24 hours against the current version, then ramps to 100% with automatic rollback on any regression.

5%
canary · then 25 → 50 → 100%

Want the same rigour on your workflow?