Skip to main content
Glama
oce-math-mcp

oce-math-mcp

by oce-projects

oce-math-mcp

Server MCP (Model Context Protocol) di matematica per modelli linguistici locali, pensato per addestrare e far lavorare Qwen3.6 su calcoli che un modello non sa fare a mente: aritmetica esatta, algebra simbolica, analisi, teoria dei numeri, calcolo numerico, verifica delle risposte, calendario italiano, geometria 3D per CAD/CNC e prove formali in Lean 4.

Stato: versione 0.1.0. 9 tool su 10 funzionano; eng_calc ha lo schema fissato e il codice arriva in fase 2. Le operation implementate sono 112 su 137 (le altre 25 sono di eng_calc).

Perché

Il modello di base sbaglia quasi tutti i calcoli complessi: nel benchmark di partenza Qwen3.6-35B-A3B ha dato il risultato esatto in 1 problema su 12. Un modello non deve calcolare a mente: deve chiamare uno strumento deterministico e verificabile. Lo stesso server produce anche le risposte vere per il dataset di addestramento.

Related MCP server: Polymath MegaBlaster MCP

Tool

Tool

Cosa fa

math_eval

aritmetica esatta (decimal, fraction, float), funzioni, statistica, finanza italiana, unità

math_solve

algebra e analisi simbolica con SymPy (34 operation), con verifica delle soluzioni

number_theory

primi, fattorizzazione, aritmetica modulare, equazioni diofantee (26 operation)

math_numeric

precisione arbitraria, somme e integrali numerici, ottimizzazione, ODE (10 operation)

math_verify

controlla una risposta: equivalenza, sostituzione, derivate, disuguaglianze (6 operation)

python_sandbox

programmi Python brevi in un interprete ristretto (conteggi, forza bruta, successioni)

lean_check

verifica una dimostrazione in Lean 4 con Mathlib (limite 60 s)

date_calc

calendario italiano Europe/Rome: età, festività, giorni lavorativi, fusi (12 operation)

geom3d_calc

vettori, rotazioni, quaternioni, solidi, CNC, calcoli per il disegno 3D (24 operation)

eng_calc

formule di progetto meccanico: schema pronto, codice in fase 2

Il contratto completo (nomi, schemi JSON, esempi) è in docs/spec/SPEC_OCE_MATH_MCP_V3.md e in docs/spec/oce_math_mcp_tools.json. Ogni risposta ha 9 campi fissi: ok, tool, operation, result, units, formula_used, formatted_it, warnings, error.

Installazione

Serve Python 3.12 o più recente e uv.

uv sync --compile-bytecode

--compile-bytecode serve una volta sola: senza, ogni processo di calcolo ricompila SymPy e SciPy quando PYTHONDONTWRITEBYTECODE è attivo (avvio misurato 4,997 s contro 2,853 s, decisione D34).

Se la repo sta su un disco di rete, tieni l'ambiente Python su un disco locale (decisione D26):

$env:UV_PROJECT_ENVIRONMENT = "$HOME\.venvs\oce-math-mcp"; uv sync --compile-bytecode

Avvio

Transport stdio (quello che usano i client MCP):

uv run oce-math-mcp

Streamable HTTP su http://127.0.0.1:8012/mcp:

uv run oce-math-mcp --http --port 8012

Esempio di configurazione per un client MCP:

{
  "mcpServers": {
    "oce-math": { "command": "uv", "args": ["run", "--directory", "<percorso della repo>", "oce-math-mcp"] }
  }
}

Opzioni

Opzione

Effetto

--http, --host, --port

streamable HTTP invece di stdio (predefiniti 127.0.0.1 e 8012)

--pool-size N

processi di calcolo (predefinito: OCE_MATH_POOL_SIZE, altrimenti CPU-1, massimo 4)

--no-pool

calcolo nel processo del server, solo per prove: il timeout non può fermare il calcolo

--dump-schemas --format mcp|openai

stampa gli schemi dei 10 tool ed esce

--misura

misura avvio, latenza e ripartenza dei processi di calcolo (risultato in JSON)

--misura-md FILE

con --misura: scrive anche la tabella in Markdown (per esempio docs/MISURE.md)

--prova-tir FILE...

esegue in python_sandbox le chiamate di calcolo di file JSONL TIR e le confronta con le risposte registrate (decisione D13)

--install-lean

installa elan, Lean 4 e Mathlib dentro la repo (decisione D17)

--sync-spec --note "..."

copia il contratto nella spec e nelle copie esterne del progetto

Variabile d'ambiente

Effetto

OCE_MATH_POOL_SIZE

numero di processi di calcolo

OCE_MATH_ELAN_HOME

cartella di elan (predefinita .lean-tools/elan nella repo)

OCE_MATH_LEAN_PROJECT

