# Vendor Creep & Overcharge Guard MCP Server (`rhythmic_clothier/pdf-struct-mcp`) Actor

Zero-PO deterministic invoice auditing for AI agents: catch silent vendor price hikes, sneaky new fees, exact-cent math errors, and duplicate billing with page/line evidence citations, annualized creep impact, and ready-to-send dispute memos.

- **URL**: https://apify.com/rhythmic_clothier/pdf-struct-mcp.md
- **Developed by:** [Adam Saul](https://apify.com/rhythmic_clothier) (community)
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $100.00 / 1,000 audit vendor invoice pdfs (ap guardrail)

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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

## Vendor Creep & Overcharge Guard MCP (`pdf-struct-mcp`)

> **Verify before you pay — deterministic invoice auditing, zero-PO vendor creep detection, and ready-to-send dispute memos for AI agents.**

LLMs can read a PDF, but they routinely miss 1-cent arithmetic errors, silently drop rows on multi-page invoices, misread European decimals or accounting parentheses, and hallucinate totals. **Vendor Creep & Overcharge Guard MCP** runs pure deterministic parsing and exact-cent accounting math (zero upstream LLM calls) so agents and AP reviewers get provable verdicts and page-level evidence.

***

### Why Use This MCP Server?

- **Works Zero-PO (Month-over-Month Drift):** No ERP or formal PO required — pass this month's invoice PDF alongside last month's invoice PDF to catch silent unit-price hikes, sneaky new fees, usage spikes, and annualized cost impact (`monthly delta × 12`).
- **Full PO & Rate-Card Matching:** Also accepts structured PO / rate-card JSON (`baseline_po`) to enforce contracted unit prices, quantity limits, combined split-row allowances, and total caps.
- **Ready-to-Send Dispute Memos:** When discrepancies are found, returns a zero-hallucination `dispute_memo` citing `[Page X, Line Y]`, exact math formulas, and the tax-adjusted `credit_requested_amount` — keeping internal extraction/usage warnings strictly separate from vendor-facing claims.
- **Exact-Cent Accounting Engine:** Handles multi-page invoices (with or without repeated headers), European (`€1.496,28`, `€1 234,56`) and US formats, accounting parentheses `($25.00)`, fractional quantities/rates, multi-tax components (`GST` + `PST` / `VAT`), wrapped descriptions, and vendor-scoped SHA-256 duplicate fingerprinting.
- **Five Invoice Languages:** Reads English, Dutch, French, German and Spanish invoices: their labels (`Factuurnummer`, `Facture n°`, `Rechnungsdatum`, `Base imponible`, `BTW`/`TVA`/`MwSt.`/`IVA`), comma decimals, day-first and written dates (`7. Mai 2014`, `1 de enero de 2026`, returned as ISO `issue_date_iso` / `due_date_iso`), prices that already include VAT, discount columns and per-line tax columns. Receipts, quotes and estimates are recognised and not charged.
- **Agent-Friendly by Design:** Free preview tool (`inspect_pdf`), outcome-based billing (non-invoices and scanned PDFs without a text layer return `$0` charge), and `detail: "auto"` compact mode (shrinks a 3,000-line audit from ~1 MB to ~1.5 KB).

***

### Tools & Outcome Pricing

| Tool | Tier / Price | Apify Event | What It Does |
| --- | --- | --- | --- |
| `inspect_pdf` | **Free** | — | Pre-flight check: page count, `has_text_layer`, metadata, detected tables, 3-row sample, `looks_like_invoice`, and arithmetic-only `quick_risk_preview`. |
| `audit_invoice_pdf` | **$0.10 / job** | `audit-invoice-pdf` | Full deterministic AP audit: exact-cent line/subtotal/multi-tax/total checks, page/line evidence, SHA-256 duplicate fingerprints, `APPROVE` / `HOLD_FOR_REVIEW` / `REJECT` verdict, and `dispute_memo`. |
| `compare_invoice_to_baseline` | **$0.15 / job** | `compare-invoice-baseline` | Zero-PO month-over-month diff (against prior invoice PDF) **or** PO/rate-card match (`baseline_po` JSON). Catches unit price creep, unauthorized fees, split-row allowance reuse, usage spikes (`usage_spike_threshold_pct`, default `50%`), duplicate billing, annualized creep impact, and generates `dispute_memo`. |
| `parse_invoice_pdf` | **$0.08 / job** | `parse-invoice-pdf` | Extracts structured invoice headers, typed line items (with page & line provenance), multi-tax breakdown, and exact-cent reconciliation. |
| `extract_pdf_tables` | **$0.05 / job** | `extract-pdf-tables` | Extracts all tables across selected pages (`"all"` or `"1-3,5"`) into `json`, RFC-4180 `csv`, or `markdown`. |

#### Input Sources & Options

- **Sources (provide exactly one):** `pdf_url` (public HTTP/HTTPS, max 25 MB, 15s timeout), `pdf_base64`, or `file_path` (*local stdio mode only; disabled over HTTP for security*).
- **Compact Output (`detail`):** `audit_invoice_pdf` and `compare_invoice_to_baseline` support `detail: "auto" | "compact" | "full"`. Defaults to `"auto"` (switches to compact above 100 line items to protect agent context windows).
- **Zero-Charge Guardrails:** Scanned PDFs with no text layer return `NO_TEXT_LAYER` (advising OCR first) at **$0**, and non-invoice documents return `NOT_AN_INVOICE` at **$0**.

***

### Connect from Your AI Client

#### Remote (hosted on Apify — recommended)

Connect any Streamable HTTP MCP client to:

```
https://rhythmic-clothier--pdf-struct-mcp.apify.actor/mcp
```

with the header `Authorization: Bearer <YOUR_APIFY_TOKEN>` (free Apify account; copy the token from
Apify Console → Settings → API & Integrations). You pay only per completed job, at the prices above.

**Claude Code:**

```bash
claude mcp add --transport http invoice-guard https://rhythmic-clothier--pdf-struct-mcp.apify.actor/mcp --header "Authorization: Bearer <YOUR_APIFY_TOKEN>"
```

**Any client with a JSON config:**

```json
{
  "mcpServers": {
    "invoice-guard": {
      "type": "http",
      "url": "https://rhythmic-clothier--pdf-struct-mcp.apify.actor/mcp",
      "headers": { "Authorization": "Bearer <YOUR_APIFY_TOKEN>" }
    }
  }
}
```

#### Local (`stdio`, self-hosting from source)

**Claude Desktop** (`~/Library/Application Support/Claude/claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "pdf-struct": {
      "command": "node",
      "args": ["/path/to/pdf-struct-mcp/dist/index.js"],
      "env": {
        "BILLING_MODE": "free_dev"
      }
    }
  }
}
```

**Claude Code:**

```bash
claude mcp add pdf-struct -e BILLING_MODE=free_dev -- node /path/to/pdf-struct-mcp/dist/index.js
```

**OpenAI Codex CLI:**

```bash
codex mcp add pdf-struct --env BILLING_MODE=free_dev -- node /path/to/pdf-struct-mcp/dist/index.js
```

***

### Local Development & Verification

```bash
npm install
npm run test:all   # Builds TypeScript and runs every suite, including 26 generated and 11 real public invoices
```

- **MCP Inspector:** `BILLING_MODE=free_dev npm run inspect`
- **Local HTTP mode:** `MCP_TRANSPORT=http BILLING_MODE=api_key VALID_API_KEYS=sk_live_demo npm start` (`GET /health`, `POST /mcp`)
- **Generate realistic sample PDFs:** `npm run generate:samples`

***

### Security & Billing Model

- **SSRF & DNS-Rebinding Defense:** `pdf_url` validates resolved IPs at connect time (and across redirects), blocking `localhost`, private/link-local ranges, IPv6 private ranges, and cloud metadata (`169.254.169.254`), with a hard 15s total download timeout and streaming 25 MB limit.
- **No Remote Disk Access:** `file_path` and `baseline_file_path` are rejected in HTTP mode unless explicitly opted in for private self-hosting (`ALLOW_LOCAL_FILES=1`).
- **Fail-Closed Apify Billing:** In Apify Standby (`BILLING_MODE=apify`), charges include `X-Actor-Request-ID` with an idempotency key and fail closed (`BILLING_FAILED`, $0 charged) if Apify does not confirm the charge.

***

### Deploying to Apify

```bash
npx apify-cli login
npx apify-cli push
```

In **Apify Console → Publication / Monetization**, enable **Standby mode** and **Pay per event** using the four event names in [.actor/pay_per_event.json](.actor/pay_per_event.json). Leave `ALLOW_LOCAL_FILES` and `ALLOW_PRIVATE_URLS` unset on Apify.

# Actor input Schema

## Actor input object example

```json
{}
```

# Actor output Schema

## `mcpEndpoint` (type: `string`):

Point your MCP client here.

## `health` (type: `string`):

No description

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("rhythmic_clothier/pdf-struct-mcp").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("rhythmic_clothier/pdf-struct-mcp").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 '{}' |
apify call rhythmic_clothier/pdf-struct-mcp --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rhythmic_clothier/pdf-struct-mcp"
        }
    }
}
```

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/X4S7bL7m8HoTO41LS/builds/oI1mW3q3SgGxsptBF/openapi.json
