Skip to main content

Comprehensive MCP function library for AI models

Project description

CHUK MCP Math Library

๐Ÿงฎ Comprehensive Mathematical Functions Library for AI Models (Async Native)

A cutting-edge collection of 572+ mathematical functions organized by domain, designed specifically for AI model execution with async-native performance, MCP integration, and robust error handling.

โœจ Key Features

  • ๐Ÿš€ Async Native: All 572+ functions built from the ground up for async/await patterns
  • ๐Ÿ”ข Comprehensive Coverage: 572+ functions across 25+ specialized mathematical domains
  • โœ… 94% Test Coverage: 4,429 tests passing with 94% code coverage
  • ๐ŸŽฏ MCP Integration: Model Context Protocol compatible with smart caching and performance optimization
  • ๐Ÿ“ Mathematical Domains: Number theory (340+ functions), trigonometry (120+ functions), linear algebra, calculus, statistics, geometry, probability
  • ๐ŸŒŠ Streaming Support: Real-time computation with backpressure handling
  • ๐Ÿ’พ Smart Caching: Async-optimized memory caching with TTL and LRU eviction
  • โšก Performance Optimized: Built-in performance metrics and concurrency control
  • ๐Ÿ”’ Type Safe: Complete type safety with mypy (0 errors)
  • ๐Ÿ“š Educational Ready: Rich examples, comprehensive demos, and educational applications
  • ๐Ÿ› ๏ธ Zero External Dependencies: CLI uses stdlib argparse, no click required

๐Ÿ—๏ธ Architecture Overview

chuk_mcp_math/
โ”œโ”€โ”€ arithmetic/           # Core arithmetic operations (100% coverage)
โ”‚   โ”œโ”€โ”€ core/            # Basic operations, rounding, modular
โ”‚   โ””โ”€โ”€ comparison/      # Relational, extrema, tolerance
โ”œโ”€โ”€ calculus/            # Numerical methods (100% coverage)
โ”‚   โ”œโ”€โ”€ derivatives.py   # Central, forward, backward differences
โ”‚   โ”œโ”€โ”€ integration.py   # Trapezoidal, Simpson's, midpoint rules
โ”‚   โ””โ”€โ”€ root_finding.py  # Bisection, Newton-Raphson, secant methods
โ”œโ”€โ”€ linear_algebra/      # Matrix & vector operations (100% coverage)
โ”‚   โ”œโ”€โ”€ matrices/        # Matrix ops, determinants, solvers
โ”‚   โ””โ”€โ”€ vectors/         # Vector operations, norms, projections
โ”œโ”€โ”€ probability/         # Distributions & sampling (98-100% coverage)
โ”‚   โ”œโ”€โ”€ distributions.py # Normal, uniform distributions
โ”‚   โ””โ”€โ”€ additional_distributions.py # Exponential, binomial
โ”œโ”€โ”€ statistics/          # Statistical analysis (90% coverage)
โ”‚   โ””โ”€โ”€ statistics.py    # Mean, variance, correlation, regression
โ”œโ”€โ”€ geometry/            # Geometric calculations (92-98% coverage)
โ”‚   โ”œโ”€โ”€ distances.py     # Euclidean, Manhattan, great circle
โ”‚   โ”œโ”€โ”€ intersections.py # Line, circle, polygon intersections
โ”‚   โ””โ”€โ”€ shapes.py        # Area, perimeter, centroid calculations
โ”œโ”€โ”€ number_theory/       # 18 specialized modules, 340+ functions
โ”‚   โ”œโ”€โ”€ primes/          # Prime operations and testing
โ”‚   โ”œโ”€โ”€ divisibility/    # GCD, LCM, divisors
โ”‚   โ”œโ”€โ”€ sequences/       # Fibonacci, Lucas, Catalan
โ”‚   โ”œโ”€โ”€ special_numbers/ # Perfect, abundant, amicable
โ”‚   โ”œโ”€โ”€ diophantine_equations/ # Linear, Pell's equation
โ”‚   โ”œโ”€โ”€ continued_fractions/   # CF expansions, convergents
โ”‚   โ”œโ”€โ”€ farey_sequences/       # Farey sequences, Ford circles
โ”‚   โ””โ”€โ”€ ...              # 11 more specialized modules
โ””โ”€โ”€ trigonometry/        # 8 modules, 120+ functions
    โ”œโ”€โ”€ basic_functions/ # sin, cos, tan (radians & degrees)
    โ”œโ”€โ”€ inverse_functions/ # asin, acos, atan, atan2
    โ”œโ”€โ”€ hyperbolic/      # sinh, cosh, tanh
    โ”œโ”€โ”€ wave_analysis/   # Amplitude, frequency, harmonics
    โ”œโ”€โ”€ applications/    # Navigation, physics, GPS
    โ””โ”€โ”€ ...              # 3 more modules

