finance-engines-mcp
Deterministic, offline finance engines for AI agents — 14 stdio MCP tools covering commodity margin math, loan covenant monitoring, invoice/AP audit, and multi-ERP five-day close, plus a UiPath routing wrapper; every call is pure, stateless, and returns identical output for identical input.
Margin economics —
product_marginscomputes revenue/cost/margin per MT per product from assay × payable × index price with inventory mark-to-market;price_sensitivitybuilds a shock grid (default ±10/25%, uniform and per-metal);breakevenderives the index prices where margin/MT hits zero;evaluate_contractsprices grade-multiplier, discount+profit-share, collar, and assay-payables structures at spot and flags binding terms.Loan covenants —
parse_trial_balanceflattens a Xero trial-balance payload into netted section balances;compute_covenant_metricsderives EBITDA, DSCR, current ratio, leverage, liquidity, and more;evaluate_covenantstests each metric against thresholds with % headroom;compliance_certificateruns the full chain and renders a signable markdown lender certificate for a period.Invoice audit —
audit_invoicesruns eight anomaly rules (duplicates, entry lag, overdue-unpaid, amount outliers, unit-rate changes, new charge types, unexplained credits, inconsistent tax);normalize_invoice_numbercanonicalizes numbers soINV123/#INV123/NV123collide.AP exceptions —
classify_ap_exceptionssorts invoices into a taxonomy (duplicate, missing/mismatched PO, missing receipt, wrong legal entity, tax review, ownerless approval) with confidence scores and stable reason codes.Five-day close —
close_readinessandfive_day_closeinventory ERP extracts, flag stale inputs, track reconciliation coverage, walk the six gates (source freeze, subledger cutoffs, reconciliation queue, evidence bundle, exception SLA, controller sign-off), optionally flash covenants, and report operator metrics (straight-through rate, double-handling minutes, stale-input rate, hours-to-close).Integration —
uipath_handoffroutes a UiPath payload to any of the five underlying engines; bundled sample configs/prices apply where inputs are optional, so you can run everything with no setup.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@finance-engines-mcp compute product margins for black mass at current index prices"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
@cubiczan/finance-engines
Deterministic finance engines for AI agents: commodity margins, loan covenants, invoice audit, AP exceptions, and five-day close — as a TypeScript library and a licensed MCP server.
LLM agents are good at judgment and bad at arithmetic. This package gives them the arithmetic: pure, offline, fully deterministic engines that always return the same numbers for the same inputs — no network, no state, no hallucinated math. Use them directly from TypeScript/JavaScript, or hand them to any MCP-compatible agent (Claude Code, Claude Desktop, Cursor, custom agents) as a stdio tool server.
Commercial software.
UNLICENSED— all rights reserved. Use requires a commercial agreement: sam@cubiczan.com. See LICENSE.md and PROVENANCE.md.
Engines
Margin — index-linked product economics for commodity processors (e.g. battery recycling): revenue/margin per tonne from assay x payable x index price, inventory mark-to-market, shock-grid price sensitivity, breakeven prices, and config-driven contract structures (grade multiplier, discount + profit share, collar, assay payables).
Covenant — loan covenant monitoring: parse a trial balance (Xero payload or plain records), compute EBITDA / DSCR / current ratio / leverage / liquidity, evaluate against covenant thresholds with headroom, and render a signable markdown compliance certificate.
Audit — vendor-invoice anomaly detection for procure-to-pay: duplicate invoice numbers, entry lag, overdue-unpaid, amount outliers, unit-rate changes, new charge types, unexplained credits, inconsistent tax.
Close — multi-ERP five-day-close readiness (source freeze, subledger cutoffs, reconciliation queue, evidence bundle, exception SLA, controller sign-off) plus an AP exception taxonomy with confidence and reason codes. Operator metrics: straight-through rate, synthetic double-handling minutes, stale-input rate, hours-to-close.
Related MCP server: ETL-D MCP Server
Quickstart — library
npm install @cubiczan/finance-enginesimport {
productEconomics, sensitivity, breakevenPrices, evaluateAllContracts,
parseXeroTrialBalance, computeMetrics, evaluateCovenants, certificateMarkdown,
runAllAuditRules, normalizeInvoiceNumber,
classifyApExceptions, runFiveDayClose, assessCloseReadiness,
defaultMarginConfig, defaultCovenantConfig,
} from "@cubiczan/finance-engines";
// Margins: bring your own config/prices, or use the bundled defaults
const prices = { LI2CO3: 12000, "LME-NI": 16000, "LME-CO": 34000, "LME-CU": 9600 };
const econ = productEconomics(defaultMarginConfig, prices);
const grid = sensitivity(defaultMarginConfig, prices, "black_mass");
const be = breakevenPrices(defaultMarginConfig, prices, "black_mass");
const contracts = evaluateAllContracts(defaultMarginConfig, prices);
// Covenants: trial balance -> metrics -> evaluation -> certificate
const tb = parseXeroTrialBalance(xeroTrialBalanceJson);
const metrics = computeMetrics(tb, defaultCovenantConfig);
const results = evaluateCovenants(metrics, defaultCovenantConfig);
const certificate = certificateMarkdown(results, metrics, "Q2 2026");
// Invoice audit: plain rows in, findings out
const findings = runAllAuditRules(invoiceRows, itemRows, { today: "2026-07-03" });
normalizeInvoiceNumber("#INV20481"); // -> "20481"
// AP exceptions + five-day close: see the cookbook below
const exceptions = classifyApExceptions(invoiceRows, itemRows);
const close = runFiveDayClose(closePayload); // period, now, freeze_at, sources, …The engine core has zero runtime dependencies (the MCP SDK is only loaded by the server entry point).
UiPath can hand invoice rows, trial balances, or contract payloads to the same deterministic tools through the uipath_handoff MCP tool or directly into the library.
Procurement-profitability integration contract
The package exports a type-only boundary for callers that coordinate covenant checks, invoice audit, AP exceptions, and a five-day close:
import {
type CovenantCheckInput,
type InvoiceAuditInput,
type APExceptionsInput,
type FiveDayCloseInput,
type ProcurementProfitabilityAdapter,
} from "@cubiczan/finance-engines";
const adapter: ProcurementProfitabilityAdapter = {
checkCovenant: (input: CovenantCheckInput) => {
// Call parse/compute/evaluate/certificate from this package here.
return callerOwnedCovenantResult(input);
},
auditInvoices: (input: InvoiceAuditInput) => callerOwnedInvoiceAudit(input),
reviewAPExceptions: (input: APExceptionsInput) => callerOwnedAPReview(input),
assessFiveDayClose: (input: FiveDayCloseInput) => callerOwnedCloseReview(input),
};CovenantCheckInput/Output and InvoiceAuditInput/Output use the package's
existing typed engine rows and results. APExceptions* and FiveDayClose*
describe caller-owned workflow data; this package does not persist, fetch, or
resolve those records. Every contract carries provenance.invocation: "dependency"
to make that boundary explicit. This example is an integration contract only:
callers must have a commercial license and must depend on this package rather
than copy its internals. See LICENSE.md and
PROVENANCE.md.
Quickstart — MCP server
The package ships a stdio MCP server as the finance-engines-mcp binary.
# Claude Code
claude mcp add finance-engines -- npx -y @cubiczan/finance-engines finance-engines-mcp
# or, with the package installed:
claude mcp add finance-engines -- finance-engines-mcpOr in a generic MCP client config:
{
"mcpServers": {
"finance-engines": {
"command": "npx",
"args": ["-y", "@cubiczan/finance-engines", "finance-engines-mcp"]
}
}
}All tools are deterministic and offline. Where config/prices are optional,
bundled sample defaults apply — supply your own to price your own book.
MCP tools
Tool | Engine | What it does |
| margin | Revenue, cost, and margin per MT per product, with metal contributions and inventory mark |
| margin | Margin/MT scenario grid under uniform and per-metal price shocks |
| margin | Implied per-metal index prices at which a product's margin hits zero |
| margin | Evaluate grade-multiplier / profit-share / collar / assay-payables contract structures at spot |
| covenant | Flatten a Xero Reports/TrialBalance payload into netted section balances |
| covenant | EBITDA, DSCR, current ratio, leverage, liquidity, etc. from a trial balance |
| covenant | Test metrics against covenant thresholds with % headroom |
| covenant | End-to-end signable markdown covenant certificate for a period |
| audit | Run all eight invoice anomaly rules over supplied invoice/item rows |
| audit | Canonicalize an invoice number for duplicate detection |
| audit | AP exception taxonomy with confidence + reason codes (reuses duplicate/tax rules) |
| close | Inventory extracts, stale inputs, reconciliation coverage, hours-to-close |
| close | Six-gate five-day close + metrics; optional covenant evidence |
| UiPath | Route a UiPath payload to invoice audit, covenant certificate, contract evaluation, AP exceptions, or five-day close |
Development
npm install
npm run build # tsc -> dist/
npm test # builds, then runs all suites + MCP smoke test (node --test)
npm run example:close # multi-ERP five-day close fixtureThe test suites mirror the donor Python test suites number-for-number (same fixtures, same hand-computed expectations), proving the ports equivalent.
Cookbook — five-day close + AP exceptions
PE-style close pressure (multiple ERPs, five-day clock, AP exceptions killing straight-through rate) is the operator problem this example is built against. The engines stay offline and deterministic; they do not talk to NetSuite, SAP, or Xero.
npm run example:close
# or, after a build:
node examples/five-day-close/run.mjsThe fixture (examples/five-day-close/fixture.json) is a synthetic June 2026
close across three ERPs:
System | ERP | Entity |
| NetSuite | US HoldCo |
| SAP | DE OpCo GmbH |
| Xero | UK Shared Services Ltd |
It walks the six gates — source freeze, subledger cutoffs, reconciliation
queue, evidence bundle, exception SLA, controller sign-off — and classifies
the AP corpus (duplicates reuse normalizeInvoiceNumber; plus missing /
mismatched PO, missing receipt, wrong legal entity, tax review, ownerless
approval).
Library equivalent:
import { readFileSync } from "node:fs";
import { runFiveDayClose, classifyApExceptions, apExceptionTaxonomy } from "@cubiczan/finance-engines";
const payload = JSON.parse(readFileSync("examples/five-day-close/fixture.json", "utf8"));
const report = runFiveDayClose(payload);
// report.gates, report.metrics, report.exceptions, report.covenant, report.signoff_readyPass the same payload to MCP tools five_day_close / close_readiness
({ "close": { …payload } }) or classify_ap_exceptions.
Illustrative vs production
Deterministic engine (this package)
Gate status, stale flags, coverage, hours-to-close, exception codes / reason codes / confidence, and the four operator metrics — given the same payload, every run returns the same JSON.
Duplicate detection is the existing audit normalizer, not a second scheme.
Covenant flash, when a trial balance is supplied, is the existing covenant engine (same certificate markdown).
Illustrative only (do not treat as measured ops data)
Every timestamp in the fixture (
now,freeze_at, extract times, SLA clocks). Production should inject real freeze/extract/sign-off times.Double-handling minutes — a published synthetic table (
DEFAULT_HANDLING_MINUTES+ retouch minutes), not stopwatch data.Entity names, checksums, invoice amounts, and the mid-close “blocked” story (stale Xero extract, open intercompany rec, past-SLA exceptions, DSCR breach).
No ERP connector, OCR, workflow engine, or system of record. Straight- through rate here is exception-free invoices / invoices, not OCR capture rate.
Taxonomy: docs/ap-exceptions.md.
Gates and metrics: docs/five-day-close.md.
Copyright (c) 2026 Shyam Desigan (Cubiczan). All rights reserved.
Available Tools
14 toolsaudit_invoicesAudit vendor invoicesA
Run all anomaly rules over a set of invoices (and optional line items): duplicate numbers, entry lag, overdue-unpaid, amount outliers, unit-rate changes, new charge types, unexplained credits, and inconsistent tax. Header-level rules always run; item-level rules run only when line items are supplied.
Inputs: invoices (required), items, today, overdue_days, +4 more.
breakevenBreakeven index pricesA
Implied per-metal index prices at which a product's margin/MT hits zero (uniform cost/revenue multiple applied to current prices).
Inputs: product (required), config, prices.
classify_ap_exceptionsClassify AP exceptionsA
Classify vendor invoices into the AP exception taxonomy: duplicate invoice (reuses audit normalize/duplicate rules), missing/mismatched PO, missing receipt, wrong legal entity, tax review, and ownerless approval. Each exception includes confidence and a stable reason code. Invoices without match-context fields are only eligible for duplicate and inconsistent-tax reuse.
Inputs: invoices (required), items, today, include_audit_tax, +2 more.
close_readinessClose readinessA
Inventory ERP extracts, flag stale inputs, report reconciliation coverage, and compute hours-to-close from freeze (or earliest extract) to sign-off or the supplied now. Does not mutate state. Pass precomputed exceptions or invoices to include STP / double-handling.
Inputs: close (required).
compliance_certificateCompliance certificateA
Generate a full markdown covenant compliance certificate for a period. End-to-end: computes metrics, evaluates covenants, and renders the signable lender certificate in one call.
Inputs: period (required), trial_balance (required), config.
compute_covenant_metricsCompute covenant metricsB
Compute financial metrics used by loan covenants from a trial balance: revenue, net_income, ebitda, cash, current_ratio, dscr, debt_to_net_worth, total_debt, equity.
Inputs: trial_balance (required), config.
evaluate_contractsEvaluate contract structuresA
Evaluate all configured offtake/feedstock contract structures at spot. Supports grade_multiplier, discount_profit_share, collar, and assay_payables. Returns each contract's outputs and binding flags (collar floor/ceiling binding, profit-share triggered).
Inputs: config, prices.
evaluate_covenantsEvaluate covenantsB
Test computed metrics against covenant thresholds. Each result reports the metric value, operator, threshold, compliant flag, and percentage headroom to the threshold.
Inputs: metrics (required), config.
five_day_closeFive-day close workflowB
Run the six-gate five-day close reference: source freeze, subledger cutoffs, reconciliation queue, evidence bundle, exception SLA, and controller sign-off. Classifies AP exceptions when invoices are supplied, optionally flashes covenants, and returns operator metrics (straight-through rate, double-handling minutes, stale-input rate, hours-to-close).
Inputs: close (required).
normalize_invoice_numberNormalize invoice numberA
Normalize an invoice number for duplicate detection: strips punctuation, uppercases, and drops common prefixes so 'INV123', '#INV123', and 'NV123' collide to the same canonical form.
Inputs: number (required).
parse_trial_balanceParse trial balanceA
Flatten a Xero Reports/TrialBalance payload into netted section balances (debit positive for assets/expenses, credit positive for revenue/liabilities/equity). Returns a dict keyed by section, each mapping account name -> balance.
Inputs: report (required).
price_sensitivityPrice sensitivity gridB
Margin-per-tonne sensitivity for one product under price shocks: an 'all metals' row plus one row per metal, showing margin/MT under each configured shock (default -25%/-10%/+10%/+25%).
Inputs: product (required), config, prices.
product_marginsProduct margins per tonneB
Compute per-product revenue, cost, and margin per metric tonne. Revenue/MT = sum over metals of (assay% x payable% x index price), marked to market against inventory. Returns one record per product with metal contributions and inventory valuation.
Inputs: config, prices.
uipath_handoffUiPath handoffB
Accept a UiPath payload and route it to the matching deterministic engine: invoice audit, covenant certificate, contract evaluation, AP exception classification, or five-day close.
Inputs: kind (required), close, items, config, +11 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 14 tools
Tools cluster around distinct sub-domains (margins, covenants, invoices, close) with clear delineation in descriptions. Some overlap exists (e.g., product_margins vs price_sensitivity, evaluate_covenants vs compliance_certificate), but each tool's scope is explicit enough to avoid misselection.
All names are snake_case and mostly readable, but verb usage is inconsistent: many start with a verb (compute_covenant_metrics, evaluate_covenants, audit_invoices) while others start with a noun (product_margins, breakeven, compliance_certificate, close_readiness). This mixed convention is understandable but not uniformly predictable.
14 tools sit within the ideal 3-15 range and cover multiple finance engines without feeling bloated. Each tool has a distinct purpose, and the breadth of domains (margins, covenants, invoices, close, contracts) justifies the count, though it edges toward the upper bound for such a server.
The tool surface covers major workflows end-to-end: margin analysis (compute, sensitivity, breakeven), covenant handling (metrics, evaluation, certificate), invoice processing (audit, normalization, AP classification), close execution (readiness, five-day), contract evaluation, and trial balance parsing. Minor gaps exist (e.g., no tool to reference available products or list covenant definitions), but for an analytics engine the coverage is strong.
Related MCP Connectors
Connect AI agents to financial institution origination, analytics, and compliance workflows.
Primary-source SEC filing intelligence and financial/disclosure reconciliation for AI agents.
A structured financial modeling layer for AI agents. Build, version, and audit financial models without drift, then export to Excel, from Claude or any MCP client. Learn more: https://layerz.cc/for-agents
Paid deterministic data-quality and execution-verification tools for AI agents.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to perform financial analysis, budget forecasting, compliance checks, expense categorization, and risk assessment, returning structured JSON with audit-ready governance receipts.5102 npm1Business Source 1.1
- AlicenseCqualityDmaintenanceProvides deterministic data parsing and enrichment for AI agents, including bank statements, trade history, EDI, PDFs to structured markdown, and atomic enrichment for amounts, dates, and addresses, with strict schema enforcement to prevent hallucinations.3744 npm2ISC
- FlicenseBqualityBmaintenanceEnables AI assistants to perform financial reconciliation with a deterministic proof engine: intake files, match transactions, verify proofs, resolve exceptions, and sign off on balanced journals under the user's authority.21-
- AlicenseNot gradedqualityCmaintenanceEnables LLMs to query a synthetic general ledger and trial balance through read-only tools for account lookups, GL drill-down, variance analysis, and naive forecasting, with every answer cited to specific transactions or periods.66 npmMIT