Jiheng (玑衡): an exact computation layer for AI agents over MCP. Fractions, radicals, symbolic math, statistics, finance, units, dates, parallel shards.
pip install jiheng-mcp==0.3.4 Copy PIP instructions
Fractions stay fractions. Radicals stay radicals. Nothing silently rounds.
LLMs are great at reasoning and bad at arithmetic. One silently rounded number can propagate into a price, a report, or a trade. Jiheng does one job: return the exact value, or tell you clearly why it cannot.
Named after the ancient Chinese astronomical instrument xuanji yuheng — measurement has to be exact, and so does computation. Ships as an MCP server (jiheng-mcp) and a DSH plugin.
Different tools optimize for different jobs. Jiheng is built for one specific use case: an AI agent that needs a fast, exact, local calculator with a clean tool interface.
Jiheng is a computation layer, not a data layer. It does not open database connections, fetch web pages, or read files. It computes on numbers you already have. Data access belongs to dedicated MCP tools; compose them:
DB MCP: SELECT month, revenue FROM finance ↓ [120000, 135000, 149000, 162000] ↓ Jiheng: cagr(162000, 120000, 3) → 0.105... Jiheng: mean([...]) → 141500 Jiheng: npv(0.08, [...], 1) → discounted value Why Jiheng does not embed a database client:
If you need read-only SQLite / DuckDB / CSV access, use a dedicated data tool or MCP server, then pass the numbers to Jiheng.
# macOS / Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows PowerShell irm https://astral.sh/uv/install.ps1 | iex 2. Let your client launch Jiheng
Add this to your MCP client config (Claude Desktop, Cursor, Codex, ...):
{ "mcpServers": { "jiheng": { "command": "uvx", "args": ["jiheng-mcp"] } } } uvx downloads jiheng-mcp on first launch, then uses the local cache.
Use calc to compute 1/3 + 1/6 Use calc to compute mean([12,15,9,22]) Use calc to compute npv(0.08, [623,644,431,286], 1) Use calc to compute sqrt(2)*sqrt(2) Other install options Method Command PyPI (pip) pip install jiheng-mcp Local checkout uvx --from ./dsh-calc jiheng-mcp From git uvx --from git+https://github.com/CQQOOQ123/jiheng jiheng-mcp DSH plugin plugin_manager install_bundle target="D:\path\to\dsh-calc" plugin_manager set_bundle target="@local/jiheng" enabled=true Run the MCP server directly (debugging) cd dsh-calc python -u mcp_server.py # JSON-RPC over stdio Tool arguments { "expr": "final expression (optional when steps are given)", "steps": [{"name": "d1", "expr": "..."}, {"name": "C", "expr": "..."}], "defs": {"const": {"k": 1.05}, "fn": {"f": {"p": ["x"], "e": "x^2"}}} } Returns content[0].text (decimal-first, with exact form). On errors, isError: true with a correctable hint.
calc(expr="1/3 + 1/6") → 1/2 calc(expr="sqrt(2)*sqrt(2)") → 2 calc(expr="mean([12,15,9,22])") → 14.5 calc(expr="loan_pmt(1000000, 0.049, 20)") → monthly payment calc(expr="black_scholes_call(115,113,1,0.05,0.30)") calc(expr="npv(0.08, [623,644,431,286], 1)") → start=1: first cash flow at year-end calc(expr="functions()") → all function names calc(expr="help(\"norm_cdf\")") → norm_cdf(x, mu, sigma) — normal CDF Multi-step in one call:
{ "steps": [ {"name": "d1", "expr": "(ln(115/113)+(0.05+0.3^2/2)*1)/(0.3*sqrt(1))"}, {"name": "d2", "expr": "d1-0.3*sqrt(1)"}, {"name": "C", "expr": "115*norm_cdf(d1)-113*exp(-0.05)*norm_cdf(d2)"} ] } N(expr, digits) is numeric evaluation, not the normal CDF; use norm_cdf(x).
See AI-USAGE.md for the full contract (60+ functions).
Settings → Calculator → Limits (stored in /settings.json):
workers: 1 # 1..maxWorkers, or auto maxWorkers: 8 # hard cap 16; ~52 MB each auto: start with 1 and grow when busy Settings page shows running/ready counts; changes apply immediately Routes: GET/POST /calc/workers, POST /calc/batch (1..200 expressions in parallel) Workers send {"ready":true} on startup; resize waits for all to be ready Environment variables Variable Default Meaning DSH_CALC_PYTHON auto-detect worker interpreter DSH_CALC_HOME ./.calc or ~/.calc settings/packs directory DSH_CALC_TIMEOUT_MS 8000 per-evaluation timeout DSH_CALC_DEBUG empty forward worker stderr DSH_CALC_POLICY empty override policy DSH_CALC_BUILTIN_PACKS bundled packs/ built-in packs directory Architecture DSH Host (Node, resident) └─ index.js ── registers calc / calc_shard tools │ spawn 1..N workers ▼ worker.py (resident, JSON-lines protocol, ~3ms/eval) └─ calc_core.py AST whitelist + Fraction + SymPy └─ packs/*.py hot-reloadable capability packs MCP client ──stdio JSON-RPC──▶ mcp_server.py ──▶ calc_core.py + packs/ Resident worker avoids 250–800ms Python startup per call No eval: AST whitelist only Exact first: Fraction fast path; SymPy only for radicals/π/transcendentals Precision contract Arithmetic / integer powers / percentages / statistics → exact rationals Fractions, radicals, constants stay symbolic, plus a decimal d Simplifiable transcendentals are simplified (sin(pi/6)=1/2, log(1000,10)=3) Oversized exact fractions degrade to decimals with exact=false Never silently round; every approximation is flagged Error protocol {"e":"ValueError","msg":"unknown function 'norm_cdf'... did you mean ..."} {"e":"ValueError","msg":"invalid date '2026-02-30': 2026-02 has 28 days ... Do not roll over."} {"e":"ValueError","msg":"dimension mismatch: GB (data) vs kg (mass)"} {"e":"ValueError","msg":"not an expression (hint: multiple statements are not supported ...)"} HTTP routes (DSH plugin) /calc/status — version, policy, registration, worker/ready counts POST /calc/policy — {policy, customRules} GET/POST /calc/limits — limits; {"reset":true} restores defaults GET/POST /calc/workers — worker pool POST /calc/batch — {exprs:[...]} evaluated in parallel GET/POST /calc/packs — formula/capability packs Capability packs packs/*.py (or .calc/plugins/*.py):
NAME = "stats" def register(reg): reg.func("corr", ["x", "y"], corr_impl, doc="Pearson correlation") Pure functions, no IO/state, exact values in/out | Pack | Provides | |---|---| | stats | correlation, covariance, dot product, linear regression | | finance | NPV, annuities, IRR, bonds, Black-Scholes | | calculus | integrate / limit / taylor | | calculus2 | nintegrate / summation | | distributions | normal / t / chi-square pdf, cdf, quantiles | | linalg | determinant, inverse, eigenvalues, linear solve, matmul | | ode | first-order ODE dsolve | | special | gamma, erf, Bessel, factorial, binomial, beta, zeta | | strategy | integral checks, integration by parts, partial fractions, trig simplification | | units | unit conversion/mul/div/pow, temperature | | dates | date differences, date arithmetic, weekday | | currency | currency conversion | | percent | share, YoY, tax-inclusive/exclusive, discount, growth multiple | | engineering | stress, strain, beam deflection, bending stress, heat flux, thermal resistance | | templates | quotes, tax, discounts, margin, markup, remaining principal, wastage | | templates_hr | overtime pay, N+1 compensation, income tax, social insurance base | | templates_logistics | volumetric weight, chargeable weight, shipping cost | | templates_manufacturing | yield, OEE, material cost, labor cost | | templates_retail | double discount, rebate, average ticket, sell-through rate | 19 capability packs, bundled and hot-reloaded.
calc_shard(expr="x*exp(x)", var="x", from=0, to=1, shards=4, mode="integrate", op="sum") → sum(nintegrate) = 1 mode: integrate / sum; op: sum / mean / max / min Only for decomposable problems (interval integrals, range sums, parameter scans) Tests & benchmark python test_cases.py # 63: precision/stats/semantics/errors/security python test_packs.py # 93: capability packs python test_worker.py # 12: worker protocol/hot reload/ready python test_mcp.py # 6: MCP smoke node test_client_contract.mjs # 8: client contract node test_routes.mjs http://127.0.0.1:3379 # 26: HTTP routes Benchmark (1000 mixed tasks, deepseek-v4-flash, natural usage): 97.6% (976/1000).
Q: Is std sample or population? A: std/std_pop/var/var_pop are population; std_sample/var_sample are sample. sharpe, zscore and cov use the sample convention internally (ddof=1).
Q: Why is N(...) not the normal CDF? A: N(expr, digits) is numeric evaluation; use norm_cdf(x).
Q: Why is the first npv cash flow not discounted? A: Default start=0 (flows[0] at t=0); use npv(rate, flows, 1) for year-end flows.
Q: What happens with an invalid date? A: A clear error (e.g. 2026-02-30), never normalized to March 2.
Q: What is api retries exhausted? A: The model API failed after 6 retries (rate limit/network); not a calculator error.
uv build --directory dsh-calc # dist/jiheng_mcp-0.3.4-py3-none-any.whl # dist/jiheng_mcp-0.3.4.tar.gz Docker:
docker build -t jiheng-mcp dsh-calc docker run -i --rm jiheng-mcp Version & license Version: 0.3.4 MCP package: jiheng-mcp on PyPI DSH plugin id: @local/jiheng License: MIT (see LICENSE) Project links Data verified by PyPI on Nov 4, 2026 Data provided by the project maintainers, verified at the time the release was uploaded to PyPI. Homepage Issues Repository Key dates PyPI data Data sourced directly from PyPI's database. Released: Nov 4, 2026 Newer release available (0.3.9) 1 maintainer PyPI data Data sourced directly from PyPI's database. wow-qaq GitHub Statistics Data verified by PyPI on Nov 4, 2026 The GitHub source repository was provided by the project maintainers and verified by PyPI at the time of upload. Stars, forks, and open issues/PRs are derived from that repository and have not been independently verified. Repository Stars: Forks: Open issues: Open PRs: Provenance Data verified by PyPI on Nov 4, 2026 Data provided by the project maintainers and verified by PyPI at the time of upload. Full provenance
All 2 files in this release have provenance metadata.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.
All 2 files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