๐Ÿš€ Quick Start

Installation

# Basic installation (no external dependencies!)
pip install chuk-mcp-math

# With Pydantic validation support (recommended)
pip install chuk-mcp-math[pydantic]

# With development dependencies
pip install chuk-mcp-math[dev]

# Install all optional dependencies
pip install chuk-mcp-math[pydantic,dev]

Basic Usage

import asyncio
from chuk_mcp_math import number_theory, trigonometry, calculus, statistics

async def main():
    # Number theory operations
    is_prime_result = await number_theory.is_prime(17)
    fibonacci_result = await number_theory.fibonacci(10)
    gcd_result = await number_theory.gcd(48, 18)

    # Trigonometric operations
    sin_result = await trigonometry.sin(3.14159/4)
    distance = await trigonometry.distance_haversine(40.7128, -74.0060, 34.0522, -118.2437)

    # Calculus operations
    f = lambda x: x**2
    derivative = await calculus.derivative_central(f, 3.0)  # f'(3) = 6
    integral = await calculus.integrate_simpson(f, 0.0, 1.0)  # โˆซโ‚€ยน xยฒ dx = 1/3

    # Statistics operations
    data = [1, 2, 3, 4, 5]
    mean = await statistics.mean(data)
    variance = await statistics.variance(data)

    print(f"is_prime(17): {is_prime_result}")
    print(f"fibonacci(10): {fibonacci_result}")
    print(f"gcd(48, 18): {gcd_result}")
    print(f"sin(ฯ€/4): {sin_result:.6f}")
    print(f"NYC to LA distance: {distance['distance_km']:.0f} km")
    print(f"derivative of xยฒ at x=3: {derivative:.4f}")
    print(f"integral of xยฒ from 0 to 1: {integral:.6f}")

asyncio.run(main())

CLI Usage

The library includes a powerful CLI with no external dependencies (uses stdlib argparse):

# List all available functions
python -m chuk_mcp_math.cli.main list

# Search for functions
python -m chuk_mcp_math.cli.main search prime

# Describe a function
python -m chuk_mcp_math.cli.main describe is_prime

# Call a function
python -m chuk_mcp_math.cli.main call is_prime 17

# Filter by module
python -m chuk_mcp_math.cli.main list --module number_theory

# Show detailed information
python -m chuk_mcp_math.cli.main list --detailed

MCP Function Decorator

from chuk_mcp_math.mcp_decorator import mcp_function

@mcp_function(
    description="Calculate compound interest with async optimization",
    cache_strategy="memory",
    cache_ttl_seconds=3600,
    estimated_cpu_usage="medium"
)
async def compound_interest(principal: float, rate: float, time: float, compounds_per_year: int = 12) -> float:
    """Calculate compound interest: A = P(1 + r/n)^(nt)"""
    import math
    return principal * math.pow(1 + rate/compounds_per_year, compounds_per_year * time)

๐Ÿ“ New Features - Phase 1 & 2 Complete!

Phase 1: Core Numerical Engine (100% Complete)

Linear Algebra (100% Coverage)

from chuk_mcp_math.linear_algebra import matrices, vectors

# Matrix operations
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
product = await matrices.matrix_multiply(A, B)
transpose = await matrices.matrix_transpose(A)
det = await matrices.matrix_det_2x2(A)

# Solve linear systems
solution = await matrices.matrix_solve_2x2(A, [5, 6])  # Ax = b
gaussian = await matrices.gaussian_elimination(A, [5, 6])

# Vector operations
v1 = [1, 2, 3]
v2 = [4, 5, 6]
dot = await vectors.dot_product(v1, v2)
norm = await vectors.vector_norm(v1)
normalized = await vectors.normalize_vector(v1)

Calculus (100% Coverage)

from chuk_mcp_math.calculus import derivatives, integration, root_finding

# Derivatives
f = lambda x: x**2
central = await derivatives.derivative_central(f, 3.0)  # Most accurate
forward = await derivatives.derivative_forward(f, 3.0)
backward = await derivatives.derivative_backward(f, 3.0)

# Integration
integral_trap = await integration.integrate_trapezoid(f, 0.0, 1.0, 1000)
integral_simp = await integration.integrate_simpson(f, 0.0, 1.0, 1000)  # More accurate
integral_mid = await integration.integrate_midpoint(f, 0.0, 1.0, 1000)