progetto Lean con Mathlib (predefinito lean/ nella repo)

OCE_MATH_DATASET_DIR, OCE_MATH_RAG_DOC

destinazioni di --sync-spec

Lean 4 e Mathlib

lean_check funziona solo dopo l'installazione:

uv run oce-math-mcp --install-lean

Il comando scarica elan, installa la toolchain fissata in lean/lean-toolchain, scarica Mathlib e i suoi file già compilati (lake exe cache get). Senza Lean, lean_check risponde con un errore chiaro e gli altri tool funzionano. Servono circa 10 GB: misurati 3.287,2 MB per elan e 6.993,7 MB per Mathlib. Tempi misurati: docs/MISURE.md.

Se la repo sta su un disco di rete, installa Lean su un disco locale (proposta D37: sul disco di rete l'installazione è fallita 2 volte su 2). Le stesse variabili vanno date anche al server:

$env:OCE_MATH_ELAN_HOME = "$HOME\.oce-math-mcp\elan"; $env:OCE_MATH_LEAN_PROJECT = "$HOME\.oce-math-mcp\lean"; uv run oce-math-mcp --install-lean

lean_check rifiuta il codice che può eseguire programmi o aggiungere assiomi (#eval, elab, macro, run_cmd, axiom, native_decide e altri, decisione D36) e dichiara valida una dimostrazione solo se usa gli assiomi standard (propext, Classical.choice, Quot.sound).

Sicurezza

  • Nessun eval, exec, sympify o parse_expr sul testo del modello: un parser AST a whitelist costruisce le espressioni SymPy (decisioni D5 e D31). Un test intercetta eval ed exec durante i calcoli e fallisce se il testo del modello arriva a uno dei due.

  • python_sandbox è un interprete AST scritto qui, non exec: moduli e funzioni da una lista ammessa, attributi pericolosi bloccati (D13, D28, D29). Accetta i costrutti tipici dei programmi TIR: from sympy import *, global, sympy.S, nsimplify (D38); class no.

  • Limiti: espressione fino a 2.000 caratteri, esponente fino a 10.000, timeout di 5 secondi per chiamata. Il calcolo gira in processi separati: allo scadere il processo viene ucciso e sostituito (D32). Limite di memoria per processo (Job Object su Windows, RLIMIT_AS su Linux).

  • Nessuna eccezione esce dal server: ogni errore ha code, message ed example.

Sviluppo

Le prove si lanciano sul PC o su un server di casa, non in GitHub Actions.

uv run ruff check src tests
uv run ruff format --check src tests
uv run basedpyright
uv run pytest -q

La suite comprende le prove reali del server in stdio e in HTTP. I test di lean_check si saltano se Lean non è installato.

Documenti

  • docs/spec/SPEC_OCE_MATH_MCP_V3.md: contratto dei 10 tool (prevale sulla spec V2)

  • docs/DECISIONI.md: registro delle decisioni

  • docs/MISURE.md: tempi e spazio misurati

  • docs/DISCUSSIONE-2026-11-23.md: discussione di avvio e strategia

  • CHANGELOG.md: storia delle versioni

Licenza

Apache License 2.0, vedi LICENSE e NOTICE.

Available Tools

10 tools
date_calcC

Dates and times in the Italian calendar (Europe/Rome): exact age (also in months and weeks), weekday, differences (days, business days, real elapsed hours across DST) and additions, relative dates, events with DST offsets and reminders, recurring events, time zone conversion, invoice due dates (DFFM), month calendar, Italian national holidays including Easter and Easter Monday.

Inputs: operation (required), nth, date, days, +18 more.

eng_calcC

Engineering design formulas: strength of materials (Hooke, beams, shafts, Von Mises/Tresca, Euler buckling, fatigue, pressure vessels, bolts, welds), machine design (dynamics, vibrations, gears, bearings L10, belts, CNC cutting), fluids and heat (pipes, drag/lift, heat transfer, heatsinks), electrical and control (AC/DC, RLC filters, Clarke/Park, second-order systems, PID, optics, acoustics), material properties.

Inputs: params (required), operation (required).

geom3d_calcC

3D geometry for CAD, CNC and robotics: vector operations, angles, rotations (Euler, axis-angle), 4x4 homogeneous transforms, quaternions, Denavit-Hartenberg forward kinematics, distances and intersections, cylindrical and spherical coordinates, bolt holes, solid and cross-section properties. For 3D drawing: 2D sketch profiles, circles through 3 points, fillets, triangle solving, curves as point lists (helix, involute, spline, parametric), CAD pick points on faces and edges, patterns, point clouds, mesh and composite part checks (volume, centroid, bounding box).

Inputs: operation (required), v1, v2, axis, +10 more.

lean_checkA

Check a formal proof in Lean 4 with Mathlib. Returns whether it compiles without errors, without sorry and with only the standard axioms, with Lean messages. Code that runs programs (#eval, run_cmd, elab, macro), new axioms and native_decide are rejected. 60 s limit.

Inputs: code (required), allow_sorry.

math_evalC

Exact arithmetic and scalar functions: Decimal/Fraction/float modes, logs, roots, trig in rad and deg, hyperbolic, combinatorics, statistics and distributions, Italian finance (VAT, withholding, loans, NPV, IRR, DCF), unit conversion.

Inputs: expr (required), precision, variables, exact_mode, +1 more.

math_numericC

Numerical math with mpmath, SciPy and NumPy: arbitrary precision evaluation (up to 1000 digits), infinite sums, numerical integrals, roots, constrained and global optimization, linear and integer programming, ODE initial value problems, polynomial roots, closed-form identification of constants, curve fitting.

Inputs: operation (required), x0, expr, bounds, +9 more.

math_solveC

Symbolic math with SymPy plus SciPy/NumPy: equations, systems, inequalities, derivatives, integrals (single, multiple, line, surface), limits, series, function study, vector calculus, Lagrange, ODE, Laplace, Fourier/FFT, Riccati LQR, linear algebra, sums, recurrences, polynomials, complex numbers. Results are self-verified.

Inputs: operation (required), ics, expr, time, +15 more.

math_verifyB

Check an answer before giving it: symbolic and random-point equivalence of two expressions, substitution of a solution into equations, derivative and antiderivative checks, numeric comparison with tolerance, counterexample search for inequalities.

Inputs: expr (required), operation (required), domain, samples, +4 more.

number_theoryB

Integer and modular arithmetic with exact big integers: primality, factorization, divisors, totient, Mobius, primes, gcd/lcm/extended gcd, modular power/inverse/square root/log, primitive roots, Legendre/Jacobi, CRT, Diophantine equations, continued fractions, partitions, digits.

Inputs: operation (required), k, m, n, +6 more.

python_sandboxA

Run a short Python program in a restricted interpreter for problems no other tool covers (counting, brute force, sequences, multi-step computations). Allowed imports: math, cmath, fractions, decimal, itertools, functools, collections, statistics, random, heapq, bisect, sympy, numpy, scipy, mpmath. No files, no network, 5 s limit. Returns printed output and the value of the last expression.

Inputs: code (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3/5.0

    Scored across 10 tools

    Disambiguation3/5

    The three computational cores (math_eval for exact/scalar, math_solve for symbolic, math_numeric for arbitrary-precision/numerical) are conceptually distinct but overlap in practice: roots, integrals and evaluation can plausibly be routed to any of them, and eng_calc/math_eval both cover engineering-finance formulas while date_calc also handles invoice due dates. The very long descriptions help an agent choose, but boundaries are decided by mode (exact vs symbolic vs numeric) rather than by resource, which invites misselection.

    Naming Consistency3/5

    Half the tools use a clean math_* prefix family (math_eval, math_solve, math_numeric, math_verify) while the rest use domain-first or suffix conventions (geom3d_calc, date_calc, eng_calc, number_theory, python_sandbox, lean_check). There is a loose 'domain + action/noun' logic throughout, but no single predictable pattern, and geom3d_calc breaks the calc/verb scheme entirely.

    Tool Count5/5

    Ten tools is squarely in the well-scoped range, and each corresponds to a recognizable subdomain (arithmetic, symbolic, numeric, number theory, geometry, verification, sandbox, proof, dates, engineering). No tool looks redundant at the count level, even though individual tools internally bundle very large surfaces.

    Completeness4/5

    The surface covers essentially the full lifecycle of a math problem: compute, solve, numerically approximate, verify, formally prove, and fall back to a sandbox, plus geometry, dates and engineering. Minor gaps remain — no plotting/visualization or matrix-oriented entry point and unit conversion is buried inside math_eval rather than exposed — but agents can work around these.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      A secure mathematical computation sandbox that enables LLMs to perform symbolic math operations like algebra, calculus, and equation solving via SymPy. It features low-latency execution through pre-warmed process pools and provides standardized JSON outputs for reliable agent integration.
      1
      2
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Enables AI agents to perform accurate local computations including arbitrary-precision math, date handling, unit conversion, subnet calculations, encoding, hashing, and text analysis, all without network calls or API keys.
      27
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Provides LLMs with deterministic math tools for sandboxed expression evaluation, descriptive statistics, primality testing, prime factorization, GCD/LCM, quadratic solving, and base conversion. Every operation runs real code rather than relying on the model's arithmetic, with expression parsing restricted to a whitelist of operators, constants, and functions.
      21
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables language models and users to perform exact arithmetic, symbolic math, unit/date conversions, statistics, and read-only SQL queries over registered files, with every operation logged by a citable ID that humans can re-run.
      11
      MIT