# Invoice & PO Deterministic Math Validator (MCP) (`snowy_divide_r1t/structured-invoice-line-validator`) Actor

Zero-scraping deterministic B2B invoice & purchase order auditor. Catches LLM subtotal/tax hallucinations with exact BigInt cents math and outputs clean normalized JSON.

- **URL**: https://apify.com/snowy_divide_r1t/structured-invoice-line-validator.md
- **Developed by:** [對帳 秒](https://apify.com/snowy_divide_r1t) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$4.00 / 1,000 invoice validateds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Structured Invoice & PO Deterministic Validator (MCP)

**Stop LLM arithmetic hallucinations before they corrupt your ERP, QuickBooks, Xero, or Google Sheets.**

AI models (GPT, Claude, Gemini) and OCR pipelines are great at *reading* messy PDF invoices—but notoriously unreliable at *math*. They routinely miscalculate `quantity × unit_price`, silently drop negative credit-note signs, hallucinate tax totals, or break on currency rounding.

**Structured Invoice & PO Deterministic Validator** is a **zero-scraping, pure-compute, 100% deterministic financial auditing Actor & MCP Tool**. Feed it raw JSON extracted by any LLM or OCR engine, and get back:

- Exact integer minor-unit math verification (zero IEEE-754 floating-point drift)
- Explicit LLM hallucination flagging (`hallucinationDetected`, `expected`, `actual`, `delta`)
- Multi-country Tax ID / VAT / EIN / Taiwan GUI checksum verification
- Clean, strictly typed, auto-corrected `normalizedInvoice` JSON ready for downstream automation

***

### Why Developers Choose This Actor

| Feature | LLM Self-Checking | This Deterministic MCP Actor |
|---|---|---|
| Arithmetic accuracy (`19.99 × 3`, taxes, credits) | Probabilistic (hallucination-prone) | **100% Exact BigInt Minor-Unit Math** |
| External URL / Web Scraping | N/A | **Zero Scraping, Zero Outbound Calls, Zero SSRF** |
| Data Privacy & Latency | Slow extra LLM round-trip | **Pure in-memory compute (< 50ms core execution)** |
| Cost Predictability | High token cost per retry | **Pay-Per-Event: `$0.004` per invoice** |
| Downstream Routing | Free-form text explanations | **Machine-readable error codes for n8n / Make IF nodes** |

***

### What It Validates & Normalizes

1. **Line-Item Math**: Verifies `quantity × unit_price - discount = line_total` across arbitrary decimal quantities (up to 6 decimal places) and messy currency strings (`"$1,234.50"`, `"NT$ 10,500"`, `"1.234,50"`, accounting negatives `"(50.00)"`).
2. **Credit Notes & Discounts**: Distinguishes legitimate negative credit lines from OCR/LLM sign-flip errors (`NEGATIVE_SIGN_MISMATCH`).
3. **Tax & Grand Total Verification**: Supports both **tax-exclusive** and **tax-inclusive** modes, per-line or header tax rates, shipping, and invoice-level discounts.
4. **Multi-Currency Precision**: Built-in ISO-4217 minor unit table (`USD/EUR/GBP`: 2 decimals, `TWD/JPY/KRW`: 0 decimals, `KWD/BHD`: 3 decimals) with configurable `HALF_UP` or `HALF_EVEN` rounding.
5. **Multi-Country Tax IDs**: Validates **EU/UK VAT formats** (`DE`, `FR`, `NL`, `GB`, `ES`, `IT`, etc.), **US EIN**, and **Taiwan Unified Business Numbers (MOF 2023+ checksum)**.
6. **Date & Duplicate Guards**: Normalizes ISO, US, and Taiwan ROC dates (`115/11/28` → `2026-11-28`), rejects impossible calendar dates and `due_date < issue_date`, and flags duplicate OCR line extractions (`DUPLICATE_LINE_ITEM`).

***

### Pricing (Pay-Per-Event)

- **`invoice-validated`**: **`$0.004` USD** per invoice audited and normalized (`$4.00` per 1,000 invoices).
- No proxy costs. No hidden browser compute overhead. Runs at minimal 128–256MB memory.

***

### Example Input

```json
{
  "invoice": {
    "invoice_number": "INV-2026-0042",
    "vendor_name": "Neural Supplies GmbH",
    "vendor_tax_id": "DE123456789",
    "issue_date": "2026-11-15",
    "due_date": "2026-12-15",
    "currency": "EUR",
    "tax_rate": "19%",
    "line_items": [
      {
        "description": "GPU Rack Mount",
        "quantity": 7,
        "unit_price": 149.5,
        "line_total": 1096.5
      },
      {
        "description": "Fiber Patch Cable",
        "quantity": 4,
        "unit_price": 12.25,
        "line_total": 49.0
      }
    ],
    "subtotal": 1145.5,
    "tax_amount": 217.65,
    "total": 1363.15
  },
  "options": {
    "toleranceMinorUnits": 1,
    "autoCorrectOutput": true
  }
}
```

### Example Output (Hallucination Caught & Auto-Corrected)

```json
{
  "invoiceNumber": "INV-2026-0042",
  "status": "INVALID",
  "hallucinationDetected": true,
  "confidenceScore": 0,
  "currency": "EUR",
  "issueCount": 4,
  "issues": [
    {
      "code": "LINE_SUBTOTAL_MISMATCH",
      "severity": "ERROR",
      "field": "line_items[0].line_total",
      "expected": 1046.5,
      "actual": 1096.5,
      "delta": 50
    }
  ],
  "auditTrail": {
    "subtotal": { "reported": 1145.5, "computed": 1095.5, "delta": 50 },
    "tax": { "reported": 217.65, "computed": 208.15, "delta": 9.5 },
    "grandTotal": { "reported": 1363.15, "computed": 1303.65, "delta": 59.5 }
  },
  "normalizedInvoice": {
    "invoice_number": "INV-2026-0042",
    "currency": "EUR",
    "subtotal": 1095.5,
    "tax_amount": 208.15,
    "total": 1303.65
  }
}
```

***

### Integration Guide

#### 1. Connect via Claude Desktop / Cursor (Apify MCP Server)

Add this to your `claude_desktop_config.json` or Cursor MCP configuration:

```json
{
  "mcpServers": {
    "apify-invoice-validator": {
      "command": "npx",
      "args": [
        "-y",
        "@apify/actors-mcp-server",
        "--actors",
        "YOUR_APIFY_USERNAME/structured-invoice-line-validator"
      ],
      "env": {
        "APIFY_TOKEN": "YOUR_APIFY_API_TOKEN"
      }
    }
  }
}
```

#### 2. Connect via n8n / Make (AP Automation Guardrail)

Recommended 4-node workflow:

1. **Trigger**: Email Attachment / Google Drive PDF upload.
2. **LLM Extraction Node**: Extract raw invoice JSON (OpenAI / Claude / Mistral OCR).
3. **Apify Run Actor Node** (`structured-invoice-line-validator`): Pass `{{ $json }}` into `invoice`.
4. **IF Router Node**:
   - `status === "VALID"` → Auto-post `normalizedInvoice` to QuickBooks / Xero / ERP.
   - `hallucinationDetected === true` → Route to Slack/Email human approval with exact `auditTrail` diff.

***

### Security & Compliance Statement

This Actor performs **100% deterministic in-memory computation** on user-supplied JSON payloads. It does not accept external URLs, does not scrape websites, does not make outbound network requests, and does not transmit financial documents to third-party AI APIs.

# Actor input Schema

## `invoice` (type: `object`):

A single raw invoice, purchase order, or receipt JSON object extracted by an LLM or OCR engine. Mutually complementary with 'invoices'.

## `invoices` (type: `array`):

An array of raw invoice JSON objects to validate in a single batch run (up to 1,000 invoices per run).

## `options` (type: `object`):

Optional deterministic rules controlling currency fallback, tax mode, rounding, tolerance, and tax ID strictness.

## Actor input object example

```json
{
  "invoice": {
    "invoice_number": "INV-2026-0042",
    "vendor_name": "Acme Cloud Components Ltd.",
    "vendor_tax_id": "DE123456789",
    "issue_date": "2026-11-28",
    "due_date": "2026-12-28",
    "currency": "USD",
    "tax_rate": 0.0825,
    "line_items": [
      {
        "description": "Dedicated Compute Node",
        "quantity": 3,
        "unit_price": 19.99,
        "line_total": 59.97
      },
      {
        "description": "Data Transfer Tier",
        "quantity": 2,
        "unit_price": 0.15,
        "line_total": 0.3
      }
    ],
    "subtotal": 60.27,
    "tax_amount": 4.97,
    "total": 65.24
  },
  "options": {
    "defaultCurrency": null,
    "defaultTaxRate": null,
    "taxInclusive": false,
    "toleranceMinorUnits": 1,
    "roundingMode": "HALF_UP",
    "strictTaxId": true,
    "detectDuplicates": true,
    "autoCorrectOutput": true
  }
}
```

# Actor output Schema

## `overview` (type: `string`):

Structured dataset items showing audit status, LLM math hallucination flags, health score, and issues.

## `results` (type: `string`):

Complete normalized invoice JSON and detailed audit findings from the default dataset.

## `summary` (type: `string`):

Aggregated run summary JSON stored in the default Key-Value Store under the OUTPUT key.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "invoice": {
        "invoice_number": "INV-2026-0042",
        "vendor_name": "Acme Cloud Components Ltd.",
        "vendor_tax_id": "DE123456789",
        "issue_date": "2026-11-28",
        "due_date": "2026-12-28",
        "currency": "USD",
        "tax_rate": 0.0825,
        "line_items": [
            {
                "description": "Dedicated Compute Node",
                "quantity": 3,
                "unit_price": 19.99,
                "line_total": 59.97
            },
            {
                "description": "Data Transfer Tier",
                "quantity": 2,
                "unit_price": 0.15,
                "line_total": 0.3
            }
        ],
        "subtotal": 60.27,
        "tax_amount": 4.97,
        "total": 65.24
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("snowy_divide_r1t/structured-invoice-line-validator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "invoice": {
        "invoice_number": "INV-2026-0042",
        "vendor_name": "Acme Cloud Components Ltd.",
        "vendor_tax_id": "DE123456789",
        "issue_date": "2026-11-28",
        "due_date": "2026-12-28",
        "currency": "USD",
        "tax_rate": 0.0825,
        "line_items": [
            {
                "description": "Dedicated Compute Node",
                "quantity": 3,
                "unit_price": 19.99,
                "line_total": 59.97,
            },
            {
                "description": "Data Transfer Tier",
                "quantity": 2,
                "unit_price": 0.15,
                "line_total": 0.3,
            },
        ],
        "subtotal": 60.27,
        "tax_amount": 4.97,
        "total": 65.24,
    } }

# Run the Actor and wait for it to finish
run = client.actor("snowy_divide_r1t/structured-invoice-line-validator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "invoice": {
    "invoice_number": "INV-2026-0042",
    "vendor_name": "Acme Cloud Components Ltd.",
    "vendor_tax_id": "DE123456789",
    "issue_date": "2026-11-28",
    "due_date": "2026-12-28",
    "currency": "USD",
    "tax_rate": 0.0825,
    "line_items": [
      {
        "description": "Dedicated Compute Node",
        "quantity": 3,
        "unit_price": 19.99,
        "line_total": 59.97
      },
      {
        "description": "Data Transfer Tier",
        "quantity": 2,
        "unit_price": 0.15,
        "line_total": 0.3
      }
    ],
    "subtotal": 60.27,
    "tax_amount": 4.97,
    "total": 65.24
  }
}' |
apify call snowy_divide_r1t/structured-invoice-line-validator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,snowy_divide_r1t/structured-invoice-line-validator"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/IR8nejtJWqeImE87w/builds/4N9wGzn2wLFJIEmdg/openapi.json