# Root finding
f_root = lambda x: x**2 - 4  # Root at x = 2
root_bisect = await root_finding.root_find_bisection(f_root, 0.0, 3.0)
root_newton = await root_finding.root_find_newton(f_root, lambda x: 2*x, 1.0)
root_secant = await root_finding.root_find_secant(f_root, 1.0, 3.0)

Probability & Statistics (98-100% Coverage)

from chuk_mcp_math.probability import distributions, additional_distributions
from chuk_mcp_math import statistics

# Normal distribution
pdf = await distributions.normal_pdf(0.0, 0.0, 1.0)
cdf = await distributions.normal_cdf(0.0, 0.0, 1.0)
samples = await distributions.normal_sample(100, 0.0, 1.0, seed=42)

# Exponential & Binomial
exp_pdf = await additional_distributions.exponential_pdf(1.0, 1.0)
binom_pmf = await additional_distributions.binomial_pmf(3, 5, 0.5)

# Statistics
data_x = [1, 2, 3, 4, 5]
data_y = [2, 4, 6, 8, 10]
cov = await statistics.covariance(data_x, data_y)
corr = await statistics.correlation(data_x, data_y)
regression = await statistics.linear_regression(data_x, data_y)
print(f"Slope: {regression['slope']}, Rยฒ: {regression['r_squared']}")

Phase 2: Scientific & Geometry Toolkit (100% Complete)

Geometry (92-98% Coverage)

from chuk_mcp_math.geometry import distances, intersections, shapes

# Distance calculations
dist_2d = await distances.geom_distance((0, 0), (3, 4))  # Euclidean
dist_3d = await distances.geom_distance_3d((0, 0, 0), (1, 1, 1))
manhattan = await distances.geom_manhattan_distance((0, 0), (3, 4))

# GPS distance (Haversine formula)
nyc_to_la = await distances.geom_great_circle_distance(
    40.7128, -74.0060,  # NYC
    34.0522, -118.2437  # LA
)
print(f"Distance: {nyc_to_la['km']:.0f} km")

# Intersections
line_int = await intersections.geom_line_intersection(
    {"p1": (0, 0), "p2": (1, 1)},
    {"p1": (0, 1), "p2": (1, 0)}
)
circle_int = await intersections.geom_circle_intersection(
    {"x": 0, "y": 0, "r": 5},
    {"x": 5, "y": 0, "r": 5}
)

# Shapes
area = await shapes.geom_polygon_area([(0, 0), (4, 0), (4, 3), (0, 3)])
circle_area = await shapes.geom_circle_area(5.0)
triangle_area = await shapes.geom_triangle_area(3.0, 4.0, 5.0)

Advanced Statistics (90% Coverage)

from chuk_mcp_math import statistics

# Moving average
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ma = await statistics.moving_average(data, window=3)

# Z-scores and outlier detection
z_scores = await statistics.z_scores(data)
outliers = await statistics.detect_outliers(data, method="zscore", threshold=2.0)
print(f"Outliers found: {outliers['num_outliers']}")

๐ŸŽฏ Production-Quality Demos

AI Analyst Demo (Phase 1)

Comprehensive demonstration of numerical computing capabilities:

python examples/demos/ai_analyst_v0.py

Features:

  • Linear algebra: Matrix operations, solving systems
  • Calculus: Derivatives, integration, root finding
  • Probability: Distribution analysis, sampling
  • Statistics: Regression, correlation analysis
  • Combined analysis: Business metrics prediction

F1 Track Geometry Demo (Phase 2)

Advanced motorsport analytics with real-world applications:

python examples/demos/f1_track_geometry.py

Features:

  • Track geometry analysis (Monaco GP circuit)
  • Lap time modeling with sector breakdown
  • Tire degradation and fuel strategy
  • Statistical outlier detection
  • GPS-based distance calculations

๐Ÿ“Š Test Coverage & Quality

Coverage Highlights

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  OVERALL COVERAGE: 94% (10,495 statements, 643 missed)         โ•‘
โ•‘  TESTS PASSING: 4,429 โœ…                                        โ•‘
โ•‘  30 FILES WITH 100% COVERAGE โœ…                                 โ•‘
โ•‘  LINTING: PASSED โœ…                                              โ•‘
โ•‘  FORMATTING: PASSED โœ…                                           โ•‘
โ•‘  TYPE CHECKING: PASSED โœ…                                        โ•‘
โ•‘  SECURITY: PASSED โœ…                                             โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Module-by-Module Coverage:

  • โœ… Linear Algebra: 100% (matrices, vectors, solvers)
  • โœ… Calculus: 100% (derivatives, integration, root finding)
  • โœ… Probability: 98-100% (all distributions)
  • โœ… Statistics: 90% (descriptive, regression, outlier detection)
  • โœ… Geometry: 92-98% (distances, intersections, shapes)
  • โœ… Number Theory: 90-100% across all 18 modules
  • โœ… Trigonometry: 90-100% across all 8 modules
  • โœ… Arithmetic: 100%

