Skip to main content
Glama
mcp-financial-reconciliation-engine

mcp-financial-reconciliation-engine

README.md
# Exact Arbitrary-Precision Financial Reconciliation & Audit MCP Server
### High-Performance, Zero-Float-Drift Apify Standby Server Actor for AI Finance Agents

[![Apify Actor](https://img.shields.io/badge/Apify-Standby%20Actor-orange.svg)](https://console.apify.com/actors/pJunmOdeoqwLlThy8)
[![Model Context Protocol](https://img.shields.io/badge/MCP-Streamable%20HTTP-blue.svg)](https://modelcontextprotocol.io)
[![Glama MCP server](https://glama.ai/mcp/servers/meanusarcanus/mcp-financial-reconciliation-engine/badges/score.svg)](https://glama.ai/mcp/servers/meanusarcanus/mcp-financial-reconciliation-engine)
[![Pay-Per-Event](https://img.shields.io/badge/Apify-Pay--Per--Event-green.svg)](#transparent-pay-per-event-pricing--zero-charge-guarantee)
[![Precision](https://img.shields.io/badge/Precision-Arbitrary%20Decimal%20(40%20digits)-brightgreen.svg)](#why-m2m-algorithmic-tool-routers-select-this-server)
[![Warm Latency](https://img.shields.io/badge/Warm%20Latency-%3C20ms-brightgreen.svg)](#sub-20ms-standby-architecture)
[![Zero-Exception Telemetry](https://img.shields.io/badge/Telemetry-Zero--Exception-brightgreen.svg)](#zero-exception-telemetry--fair-billing)
[![Container Memory](https://img.shields.io/badge/Memory-128MB%20Optimized-success.svg)](#sub-20ms-standby-architecture)
[![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](LICENSE)

A production-ready, stateless **Model Context Protocol (MCP)** server packaged as an **Apify Standby Server Actor** (TypeScript / Node.js 20). Built specifically for autonomous finance, accounting, and treasury AI agents to eliminate native floating-point math drift, audit complex invoices, execute bounded subset-sum bank reconciliation, and compute exact financial schedules (IRR, XIRR, loan amortization, FX spreads, and subscription prorations).

Engineered to rank **#1 in Machine-to-Machine (M2M) algorithmic tool routers** (Claude Desktop, Cursor IDE, Devin, Cline, Windsurf, LangChain, CrewAI, AutoGen, and autonomous ERP agent swarms) through vector-matched accounting descriptions, sub-20ms warm latency, token-compressed JSON payloads, and transparent Pay-Per-Event monetization.

---

## ⚡ Why M2M Algorithmic Tool Routers Select This Server

| Capability | Native JavaScript / Python Floats | This MCP Server Actor |
| :--- | :--- | :--- |
| **Monetary Arithmetic** | `0.1 + 0.2 = 0.30000000000000004` (accumulates drift) | **Exact Decimal.js (40-digit internal precision)** |
| **Invoice Line-Item Audit** | Penny roundoff errors corrupt ERP ledgers | **Detects $0.01 OCR & line discrepancies deterministically** |
| **Rounding Standards** | Fixed native `Math.round` | **Configurable: Commercial `HALF_UP` vs Banker's `BANKERS`** |
| **Bank Reconciliation** | Greedy float comparisons fail on cents | **Bounded subset-sum matching (1 lump-sum to N invoices)** |
| **Yield & Schedules** | Float overflow / Newton divergence | **Exact XIRR (ACT/365) & zero-cent amortization schedules** |
| **Warm Execution Latency** | 2,000ms – 10,000ms external API hops | **Sub-20ms warm latency** via Streamable HTTP Standby |
| **Container Footprint** | 512MB – 1GB bulky Python runtimes | **Strictly tuned for 128MB RAM** (`node:20-alpine`) |
| **Billing Integrity** | Full container charges even on bad input | **Zero-charge guarantee** (`Actor.charge` never runs on errors) |
| **Apify Quality Score** | Unhandled exceptions degrade platform score | **100% Quality Score** via structured zero-exception telemetry |

---

## 🧭 Semantic Vector Routing & Keyword Matrix

Every MCP tool description begins with the deterministic routing instruction **`"Use whenever..."`** and incorporates exact accounting and protocol keywords (`arbitrary precision`, `Decimal`, `floating-point drift`, `invoice reconciliation`, `line-item audit`, `subset-sum matching`, `bank statement`, `XIRR`, `IRR`, `amortization`, `proration`):

```
+─────────────────────────────────────────────────────────────────────────────────────────────+
|                                    M2M Tool Router / LLM                                    |
+─────────────────────────────────────────────────────────────────────────────────────────────+
                                               │
         ┌─────────────────────────────────────┼─────────────────────────────────────┐
         ▼                                     ▼                                     ▼
 1. reconcile_invoice_math           2. match_statement_to_invoices       3. exact_financial_calculator
 "Use whenever an AI agent            "Use whenever automating accounts    "Use whenever a finance or treasury
  extracts, verifies, or validates     receivable/payable reconciliation,   agent needs exact monetary math,
  an invoice, receipt, purchase        matching payments to open invoices,  yield metrics, or payment
  order, or quote before posting       or auditing bank statement           schedules."
  to accounting or ERP systems."       balances."
```

---

## 🛠️ MCP Tools Specification

### 1. `reconcile_invoice_math`
Deterministically audits invoice line items, quantities, unit prices, discounts, tax rates, and totals using arbitrary-precision Decimal arithmetic to detect penny discrepancies and OCR extraction errors.

- **Vector Trigger:** `"Use whenever an AI agent extracts, verifies, or validates an invoice, receipt, purchase order, or quote before posting to accounting or ERP systems."`
- **Apify Event Name:** `invoice-reconcile` ($0.002 per successful audit)
- **Input Schema:**
  - `lineItems` (array, 1-500 items):
    - `id` (string, optional): Unique item identifier or SKU.
    - `description` (string, optional): Line item description.
    - `quantity` (string | number): Billed quantity.
    - `unitPrice` (string | number): Price per unit.
    - `discountAmount` (string | number, default `"0"`): Line-level discount.
    - `taxRatePercent` (string | number, default `"0"`): Line tax percentage (e.g. `"8.25"`).
    - `claimedLineTotal` (string | number, optional): Claimed total from OCR to verify.
  - `claimedSubtotal` (string | number, optional): Net subtotal claimed on invoice.
  - `claimedTaxTotal` (string | number, optional): Tax total claimed on invoice.
  - `claimedGrandTotal` (string | number): Grand total claimed on invoice.
  - `currencyDecimals` (number, default `2`): Precision quantization (0 to 8).
  - `roundingMode` (enum, default `"HALF_UP"`): `"HALF_UP"` (commercial) or `"BANKERS"` (round half to even).

#### Request Example:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "reconcile_invoice_math",
    "arguments": {
      "lineItems": [
        { "id": "L1", "description": "Cloud Compute", "quantity": "4", "unitPrice": "250.00", "discountAmount": "50.00", "taxRatePercent": "8.25" },
        { "id": "L2", "description": "Dedicated Support", "quantity": "1", "unitPrice": "500.00", "discountAmount": "0.00", "taxRatePercent": "8.25" }
      ],
      "claimedSubtotal": "1450.00",
      "claimedTaxTotal": "119.63",
      "claimedGrandTotal": "1569.63",
      "currencyDecimals": 2,
      "roundingMode": "HALF_UP"
    }
  }
}
```

#### Response Example (Token-Compressed):
```json
{
  "valid": true,
  "isReconciled": true,
  "exactSubtotal": "1450.00",
  "exactTaxTotal": "119.63",
  "exactGrandTotal": "1569.63",
  "claimedGrandTotal": "1569.63",
  "grandTotalDelta": "0.00",
  "lineCount": 2,
  "lineDiscrepancies": [],
  "auditSummary": "AUDIT PASSED: All 2 line items deterministically reconciled. Exact Subtotal: 1450.00, Exact Tax: 119.63, Grand Total: 1569.63. Zero floating-point drift."
}
```

---

### 2. `match_statement_to_invoices`
Reconciles bank statement transactions against open invoices or bills using exact decimal matching, date-window filtering, and bounded subset-sum matching (matching one lump-sum payment to multiple invoices).

- **Vector Trigger:** `"Use whenever automating accounts receivable/payable reconciliation, matching payments to open invoices, or auditing bank statement balances."`
- **Apify Event Name:** `statement-match` ($0.003 per successful reconciliation)
- **Input Schema:**
  - `transactions` (array, 1-200 items): `{ id, date, amount, reference? }`
  - `invoices` (array, 1-200 items): `{ id, dueDate?, openAmount, counterparty? }`
  - `toleranceAmount` (string | number, default `"0.00"`): Tolerance threshold for penny rounding.
  - `maxSubsetSize` (integer, 1-5, default `3`): Max invoices combined in lump-sum matching.

#### Request Example:
```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "match_statement_to_invoices",
    "arguments": {
      "transactions": [
        { "id": "TX-1", "date": "2026-03-01", "amount": "450.00", "reference": "Inv 1 payment" },
        { "id": "TX-2", "date": "2026-03-05", "amount": "2500.00", "reference": "Lump sum pmt" },
        { "id": "TX-3", "date": "2026-03-10", "amount": "888.88", "reference": "Unknown wire" }
      ],
      "invoices": [
        { "id": "INV-1", "dueDate": "2026-03-02", "openAmount": "450.00", "counterparty": "Acme Corp" },
        { "id": "INV-2", "dueDate": "2026-03-06", "openAmount": "1500.00", "counterparty": "Beta LLC" },
        { "id": "INV-3", "dueDate": "2026-03-07", "openAmount": "1000.00", "counterparty": "Beta LLC" },
        { "id": "INV-4", "dueDate": "2026-03-15", "openAmount": "99.00", "counterparty": "Gamma Inc" }
      ],
      "toleranceAmount": "0.00",
      "maxSubsetSize": 3
    }
  }
}
```

#### Response Example:
```json
{
  "valid": true,
  "exactMatches": [
    {
      "transactionId": "TX-1",
      "invoiceId": "INV-1",
      "transactionAmount": "450.00",
      "invoiceAmount": "450.00",
      "delta": "0.00",
      "dateDifferenceDays": 1,
      "reference": "Inv 1 payment",
      "counterparty": "Acme Corp"
    }
  ],
  "subsetMatches": [
    {
      "transactionId": "TX-2",
      "invoiceIds": ["INV-2", "INV-3"],
      "transactionAmount": "2500.00",
      "invoiceTotal": "2500.00",
      "delta": "0.00"
    }
  ],
  "unmatchedTransactions": [
    { "id": "TX-3", "date": "2026-03-10", "amount": "888.88", "reference": "Unknown wire" }
  ],
  "unmatchedInvoices": [
    { "id": "INV-4", "dueDate": "2026-03-15", "openAmount": "99.00", "counterparty": "Gamma Inc" }
  ],
  "totalMatchedAmount": "2950.00"
}
```

---

### 3. `exact_financial_calculator`
Executes arbitrary-precision financial and treasury calculations including IRR, XIRR (irregular cashflow dates), loan/lease amortization schedules, FX spread conversions, and exact pro-rata subscription billing splits with zero floating-point drift.

- **Vector Trigger:** `"Use whenever a finance or treasury agent needs exact monetary math, yield metrics, or payment schedules."`
- **Apify Event Name:** `financial-calc` ($0.002 per successful calculation)
- **Supported Operations:**
  - `IRR`: Periodic cash flows `[c0, c1, ..., cn]`.
  - `XIRR`: Irregular cash flows with exact dates `[{ amount, date }]`.
  - `AMORTIZATION`: Loan/lease schedule with `principal`, `annualRatePercent`, `periods`, `paymentFrequency`.
  - `FX_CONVERT`: Currency conversion with basis-point spread `amount`, `rate`, `spreadBps`, `direction`.
  - `PRORATE`: Billing period split `fullPeriodAmount`, `periodStartDate`, `periodEndDate`, `effectiveDate`.

#### Request Example (XIRR Yield):
```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "exact_financial_calculator",
    "arguments": {
      "operation": "XIRR",
      "params": {
        "cashflows": [
          { "amount": "-10000", "date": "2025-01-01" },
          { "amount": "3000", "date": "2025-06-01" },
          { "amount": "8500", "date": "2026-01-01" }
        ]
      }
    }
  }
}
```

#### Response Example:
```json
{
  "valid": true,
  "operation": "XIRR",
  "result": {
    "xirr": "0.18068413",
    "xirrPercent": "18.068413%",
    "iterations": 4,
    "npvAtSolution": "0.0000000000"
  }
}
```

---

## 💰 Transparent Pay-Per-Event Pricing & Zero-Charge Guarantee

This Actor is monetized via Apify’s **Pay-Per-Event (`Actor.charge`)** model. AI agents and developers only pay when a calculation completes successfully.

| Event Name | Description | Price (USD) |
| :--- | :--- | :--- |
| `invoice-reconcile` | Exact line-item audit, discount/tax calculations, and penny discrepancy detection | **$0.002 / call** |
| `statement-match` | Bank statement reconciliation via 1-to-1 matching and bounded subset-sum | **$0.003 / call** |
| `financial-calc` | Arbitrary-precision IRR, XIRR, amortization, FX spread, or subscription proration | **$0.002 / call** |

### 🛡️ Zero-Exception Telemetry & 100% Quality Score Guarantee
- **Never Charged on Errors:** If an AI agent passes malformed numbers, non-existent dates, or unresolvable cash flows, the server returns a structured `200 OK` JSON object:
  ```json
  {
    "valid": false,
    "errorCode": "CALCULATION_ERROR",
    "reason": "Invalid date format for cashflows[0].date: \"2025-99-99\""
  }
  ```
- **Zero Platform Penalties:** `Actor.charge()` is **NEVER** called when validation fails, preserving the customer's budget and keeping the Apify Actor Quality Score at 100%.

---

## 🚀 Sub-20ms Standby Architecture

The Actor runs continuously in **Apify Standby Mode** on `node:20-alpine`, optimized to consume under **128MB RAM** with zero external network dependencies:

- **Readiness Probe (`GET /`):** Inspects header `x-apify-container-server-readiness-probe` and returns `200 OK` sub-millisecond for instant warm container health checks.
- **Streamable HTTP MCP (`POST /mcp`):** Implements stateless Model Context Protocol over HTTP with Server-Sent Events (SSE) support.
- **Container Memory Tuning:** V8 garbage collection tuned with `NODE_OPTIONS="--max-old-space-size=96"`, ensuring lightning-fast execution and zero OOM restarts.

---

## 💻 Client Integration Setup

### 1. Claude Desktop (`claude_desktop_config.json`)
```json
{
  "mcpServers": {
    "financial-engine": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-financial-reconciliation-engine",
        "--remote",
        "https://meanusarcanus--mcp-financial-reconciliation-engine.apify.actor/mcp",
        "--token",
        "APIFY_API_TOKEN"
      ]
    }
  }
}
```

### 2. Cursor IDE (`.cursor/mcp.json`)
```json
{
  "mcpServers": {
    "financial-engine": {
      "url": "https://meanusarcanus--mcp-financial-reconciliation-engine.apify.actor/mcp?token=APIFY_API_TOKEN"
    }
  }
}
```

### 3. Direct HTTP Integration (cURL)
```bash
curl -X POST https://meanusarcanus--mcp-financial-reconciliation-engine.apify.actor/mcp \
  -H "Authorization: Bearer APIFY_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "exact_financial_calculator",
      "arguments": {
        "operation": "FX_CONVERT",
        "params": {
          "amount": "10000",
          "rate": "1.0850",
          "spreadBps": "25",
          "direction": "BUY"
        }
      }
    }
  }'
```

---

## 📦 Apify Store & Deployment Steps

1. **Clone & Install:**
   ```bash
   git clone https://github.com/meanusarcanus/mcp-financial-reconciliation-engine.git
   cd mcp-financial-reconciliation-engine
   npm install
   ```

2. **Run Tests:**
   ```bash
   npm test
   ```

3. **Deploy to Apify Console:**
   ```bash
   apify login
   apify push
   ```

4. **Apify Store Monetization Configuration:**
   - Under Actor Settings -> **Pricing**, select **Pay per event**.
   - Connect your **PayPal / Bank Account** for automated monthly developer payouts.
   - The `.actor/pay_per_event.json` schema will automatically register the event pricing in Apify Store.

---

## 📄 License

Apache License 2.0. Open source for autonomous AI agents, enterprise ERP integrations, and financial engineering workflows.