Repository navigation
Releases
Pycodemath 0.5.2
Listing in the official MCP Registry.
Added
pycodemath mcpstarts the MCP server over stdio, so it runs straight from
PyPI:uvx --with "mcp>=1.0,<2.0" pycodemath mcp.pycodemath-mcpand
python -m pycodemath.cli.mcp_serverstill work.server.jsonfor the MCP Registry (io.github.cybersora9/pycodemath) and the
ownership marker in README.md that the registry checks on PyPI.
Pycodemath 0.5.1
Fixes from a hands-on test session against 0.5.0 (49 CLI calls), plus a
first-run intro and commands for finding your way around.
Added
sum p(k)*binomial(n,k) for k from a to nwithpa polynomial ink: closed
form via Stirling numbers of the second kind,Σ_k k^m C(n,k) = Σ_j S(m,j) n!/(n-j)! 2^(n-j)(e.g.sum k^3*binomial(n,k) for k from 0 to n=
2**(n - 3)*n**2*(n + 3)). Proved by that identity; the result is also checked
against the brute-force sum before it is returned (tests: n = 0..20).- Definite integrals of the Bose–Einstein / Fermi–Dirac family on (0, oo):
∫ x^(s-1)/(e^(cx) - 1) = Γ(s)ζ(s)/c^s(s > 1) and∫ x^(s-1)/(e^(cx) + 1) = (1-2^(1-s))Γ(s)ζ(s)/c^s(s > 0), used where SymPy finds no closed form;
convergence is proved and the value cross-checked against the independent
quadrature as for every other definite integral (integrate x^3/(exp(x)-1) dx from 0 to oo=pi**4/15, VERIFIED, was a value without a closed form). - First run and way-finding.
pycodemath intro(alsopython -m pycodemath introandintroin the REPL): an 80-column header box with the
logo (rasterized fromassets/pycodemath-sygnet.svgbyscripts/gen_logo.py:
36 columns, stroke 12, transparent half blocks), the name, version, tagline
"Checks the math in your code.", the number of commands and API functions
(counted at run time), then one live demo (an off-by-one loop read as a
formula, REFUTED with the executed call, fixed, VERIFIED; every number comes
fromcheck_codeat run time) and a capability map of eight areas, each with
a runnable command. Animated only on a TTY, under 6 s;--static,
PYCODEMATH_NO_ANIM=1or a pipe print the final frame (30 lines, 80
columns). Truecolor, a 256-colour fallback mapped to the nearest palette
entries, monochrome underNO_COLORor off a TTY. Flags:--static,
--no-logo,--once. - The intro plays by itself once per installed version: on the first run of
pycodemath/python -m pycodemathwith a TTY stdout after installing or
upgrading, before the command's own output. Never off a TTY, never in the MCP
server, never withPYCODEMATH_NO_INTRO=1. The shown version is kept in
intro-shownin the user cache directory.pycodemath intro --onceshows it
only if this version's intro has not been shown yet, else prints nothing and
exits 0. pycodemath commands(every command by topic),pycodemath help <topic>
(the REPL help, cut by topic: solve, calculus, verify, code, numbers, money,
units, geometry, ode, stats, start),pycodemath examples <topic>(3-5
runnable examples each; a test runs every one) andpycodemath tour(five
short live demos; Enter = next, q = quit; sequential off a TTY).- MCP tool
intro: the logo as plain text, the tagline and the capability map
as text and data (no ANSI, no engine call). The existing tools are unchanged. assets/intro.svg, recorded from the real command by
scripts/record_intro_svg.py, in a new "First run" section of both READMEs.
Changed
money loan ... for N yearsis now a duration paid MONTHLY (N×12
instalments):money loan 300000 PLN at 7.2% for 25 yearsgives 300
instalments of 2158.77 PLN. 0.5.0 readyearsas N annual instalments
(26208.67 PLN) — what nobody taking a mortgage means. Annual instalments are
asked for explicitly:... for 25 years yearly(alsoannual,annually);
yearlywith a duration in months is refused. The answer now names the
schedule (300 monthly instalments: payment ...). Same on the CLI/REPL and
MCPmath_eval(whose description says so); the Python API
(amortization_schedule,annuity_payment) was never ambiguous — it takes
periodsandperiods_per_year— and is unchanged.money interestkeeps its meaning (the unit is the compounding period:
for 10 yearscompounds yearly,for 12 monthsmonthly) and the answer now
says so (compounded yearly, 10 years).dsolvewithout a closed form names the CLI command in its hint —solve it numerically instead (ode <expr> for y(t) from <t0> to <t1> at <y0>)— instead
of the Python functionsolve_ode_num, assolvealready namesroot.
routestays"ode".sum(...),Sum(...),summation(...),integrate(...),Integral(...)and
integral(...)inside an expression (verify sum(k, (k,0,n)) == ...,evalf integrate(x, (x,0,1)) 60) are refused with a pointer to thesum ... for k from .. to ../integrate ... dx from .. to ..commands instead of "write
sum*(...) if a product is meant".- The interactive REPL greets with a 2-line banner (the text mark
∫>_,
version, where to start). One-shot commands still print no banner off a TTY
— pinned by a test.
Fixed
sum p(k)*binomial(n,k)answers in about 2 s instead of about 95 s for
k^5: the proved rule now runs before SymPy, which used to grind until it
gave up.- The time budget no longer fires into cleanup code. When a deadline passed
while the thread was in a__del__, a gc callback or aweakref.finalize
finalizer, Python printedException ignored in ..., cut the cleanup short
and dropped the interrupt. The watchdog now waits for the cleanup to finish
and interrupts 50 ms later. This was also a flaky CI failure. solveandcertify solvetake an equation:solve x^2 = 4 for xand
solve x^2-5*x+6 == 0 for xare solved aslhs - rhs.==used to compare
the two sides as Python objects and printed "(no solutions)". An=anywhere
else in an expression is now aParseErrorthat points tosolve/verify.- Strict mode no longer guesses on
2abwhenaandbare also variables of
the same expression:verify (a+b)^2 == a^2 + 2ab + b^2came back REFUTED
(it readabas one variable). It is now aParseErrorasking fora*bor a
rename. Names likespeed,alphaor a loneabstill parse as before.
Pycodemath 0.5.0 — checks the math in your code
Pycodemath now checks the math inside your code. Point it at a function and a formula: you get a proof, or the exact input that breaks it. No guessing, no random samples. 🎯
>>> from pycodemath import check_code
>>> r = check_code(src, "n*(n+1)/2") # the classic off-by-one
>>> r.verdict, r.counterexample.call
('refuted', 'sum_to(n=1)')✨ What's new
- 🔍 Code ↔ formula —
check_codeproves a function equals its formula, or hands back the call that breaks it, really executed.--emit-testwrites the pytest that pins it. - 🎯 Float accuracy, with proof —
stability/improve: how many bits float64 loses, where, and a rewrite that is proved equal and measured better. - 💥 Overflow —
ranges/maxsafe: int8…uint64, float16, bfloat16, float32, float64. The 2006 binary-search bug, caught and fixed with a proof. - 💰 Money — no lost cents: exact splits, rounding modes, VAT, loans, IRR.
- 📐 Units, geometry, loops — dimension checks with witnesses, rotation conventions, predicates that never lie, loop counts and recurrences.
- 🧹
pycodemath-lint— a linter that comes with witnesses (ruff-style exit codes), plus a pytest plugin and pre-commit hook. - 🧾 Certificates — every answer ends with a re-runnable
certificate:;recheckreproduces it from the file alone. - 🔒 Strict parser —
xyis one variable, unknown words get a "did you mean…", no more silent product of letters. - 🤖 MCP server — 8 tools for AI agents,
execute=Falseby default for foreign code.
✅ By the numbers
- 2914 tests, Python 3.11 → 3.14, mypy clean
- verify benchmark: 105 / 105 mistakes caught, 0 false alarms
- real model solutions: 0 false alarms on 122 correct ones
pip install pycodemath==0.5.0
python -m pycodemath "verify code sums.py:sum_to == n*(n+1)/2 --emit-test"📦 PyPI: https://pypi.org/project/pycodemath/0.5.0/ · 📝 Full notes: CHANGELOG · 🇵🇱 README.pl
Pycodemath 0.4.0 — a verifier: VERIFIED, REFUTED or UNDECIDED
pip install -U pycodemath · PyPI
Pycodemath now checks math, not just computes it: a verifier that answers
VERIFIED, REFUTED (with a counterexample you can re-check yourself) or
UNDECIDED — and never promotes "agrees numerically" to "proved".
Added
pycodemath.verify.check_equal(a, b)returns aVerdict
(VERIFIED/REFUTED/UNDECIDED, the method used, a counterexample
and a one-line reason). Symbolic proof first; then deterministic
high-precision sampling that avoids singularities. A counterexample is
re-checked at higher precision before it is reported, so rounding noise is
never called a refutation. Domain traps are caught:sqrt(x^2)vsx
is REFUTED at a negative point, not "simplified" into equality.certify(...)— engine results checked by an independent route:
integrals by differentiating back, roots by substitution plus a
completeness check, derivatives by finite differences, limits by
two-sided numeric sequences, ODE solutions by substitution, numeric
integrals by a second, independent quadrature (certify_integrate,
certify_diff,certify_solve,certify_limit,certify_dsolve,
certify_nintegrate). Existing result types are unchanged.check_steps(...)— checks a derivation step by step: per-step
verdicts, the index of the first wrong step and a counterexample. Equation
chains are compared as solution sets, with a warning when a step adds roots
(squaring both sides) or loses them (dividing by an expression that can be
zero).- REPL and MCP surface:
verify <a> == <b>,verify steps ...and
certify <command>in the REPL; amath_verifyMCP tool next to
math_eval, returningstructuredContentwith the same rules (failure is
anerrorfield, never an exception). isolated(fn, *args, budget=...)— a hard time limit. The in-process
time_budgetcannot stop one long C call that holds the GIL
(7**(10**7)under a 2 s budget ran 7.9–8.7 s).isolatedruns the call
in a warm worker process and kills it at budget + 0.5 s (same case: 2.5 s),
raising the newIsolationError. Opt-in (~0.4 ms per call); the fast path
oftime_budgetis unchanged.- Benchmarks, with their denominators (
python -m pycodemath.bench.verify_bench,python -m pycodemath.bench.real_bench):- Synthetic: 210 generated derivations, half with an injected typical
model error — 105/105 errors caught, 0 false positives. These are
synthetic, and the verifier was fixed against misses found on this set. - Real model errors (PRM800K, MIT-licensed sample): the verifier can
extract a checkable claim from 9.5% of steps; it pinpoints the labelled
first wrong step in 24 of 378 flawed solutions (6.3%) and raised 0 false
alarms on 122 correct ones. Low recall, zero false alarms: when it says
a step is wrong, it shows why.
- Synthetic: 210 generated derivations, half with an injected typical
hypothesisjoins thedevextra (property-based tests of the verifier).
Changed
- A call to an unknown function is now a
ParseError("unknown
function"), not a product of symbols. Previouslyzeta(2)parsed as
2*zeta, which letverify zeta(2) == pi^2/6"refute" a true identity. - A bare function name (
sin,log,(sqrt)) and stray brackets (),
x)) raiseParseErrorinstead of a rawTypeError/IndexError. Expr.to_source()round-trip contract is now stated and tested as
mathematical equivalence:parse(e.to_source())is always equivalent to
e(or the parser refuses), never a different expression; structural
==is not promised, because SymPy re-distributes constants on parse.
Fixed
Expr.evalf()and compiled evaluation no longer leak a bareTypeError;
nestedzoobecomes aDomainError.time_budget: an interrupt could land after the guarded block had
exited and escape as an internal_Deadline; a nested budget poisoned the
outer one. Both fixed (Windows reproduced it most).- A huge literal such as
2^1e10no longer hangs before the budget is armed. certify_solveaccepts real roots of a cubic in the casus irreducibilis
(an imaginary part at 1-bit precision is treated as zero only when the
real part has full precision); quartics take candidates fromnroots
instead of spending the whole budget on Ferrari's formula; decimal
exponents (5^7.5vssqrt(5^15)) no longer yield a false REFUTED.- The MCP server imports on Python 3.11 again.
- Python 3.13: the time-budget interrupt no longer escapes a
with time_budget(...)block. CPython 3.13 (only — gh-139622, open) lets an
asynchronous exception skip every handler of the frame it is raised in, so
a block around code in the caller's own frame let the raw internal
interrupt out and kept re-injecting into whatever ran next (measured: 14 of
18 test runs on Linux 3.13, 5 of 6 on Windows 3.13, 0 on 3.12). On 3.13 the
watchdog now holds back while the interrupted frame sits inside a handler
and waits for a frame where nothing would be skipped; engine calls are
interrupted as before. CI now runs 3.11–3.14.
Known limitations
check_equal("cosh(t1 - log(0))", ...)can raise a bareTypeError,
andtrigsimpa bareRecursionError;sqrt(2)^10^20can still hang in
the parser.solvecan miss periodic solutions;QuadratureResult.error_estimate
can under-estimate.isolatedis not yet wired into the MCP server or the REPL.time_budgeton its own stays best-effort (see 0.3.0 below);isolated
is the hard limit.
Pycodemath 0.3.0 — structured results, typed exceptions, MCP structuredContent
[0.3.0] - 2026-08-19
Every failure and every success now carries evidence an agent can branch on,
instead of a bare value or a string to pattern-match.
Added
- Typed exception hierarchy under
PycodemathError:ParseError,
DomainError,DivergenceError,StagnationError,NonConvergenceError.
A caller can catch the specific outcome instead of string-matching the
English message;except PycodemathErrorstill catches everything. - Structured solver results:
root_find,root_find_nd,minimizeand
minimize_ndtake a keyword-onlyfull_result=Trueand return a
SolveResult(value / iterations / residual / converged / status).
integrate_numlikewise returns aQuadratureResult(adds an
error_estimate) and gained an adaptivetolthat refines panels until the
estimate fits inside it, instead of always running a fixed 100-panel grid.
Default calls are unchanged, bit-identical to 0.2.0. convergedis now corroborated, not just "the tolerance test fired": a
vanishing gradient at a saddle or a maximum, or|f| < tolreached because
fdecayed rather than becausexis a root, no longer reports false
convergence.- A symbolic refusal taxonomy:
NoClosedFormError(the engine searched
and found nothing) vs.UnsupportedFormError(no method for this shape at
all) — so a caller knows whether to stop or re-ask numerically instead of
parsing English. - A time budget for symbolic calls:
pycodemath.time_budget(seconds)(a
context manager) and abudget <s>trailing REPL/MCP option bound how long
a symbolic call may run and raiseTimeBudgetErrorinstead of hanging a
tool call forever with no result. - REPL/MCP grammar reaches solver knobs the Python API already had:
trailingtol <t>/max_iter <k>options onmin/min_nd/
nintegrate, andbudget <s>on the symbolic commands. - The MCP surface carries the structured results:
math_evalreturns
structuredContent(text/solve/quadrature/errorfields) that
a client validates against the declared schema, not just prose text. A
raising call now always returns rather than throwing past the tool
boundary. py.typed+ packaging fixes: an externalmypynow actually sees the
package's types (previously silently fell back toAny), and every symbol
a public function returns (e.g.SolveResult) is importable from the
top-level package.
Fixed
- Security: matrix literals (
matrix/det/inv/eig/solve_system/
M/V) parsed user text with baresp.sympify(), so attribute access
evaluated (().__class__.__bases__reachesobject). Routed through the
same whitelist parser scalars already use. - Identifiers with a trailing digit (
q1,x2,v0,R1— a common
physics/engineering subscript convention) crashed the parser with a leaked
NameErrorinstead of a cleanParseError. Abs/sign/Min/Maxdid not differentiate on a plain
(assumption-free) symbol — silently wrong output fromdiff, and a raw
SymPy crash instead of aPycodemathErrorfrom anything that
differentiates internally (min,solve_nd, the stiff-ODE Jacobian).- A non-finite
tol(e.g.tol inf) certified an unmoved starting guess as
converged; tolerances are now validated finite. mcpdependency pinned to>=1.0,<2.0— the unbounded constraint let a
fresh install pick upmcp2.0.0, which removed an API the MCP test
helper and integration path both relied on.
Pycodemath 0.2.0 — first public release
Token-efficient exact math for AI agents — one short command in, one exact SymPy/NumPy result out. Built as a disciplined layer over SymPy + NumPy, with an MCP server so any agent (Claude Code included) can plug it in.
Highlights
- Full ODE suite — symbolic
dsolve; fixed-step RK4; adaptive Dormand–Prince 5(4); dense output (callablesol(t)); event detection with terminal events; stiff solvers (BDF2 + Newton) incl. variable-step BDF2; backward integration everywhere. Singularities/divergence raise a readable error — never NaN/garbage. - ODE codegen — standalone RK4 / DOPRI5 / dense-output integrators, bit-for-bit identical to the engine.
- Second-order optimization —
min/min_ndwithmethod newton|bfgs+ Armijo line search (converges on Rosenbrock where gradient descent stalls). - Symbolic extensions — limits (one-sided, at
oo), Taylor/Laurent series, finite & symbolic summation (divergent sums refuse cleanly). - Hardened parser — whitelist-only function resolution;
__import__/eval/open, string literals and attribute access rejected; bounded evaluation cost.
Quality
230 tests passing on Ubuntu + Windows (Python 3.11 / 3.12), mypy clean.
Install
pip install -e . # core
pip install -e .[mcp] # + MCP server for AI agents
See the README for the Claude Code skill guide and full command table.