precisioncalc-mcp
The PrecisionCalc MCP server provides high-precision, deterministic business, finance, and operational calculations for LLM agents using Python's Decimal module. Capabilities include:
Business & SaaS Metrics: Compute 14 key metrics (LTV, CAC, payback period, churn, MRR growth, NRR, GRR, Rule of 40, magic number, etc.).
Currency Conversion: Convert between 9 major currencies (USD, EUR, GBP, JPY, CAD, AUD, CHF, CNY, INR) using live/historical ECB rates with automatic fallback.
Business Day Arithmetic: Add/subtract, count, or find next/previous business days; supports weekends and holidays for US, UK, EU, any ISO country, plus custom holidays.
Compound Growth: Future value, present value, CAGR with daily, weekly, monthly, quarterly, semiannual, annual, and continuous compounding.
Net Present Value & IRR: NPV of cashflows; IRR solved via Newton's method with bisection fallback.
Loan Amortization: Monthly payment, total interest, payoff period; optional extra payments and full amortization schedule.
Depreciation Schedules: Straight-line, declining-balance, sum-of-years-digits methods.
Batch Calculations: Run up to 100 calculations in a single request; failures are isolated, not aborting the entire batch.
Discovery & Health: List all metrics with parameters and check server status/version/capabilities.
Precision & Output: Decimal arithmetic with 50 significant digits; results returned as strings to avoid floating-point errors; every response includes a structured JSON envelope with formula, inputs, unit, and notes; errors are returned as structured objects, never raised as exceptions.
Production Features: Optional API key authentication, token-bucket rate limiting, structured JSON logging, and OpenTelemetry tracing.
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., "@precisioncalc-mcp Calculate the LTV with ARPU $100, margin 80%, churn 5%"
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.
PrecisionCalc MCP
A deterministic Model Context Protocol (MCP) server that gives LLM agents reliable, high-precision business, finance, and operational calculations.
LLMs routinely lose precision or hallucinate on multi-step financial formulas,
currency conversions, business-day logic, and growth math. PrecisionCalc offloads
that work to exact, transparent tools. Every monetary/financial value is computed
with Python's decimal module (never floats), and every result is returned in
a consistent, agent-parseable JSON envelope that includes the exact value, a
human-readable value, the formula applied, the inputs used, the unit, and
any assumptions/warnings.
v2 highlights: live + historical FX (ECB), 14 SaaS metrics, NPV/IRR, loan amortization, depreciation, a
batch_calculatetool, per-country holidays, API-key auth + rate limiting + usage metering on the HTTP transport, structured JSON logging, optional OpenTelemetry tracing, and property-based tests.
π Live hosted server (free, no install)
A public remote MCP server runs on Cloudflare's edge β point any Streamable-HTTP MCP client at it:
https://precisioncalc-mcp.pages.dev/mcpRelated MCP server: @halfords-pro/calculator
Install via npm (stdio, no hosting)
Run the server locally over stdio with a single command β nothing to deploy:
npx -y precisioncalc-mcpClaude Desktop / any stdio MCP client (claude_desktop_config.json):
{ "mcpServers": { "precisioncalc": { "command": "npx", "args": ["-y", "precisioncalc-mcp"] } } }This is the same deterministic engine as the hosted server, running on your machine.
{ "mcpServers": { "precisioncalc": {
"type": "http", "url": "https://precisioncalc-mcp.pages.dev/mcp" } } }The edge build (worker-src/) is a Cloudflare Pages Function that mirrors the
Python engine using decimal.js β verified 17/17 exact output parity. Landing
page + docs: https://precisioncalc-mcp.pages.dev.
Plans (hosted endpoint)
Plan | Price | Daily calls | Live/historical FX |
|
Free (no key) | $0 | 15 / day (per IP) | β static only | β |
Starter | $12/mo | 5,000 / day | β | β |
Pro | $39/mo | 50,000 / day | β | β |
Checkout is Stripe (subscription). On success you get an API key instantly; send it as
X-API-Key: <key> (or Authorization: Bearer <key>). Manage/cancel at /portal.
When a limit is hit, tools return a structured status:"error" envelope with type,
usage, and an upgrade block containing checkout URLs β so an agent can surface the
paywall to the user and act on it. Self-host (below) for unlimited calls with your own keys.
Billing internals live in worker-src/billing.mjs (Stripe REST + Cloudflare KV for keys
and daily counters). Server env: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET,
PRICE_STARTER, PRICE_PRO, FREE_DAILY, STARTER_DAILY, PRO_DAILY, and a
PRECISIONCALC_KV namespace binding (see wrangler.toml).
Rebuild/redeploy the edge server:
npm install # decimal.js + esbuild
npm run deploy # bundles worker-src -> site/_worker.js and deploys to PagesWhat it does
11 tools, all returning a uniform structured response:
Tool | Purpose |
| 14 SaaS/business metrics (LTV, CAC, churn, MRR growth, NRR, GRR, Rule of 40, magic number, break-even, ...) |
| Convert 9 major currencies; static (offline) or live/historical ECB rates |
| Add/count business days, next/previous; US/UK/EU + any ISO country + custom holidays |
| Future value, present value, CAGR; 7 compounding frequencies incl. continuous |
| NPV / discounted cash flow of a cashflow series |
| IRR (Newton + bisection fallback) |
| Level-payment loan: payment, totals, full schedule, extra-payment payoff |
| straight-line / declining-balance / sum-of-years-digits schedules |
| Run many calculations in one request |
| Discovery: every metric with descriptions + required params |
| Server status, version, capabilities |
Consistent response envelope
Success:
{
"status": "success",
"value": "1600", // exact, full-precision (string for money/rates)
"formatted_value": "$1,600.00", // human-readable
"formula": "LTV = (ARPU * gross_margin) / churn_rate",
"inputs_used": { "arpu": "100", "gross_margin": "0.8", "churn_rate": "0.05" },
"unit": "USD",
"notes": ["LTV = (ARPU x gross_margin) / churn_rate.", "..."]
}Error (never raised across the tool boundary):
{
"status": "error",
"error": {
"type": "missing_parameter",
"message": "Missing required parameter 'churn_rate'.",
"hint": "Include 'churn_rate' in params. See list_metrics for the full schema."
}
}Project structure
precisioncalc-mcp/
βββ server.py # MCP server: tool definitions + transports
βββ security.py # API-key auth + token-bucket rate limit + metering (ASGI)
βββ observability.py # Structured JSON logging + optional OpenTelemetry
βββ requirements.txt / pyproject.toml
βββ Dockerfile / .dockerignore
βββ fly.toml / render.yaml # One-click hosting configs
βββ .env.example
βββ calculations/
β βββ _util.py # Decimal coercion, validation, formatting
β βββ metrics.py # 14 business/SaaS metrics + catalog
β βββ currency.py # FX: static + Frankfurter (live/historical) providers
β βββ business_days.py # Region-aware holidays (built-in + `holidays` lib)
β βββ growth.py # FV / PV / CAGR
β βββ finance.py # NPV / IRR / loan amortization / depreciation
βββ schemas/responses.py # Response envelope helpers
βββ examples/agent_example.py # End-to-end MCP client demo
βββ site/ # Static landing/docs page (Cloudflare Pages)
βββ tests/ # 49 unit tests + Hypothesis property testsRequirements
Python 3.11+ (developed/tested on 3.12)
Core:
mcp,python-dateutilRecommended:
uvicorn+starlette(HTTP transport),holidays(per-country calendars)Optional:
opentelemetry-sdk(tracing),pytest+hypothesis(tests)
The server auto-detects the SDK layout and works with mcp >= 2.0
(MCPServer), mcp 1.x (FastMCP), or the standalone fastmcp package.
Run it locally
cd precisioncalc-mcp
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt # or: pip install -e ".[all]"
# stdio transport (default; how MCP clients launch it)
python server.py # or: precisioncalc-mcp (console entrypoint)
# Streamable HTTP transport (endpoint: /mcp)
python server.py http
PRECISIONCALC_API_KEYS=key1,key2 PRECISIONCALC_FX_PROVIDER=frankfurter python server.py httpDemo + tests:
python examples/agent_example.py # live end-to-end over stdio
python tests/test_calculations.py # 28 core tests (no pytest needed)
python tests/test_v2.py # 17 v2 tests
python tests/test_properties.py # Hypothesis property tests
# or simply: pytest -qRegister with an MCP client (stdio)
{ "mcpServers": { "precisioncalc": {
"command": "python", "args": ["/absolute/path/to/precisioncalc-mcp/server.py"] } } }Deploy
Docker
docker build -t precisioncalc-mcp .
docker run --rm -p 8000:8000 -e PRECISIONCALC_API_KEYS=your-key precisioncalc-mcp
docker run --rm -i precisioncalc-mcp python server.py stdioFly.io
fly launch --no-deploy
fly secrets set PRECISIONCALC_API_KEYS=key1,key2
fly deployRender.com
Push to GitHub, then New + β Blueprint and point at the repo (render.yaml).
Set PRECISIONCALC_API_KEYS as a secret in the dashboard.
Configuration (env vars)
Var | Default | Purpose |
|
| HTTP bind |
| (empty) | Comma-separated keys. Empty = open mode (still metered/limited by IP) |
|
| Token-bucket limits |
|
| Usage-metrics endpoint |
|
|
|
|
| FX cache TTL / HTTP timeout (s) |
|
| Logging |
|
|
|
Tools & parameters
calculate_metric(metric, params, currency="USD")
Rates/margins are decimals (0.05 = 5%).
metric | params | unit |
|
| currency |
|
| currency |
|
| ratio |
|
| months |
|
| currency |
|
| percent |
|
| percent |
|
| percent |
|
| currency |
|
| units |
|
| percent |
|
| percent |
|
| percent |
|
| ratio |
currency_convert(amount, from_currency, to_currency, date=None, live=None)
USD, EUR, GBP, JPY, CAD, AUD, CHF, CNY, INR. date (YYYY-MM-DD) or live=true
uses live/historical ECB rates (frankfurter.app), with automatic static fallback
on any network failure. Returns rate, provider, is_live, and timestamps.
business_days(operation, start_date, days=None, end_date=None, region="US", custom_holidays=None)
operation: add_business_days | count_business_days (inclusive) | next_business_day |
previous_business_day. region: US | UK | EU | NONE, or any ISO country code
when the holidays package is installed (DE, FR, CA, AU, JP, IN, ...).
compound_growth(operation, rate, years, present_value, future_value, begin_value, end_value, compounding="annually", currency="USD")
operation: future_value | present_value | cagr.
compounding: daily | weekly | monthly | quarterly | semiannually | annually | continuous.
net_present_value(rate, cashflows, currency="USD")
NPV = Ξ£ CFβ/(1+rate)α΅. cashflows[0] = period 0 (usually the negative outlay).
internal_rate_of_return(cashflows, guess=0.1)
Per-period rate where NPV = 0. Requires a sign change in the cashflows.
loan_amortization(principal, annual_rate, term_months, extra_payment=0, currency="USD", include_schedule=false)
Returns monthly payment, months-to-payoff, total interest, total paid, and (optionally) the full month-by-month schedule.
depreciation(method, cost, salvage_value, useful_life_years, currency="USD")
method: straight_line | declining_balance | sum_of_years_digits. Returns the
full yearly schedule; book value converges to salvage_value.
batch_calculate(calls)
calls: list of {"tool": <name>, "arguments": {...}} (max 100). One item failing never
aborts the batch.
list_metrics() / health_check()
Discovery + status. No parameters.
Example MCP tool-call payloads
{ "name": "calculate_metric",
"arguments": { "metric": "rule_of_40", "params": { "growth_rate": 0.30, "profit_margin": 0.15 } } }{ "name": "currency_convert",
"arguments": { "amount": 5000, "from_currency": "EUR", "to_currency": "GBP", "date": "2024-01-15" } }{ "name": "net_present_value",
"arguments": { "rate": 0.10, "cashflows": [-10000, 3000, 4200, 6800] } }{ "name": "loan_amortization",
"arguments": { "principal": 250000, "annual_rate": 0.065, "term_months": 360, "include_schedule": false } }{ "name": "batch_calculate",
"arguments": { "calls": [
{ "tool": "internal_rate_of_return", "arguments": { "cashflows": [-10000, 3000, 4200, 6800] } },
{ "tool": "depreciation", "arguments": { "method": "declining_balance", "cost": 50000, "salvage_value": 5000, "useful_life_years": 5 } }
] } }Design decisions & assumptions
Decimal everywhere money/rates matter;
valueis serialized as a string to prevent float loss in JSON, with a separate prettyformatted_value. Precision = 50 sig figs.Rates/margins are decimals (
0.05= 5%), documented in every tool.FX:
staticUSD-based table (as_of2024-06-01) is the offline default;frankfurterprovider adds live + historical ECB rates with in-memory TTL cache and graceful static fallback.Business days: holidays computed per-year (floating US, Easter-based UK/EU);
countis inclusive;addaccepts negatives; custom holidays unioned; any ISO country viaholidayslib.IRR uses Newton's method with a bracketed bisection fallback; requires a sign change.
Errors never cross the tool boundary as exceptions β always
status:"error"with a machinetype+ actionablehint.HTTP hardening is opt-in via env: API keys, token-bucket rate limiting,
/metricsusage.SDK compatibility shim runs on
mcp>=2.0,mcp 1.x, or standalonefastmcpunchanged.
Monetization hooks
Auth β
PRECISIONCALC_API_KEYS; requests needX-API-KeyorAuthorization: Bearer.Rate limiting β per-key token bucket (per-IP in open mode); swap for Redis to scale.
Usage metering β in-memory counters exposed at
/metrics; the seam for per-key billing.FX provider β
calculations/currency.py::RateProvideris the drop-in point for a licensed feed.
Roadmap (post-v2)
Redis-backed rate limiting + billing-grade usage metering.
Persisted historical FX + more providers; multi-currency carry through metrics.
Bond pricing/yield, WACC, options (Black-Scholes), tax/VAT, unit conversions.
Prometheus exporter + Grafana dashboard alongside OTel traces.
Published PyPI package + Docker image on GHCR; hosted multi-tenant SaaS.
Available Tools
11 toolsbatch_calculateAInspect
Run many calculations in one request to cut agent round-trips.
Each item is {"tool": <name>, "arguments": {...}}. Results are returned in
order; a failure in one item never aborts the batch (its slot holds an error
envelope). Batchable tools: calculate_metric, currency_convert, business_days,
compound_growth, net_present_value, internal_rate_of_return, loan_amortization,
depreciation, list_metrics.
Args: calls: List of {"tool": str, "arguments": object} items (max 100).
Inputs: calls (required). Returns: object
business_daysAInspect
Business-day arithmetic honoring weekends and regional public holidays.
Operations: add_business_days (needs days, may be negative) | count_business_days (needs end_date, inclusive) | next_business_day | previous_business_day.
Regions: US, UK, EU, NONE (weekends only) are built in and offline. If the
optional holidays package is installed, ANY ISO country code also works
(DE, FR, CA, AU, JP, IN, ...). custom_holidays (YYYY-MM-DD list) are added.
Args: operation: One of the four operations above. start_date: Anchor date, ISO YYYY-MM-DD. days: Business days to add (add_business_days; negative allowed). end_date: End date (count_business_days), ISO. region: US | UK | EU | NONE | ISO country code. custom_holidays: Optional extra holiday dates (YYYY-MM-DD).
Inputs: operation (required), start_date (required), days, region, +2 more. Returns: object
calculate_metricAInspect
Compute a business / SaaS / finance metric with exact decimal precision.
Supported metric values -> params keys (rates/margins are decimals,
0.05 = 5%):
ltv -> arpu, churn_rate, [gross_margin=1]
cac -> total_spend, new_customers
ltv_cac_ratio -> ltv, cac
payback_period_months-> cac, monthly_revenue_per_customer, [gross_margin=1]
contribution_margin -> revenue, variable_costs
gross_margin -> revenue, cogs
churn_rate -> customers_lost, customers_at_start
mrr_growth_rate -> beginning_mrr, ending_mrr
arr -> mrr
break_even_units -> fixed_costs, price_per_unit, variable_cost_per_unit
nrr -> starting_mrr, expansion_mrr, contraction_mrr, churned_mrr
grr -> starting_mrr, contraction_mrr, churned_mrr
rule_of_40 -> growth_rate, profit_margin
magic_number -> current_quarter_revenue, prior_quarter_revenue, prior_quarter_sm_spend
Call list_metrics for full schemas.
Args: metric: Name of the metric to compute. params: Object of named numeric parameters for the chosen metric. currency: ISO currency code used to format monetary results.
Inputs: metric (required), params (required), currency. Returns: object
compound_growthAInspect
Compound-interest / growth math (future value, present value, or CAGR).
Operations: future_value (needs rate, years, present_value) | present_value
(needs rate, years, future_value) | cagr (needs begin_value, end_value, years).
rate is an annual decimal (0.08 = 8%). compounding: daily | weekly |
monthly | quarterly | semiannually | annually | continuous.
Inputs: operation (required), rate, years, currency, +5 more. Returns: object
currency_convertAInspect
Convert an amount between major currencies with Decimal precision.
Supported: USD, EUR, GBP, JPY, CAD, AUD, CHF, CNY, INR. Returns the converted amount, exact cross-rate, provider, and timestamps.
Rates: static offline table by default. A date (YYYY-MM-DD) or live=true
uses live/historical ECB rates (frankfurter.app); on any network failure the
server falls back to static rates with a warning note.
Args:
amount: Amount in from_currency (>= 0).
from_currency: Source ISO 4217 code.
to_currency: Target ISO 4217 code.
date: Optional historical date (YYYY-MM-DD) -> live provider.
live: Force live (true) or static (false); null = auto.
Inputs: amount (required), to_currency (required), from_currency (required), date, +1 more. Returns: object
depreciationAInspect
Asset depreciation schedule.
Methods: straight_line | declining_balance (double-declining) | sum_of_years_digits. Returns Year-1 depreciation plus the full yearly schedule (book value converges to salvage_value).
Args: method: Depreciation method (see above). cost: Initial asset cost. salvage_value: Residual value at end of life (<= cost). useful_life_years: Whole years (> 0). currency: ISO code for formatting.
Inputs: cost (required), method (required), salvage_value (required), useful_life_years (required), +1 more. Returns: object
health_checkAInspect
Return server health/status metadata (name, version, tools, capabilities).
Inputs: no named parameters. Returns: object
internal_rate_of_returnAInspect
Internal Rate of Return: the per-period rate where NPV == 0.
Solved with Newton's method + a bisection fallback. Requires at least one negative and one positive cashflow.
Args: cashflows: List of >= 2 numbers, e.g. [-10000, 3000, 4200, 6800]. guess: Optional starting rate for Newton's method (decimal).
Inputs: cashflows (required), guess. Returns: object
list_metricsAInspect
List every supported metric with description, required and optional params.
Inputs: no named parameters. Returns: object
loan_amortizationAInspect
Level-payment loan: monthly payment, total interest, payoff, and schedule.
payment = P * r / (1 - (1 + r)^-n), r = annual_rate/12, n = term_months.
Args: principal: Loan amount (> 0). annual_rate: Nominal annual rate as a decimal (0.06 = 6%). term_months: Number of monthly payments (> 0). extra_payment: Optional extra principal each month (shortens the term). currency: ISO code for formatting. include_schedule: If true, return the full month-by-month schedule.
Inputs: principal (required), annual_rate (required), term_months (required), currency, +2 more. Returns: object
net_present_valueAInspect
Net Present Value (discounted cash flow) of a periodic cashflow series.
NPV = sum(CF_t / (1 + rate)^t), t = 0..n. Index 0 is period 0 (typically the negative initial investment).
Args: rate: Discount rate per period as a decimal (0.10 = 10%). cashflows: List of >= 2 numbers, e.g. [-10000, 3000, 4200, 6800]. currency: ISO code for formatting.
Inputs: rate (required), cashflows (required), currency. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 11 tools
Each tool addresses a distinct calculation domain: metric computation, currency conversion, business day arithmetic, compound growth, NPV/IRR, amortization, depreciation, batching, and health. No two tools appear to perform the same function.
All names use lowercase with underscores creating a predictable style, though some follow verb_noun (calculate_metric) while others are noun phrases (business_days, net_present_value). The convention is consistent enough that an agent can infer tool purposes.
With 11 tools, the set is well-scoped for a financial calculation server. Each tool represents a meaningful capability, and the batch_calculate tool efficiently aggregates without inflating the surface.
The server covers a comprehensive range of financial calculations: business metrics, currency conversion, time arithmetic, time-value-of-money, loans, and depreciation. The inclusion of batch_calculate and health_check rounds out operational needs. No major gaps are evident.
Maintenance
Related MCP Connectors
MCP server for Financial Modeling Prep API with 250+ financial data tools
Headless API-first double-entry accounting & bookkeeping engine. 84 MCP tools over HTTP.
Production MCP server for US equity and options intelligence: real-time IV radar, Monte Carlo simulation, options pressure, strategy backtesting, AI prediction, pre-trade risk analysis, and automated stock research reports.
Hosted MCP server for AWS cloud spend: service breakdowns, anomalies, savings and forecasts.
Related MCP Servers
- AlicenseAqualityDmaintenanceAn MCP server and CLI providing business, financial, and tax calculations including math expressions, income tax estimates, loan amortization, depreciation, and more.102MIT
- FlicenseAqualityDmaintenanceProvides precise decimal arithmetic and Excel-style rounding for accounting and tax calculations via MCP protocol.13 npm-
- AlicenseNot gradedqualityCmaintenanceMCP server providing deterministic accounting tools for AI agents, including bank statement parsing, document classification, money math, and webhook verification.2Apache 2.0
- AlicenseAqualityDmaintenanceMCP server for deterministic numeric verification and spreadsheet auditing. Enables AI agents to verify math/finance claims, audit rows, and evaluate covenant rules with signed, independently checkable receipts.4MIT