Quality Metrics

  • 4,429 tests passing (0 failures)
  • Zero external dependencies for core functionality
  • Type-safe with mypy (0 errors)
  • Security-audited with bandit (0 issues)
  • Formatted with ruff (153 files)
  • Comprehensive error handling with edge case tests

๐Ÿ› ๏ธ Development & Testing

Running Tests

# Run all quality checks (lint, format, typecheck, security, tests)
make check

# Run unit tests
make test

# Run with coverage report
make test-cov

# Run specific test suites
pytest tests/test_phase1.py -v          # Phase 1 (linear algebra, calculus, probability, stats)
pytest tests/test_phase2_geometry.py -v # Phase 2 (geometry, advanced stats)
pytest tests/cli/ -v                    # CLI tests

Running Examples

# Run Phase 1 demo (AI Analyst)
python examples/demos/ai_analyst_v0.py

# Run Phase 2 demo (F1 Track Geometry)
python examples/demos/f1_track_geometry.py

# Run all demos
make run-demos

# Run comprehensive number theory examples
python examples/applications/demo_number_theory.py

# Run comprehensive trigonometry examples
python examples/applications/demo_trigonometry.py

๐Ÿ“š Documentation

Core Documentation

Testing Documentation

๐ŸŽ“ Use Cases

Educational

  • Mathematics Curricula: Complete coverage of undergraduate topics
  • Research Projects: Advanced algorithms for graduate-level research
  • Competitive Programming: High-performance algorithms

Professional

  • AI/ML Applications: Mathematical functions optimized for AI execution
  • Engineering Simulations: Physics, signal processing, control systems
  • Financial Modeling: Statistical analysis, optimization, risk assessment
  • Scientific Computing: Numerical methods, data analysis

Research

  • Number Theory: Prime distribution, Diophantine equations
  • Computational Mathematics: High-precision calculations
  • Data Science: Statistical analysis, machine learning preprocessing

๐Ÿ“ License

MIT License - see LICENSE file for details.

๐Ÿค Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines.

๐Ÿ“Š Function Statistics

  • Total Functions: 572+
  • Test Coverage: 94% overall (4,429 tests)
  • Zero Failures: All tests passing
  • Type Safety: 0 mypy errors
  • Phase 1 Complete: Linear Algebra, Calculus, Probability, Statistics (100% coverage)
  • Phase 2 Complete: Geometry, Advanced Statistics (92-98% coverage)
  • Number Theory: 340+ functions (90-100% coverage)
  • Trigonometry: 120+ functions (90-100% coverage)
  • 30 Files: 100% test coverage

Built with โค๏ธ for the mathematical computing community

Async-native โ€ข MCP-optimized โ€ข Educational-ready โ€ข Research-grade โ€ข Production-tested

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chuk_mcp_math-0.2.tar.gz (313.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chuk_mcp_math-0.2-py3-none-any.whl (324.1 kB view details)

Uploaded Python 3

File details

Details for the file chuk_mcp_math-0.2.tar.gz.

File metadata

  • Download URL: chuk_mcp_math-0.2.tar.gz
  • Upload date:
  • Size: 313.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for chuk_mcp_math-0.2.tar.gz
Algorithm Hash digest
SHA256 98abb237d584265333599e900b4f466d6e44585fe0cff9bfc1b2950cfc0aee8d
MD5 8a526195d5fb62fe81adaa8a884cf928
BLAKE2b-256 c36123872b46d551f257a484865ed5e7ef88304e48c69410804711d2d3e6c974

See more details on using hashes here.

File details

Details for the file chuk_mcp_math-0.2-py3-none-any.whl.

File metadata

  • Download URL: chuk_mcp_math-0.2-py3-none-any.whl
  • Upload date:
  • Size: 324.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for chuk_mcp_math-0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f756e5afc8cdc60deab39989c8ecadeba4f50f4c39b1b96b74afec468d5235dd
MD5 6fe4d1aea9e74aee2b598e155ab33ed1
BLAKE2b-256 1af35382cdfdd198b13624225bf4313900c6096db4d70d96b497afd11a72e985

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page