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 400+ 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 functions built from the ground up for async/await patterns
  • ๐Ÿ”ข Comprehensive Coverage: 400+ functions across 20+ specialized mathematical domains
  • ๐ŸŽฏ MCP Integration: Model Context Protocol compatible with smart caching and performance optimization
  • ๐Ÿ“ Mathematical Domains: Number theory, trigonometry, arithmetic, sequences, special functions
  • ๐ŸŒŠ 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
  • ๐Ÿ”’ Security Focused: Sandboxed execution with trusted/untrusted function classification
  • ๐Ÿ“š Educational Ready: Rich examples, documentation, and educational applications

๐Ÿ—๏ธ Architecture Overview

chuk_mcp_math/
โ”‚   โ”œโ”€โ”€ arithmetic/           # Core arithmetic operations
โ”‚   โ”‚   โ”œโ”€โ”€ core/            # Basic operations, rounding, modular
โ”‚   โ”‚   โ””โ”€โ”€ comparison/      # Relational, extrema, tolerance
โ”‚   โ”œโ”€โ”€ 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
โ”œโ”€โ”€ mcp_decorator.py         # Async-native MCP function decorator
โ””โ”€โ”€ mcp_pydantic_base.py     # Enhanced Pydantic base with MCP optimizations

๐Ÿš€ Quick Start

Installation

pip install chuk-mcp-math

Basic Usage

import asyncio
from chuk_mcp_math import number_theory, trigonometry

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)
    
    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")

asyncio.run(main())

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)

๐Ÿ“ Mathematical Domains

Number Theory (340+ Functions)

The most comprehensive number theory library available, featuring:

๐Ÿ”ข Core Operations

  • Primes: is_prime(), next_prime(), prime_factors(), twin_primes()
  • Divisibility: gcd(), lcm(), divisors(), euler_totient()
  • Sequences: fibonacci(), lucas_number(), catalan_number()

๐Ÿงฎ Advanced Modules

  • Diophantine Equations: Linear, Pell's equation, Pythagorean triples
  • Continued Fractions: CF expansions, convergents, rational approximations
  • Farey Sequences: Ford circles, Stern-Brocot tree, mediants
  • Special Numbers: Amicable pairs, vampire numbers, Keith numbers
  • Modular Arithmetic: Chinese Remainder Theorem, quadratic residues
# Advanced number theory examples
import asyncio
from chuk_mcp_math import number_theory

async def advanced_demo():
    # Solve Pell's equation xยฒ - 2yยฒ = 1
    pell_solution = await number_theory.solve_pell_equation(2)
    print(f"Pell equation solution: {pell_solution}")
    
    # Find continued fraction expansion of ฯ€
    pi_cf = await number_theory.continued_fraction_expansion(3.14159, 8)
    print(f"ฯ€ continued fraction: {pi_cf}")
    
    # Generate Farey sequence Fโ‚…
    farey_5 = await number_theory.farey_sequence(5)
    print(f"Farey sequence Fโ‚…: {farey_5}")
    
    # Find amicable pairs up to 10000
    amicable = await number_theory.find_amicable_pairs(10000)
    print(f"Amicable pairs: {amicable}")

asyncio.run(advanced_demo())

Trigonometry (120+ Functions)

Complete trigonometric capabilities for navigation, physics, and signal processing:

๐Ÿ“ Core Functions

  • Basic: sin(), cos(), tan() with radians/degrees variants
  • Inverse: asin(), acos(), atan(), atan2() with full quadrant support
  • Hyperbolic: sinh(), cosh(), tanh() and their inverses

๐ŸŒŠ Applications

  • Navigation: GPS distance calculation, bearing computation, triangulation
  • Wave Analysis: Amplitude extraction, harmonic analysis, Fourier basics
  • Physics: Pendulum motion, spring oscillations, damping analysis
# Navigation and wave analysis examples
import asyncio
from chuk_mcp_math import trigonometry

async def navigation_demo():
    # Calculate great circle distance between cities
    nyc_to_london = await trigonometry.distance_haversine(
        40.7128, -74.0060,  # NYC coordinates
        51.5074, -0.1278    # London coordinates
    )
    print(f"NYC to London: {nyc_to_london['distance_km']:.0f} km")
    
    # Calculate bearing
    bearing = await trigonometry.bearing_calculation(
        40.7128, -74.0060, 51.5074, -0.1278
    )
    print(f"Bearing: {bearing['bearing_degrees']:.1f}ยฐ ({bearing['compass_direction']})")
    
    # Analyze wave with amplitude and phase
    wave_analysis = await trigonometry.amplitude_from_coefficients(3, 4)
    print(f"Wave amplitude: {wave_analysis['amplitude']:.3f}")
    print(f"Phase shift: {wave_analysis['phase_degrees']:.1f}ยฐ")

asyncio.run(navigation_demo())

Arithmetic Operations

Reorganized structure with logical categorization:

๐Ÿ”ง Core Operations

from chuk_mcp_math.arithmetic.core import add, multiply, power, sqrt
from chuk_mcp_math.arithmetic.comparison import minimum, maximum, clamp

# Basic operations with async support
result = await add(5, 3)
product = await multiply(4, 7)
square_root = await sqrt(16)

# Comparison operations
min_val = await minimum(10, 20)
max_val = await maximum(10, 20)
clamped = await clamp(15, 5, 25)

๐ŸŽฏ Advanced Features

Async-Native Performance

All functions built for async/await with:

  • Concurrency Control: Configurable semaphores prevent resource exhaustion
  • Strategic Yielding: Automatic yielding in long-running operations
  • Performance Metrics: Built-in timing and execution statistics

Smart Caching System

@mcp_function(
    cache_strategy="memory",        # or "file", "hybrid", "async_lru"
    cache_ttl_seconds=3600,        # 1 hour TTL
    max_concurrent_executions=5     # Concurrency limit
)
async def expensive_calculation(n: int) -> int:
    # Expensive computation here
    await asyncio.sleep(1)  # Simulate work
    return n ** 2

Streaming Support

@mcp_function(
    supports_streaming=True,
    streaming_mode="chunked"
)
async def generate_primes(limit: int) -> AsyncIterator[int]:
    """Stream prime numbers up to limit."""
    for num in range(2, limit + 1):
        if await is_prime(num):
            yield num

Educational Applications

async def educational_demo():
    """Comprehensive number analysis for students."""
    n = 60
    
    # Analyze number properties
    factors = await number_theory.prime_factors(n)
    divisors = await number_theory.divisors(n)
    totient = await number_theory.euler_totient(n)
    
    print(f"Analysis of {n}:")
    print(f"Prime factorization: {' ร— '.join(map(str, factors))}")
    print(f"All divisors: {divisors}")
    print(f"Euler's totient ฯ†({n}) = {totient}")
    
    # Check special properties
    is_abundant = await number_theory.is_abundant_number(n)
    is_harshad = await number_theory.is_harshad_number(n)
    print(f"Abundant: {is_abundant}, Harshad: {is_harshad}")

Research Applications

async def research_demo():
    """Research-level mathematical analysis."""
    
    # Prime distribution analysis
    gaps = await number_theory.prime_gaps_analysis(1000, 1100)
    print(f"Prime gaps 1000-1100: avg={gaps['avg_gap']}, max={gaps['max_gap']}")
    
    # Farey sequence density study
    density = await number_theory.density_analysis(15)
    print(f"Farey density constant: {density['estimated_constant']:.6f}")
    
    # Continued fraction convergence
    cf_analysis = await number_theory.cf_convergence_analysis(math.pi, 10)
    print(f"ฯ€ convergence type: {cf_analysis['diophantine_type']}")
    
    # Cross-module relationships
    # Perfect numbers โ†” Mersenne primes
    for exp in [2, 3, 5, 7]:
        mersenne = 2**exp - 1
        if await number_theory.is_prime(mersenne):
            perfect = (2**(exp-1)) * mersenne
            print(f"Mersenne prime 2^{exp}-1 = {mersenne} โ†’ Perfect: {perfect}")

๐Ÿ”ง Performance & Optimization

Built-in Metrics

# Get performance statistics
stats = function.get_performance_stats()
print(f"Executions: {stats['execution_count']}")
print(f"Average duration: {stats['average_duration']:.4f}s")
print(f"Cache hit rate: {stats['cache_hit_rate']:.2%}")
print(f"Async yields: {stats['async_yields']}")

Benchmarking

async def benchmark_demo():
    import time
    
    # Benchmark large computations
    start = time.time()
    large_fib = await number_theory.fibonacci(1000)
    fib_time = time.time() - start
    print(f"fibonacci(1000): {fib_time:.4f}s")
    
    # Benchmark with caching
    await expensive_calculation.clear_cache()
    
    start = time.time()
    result1 = await expensive_calculation(100)  # Cache miss
    first_time = time.time() - start
    
    start = time.time()
    result2 = await expensive_calculation(100)  # Cache hit
    cached_time = time.time() - start
    
    print(f"First call: {first_time:.4f}s, Cached call: {cached_time:.6f}s")
    print(f"Speedup: {first_time/cached_time:.1f}x")

๐Ÿ› ๏ธ Development & Testing

Running the Demos

# Number theory comprehensive demo
python -m chuk_mcp_math.number_theory

# Trigonometry comprehensive demo  
python -m chuk_mcp_math.trigonometry

# Run specific demonstrations
python number_theory_demo.py
python trigonometry_demo.py

Testing Individual Functions

import asyncio
from chuk_mcp_math import number_theory

async def test_functions():
    # Test prime operations
    assert await number_theory.is_prime(17) == True
    assert await number_theory.is_prime(4) == False
    
    # Test Fibonacci
    assert await number_theory.fibonacci(10) == 55
    
    # Test GCD
    assert await number_theory.gcd(48, 18) == 6
    
    print("โœ… All tests passed!")

asyncio.run(test_functions())

๐Ÿ“Š Function Statistics

  • Total Functions: 400+
  • Async Native: 100%
  • Number Theory: 340+ functions across 18 modules
  • Trigonometry: 120+ functions across 8 modules
  • Arithmetic: 30+ functions in reorganized structure
  • Performance Optimized: Built-in caching, concurrency control
  • Educational Ready: Comprehensive examples and documentation

๐ŸŽ“ Educational Use Cases

  • Mathematics Curricula: Complete coverage of undergraduate number theory and trigonometry
  • Research Projects: Advanced algorithms for graduate-level mathematical research
  • AI/ML Applications: Mathematical functions optimized for AI model execution
  • Competitive Programming: High-performance algorithms for contests
  • Professional Development: Mathematical software for engineering applications

๐Ÿ”ฌ Research Applications

  • Number Theory Research: Prime distribution, Diophantine equations, continued fractions
  • Cryptographic Analysis: Modular arithmetic, quadratic residues, discrete logarithms
  • Mathematical Physics: Trigonometric applications, oscillations, wave analysis
  • Computational Mathematics: High-precision constants, approximation theory
  • Geometric Number Theory: Farey sequences, Ford circles, lattice problems

๐Ÿš€ Performance Highlights

  • Async-Native: All functions built for async/await from the ground up
  • Smart Caching: Memory-optimized caching with TTL and LRU eviction
  • Concurrency Control: Configurable semaphores prevent resource exhaustion
  • Strategic Yielding: Long operations yield control automatically
  • Batch Processing: Optimized for processing large datasets
  • Memory Efficient: Minimal memory footprint with cleanup strategies

๐Ÿ“ License

MIT License - see LICENSE file for details.

๐Ÿค Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines.

๐Ÿ“š Documentation

  • Full API documentation available in docstrings
  • Comprehensive examples in demo files
  • Educational materials for classroom use
  • Research applications and case studies

๐Ÿ”— Links


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

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

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.1.0.tar.gz (258.6 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.1.0-py3-none-any.whl (289.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: chuk_mcp_math-0.1.0.tar.gz
  • Upload date:
  • Size: 258.6 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.1.0.tar.gz
Algorithm Hash digest
SHA256 9bbde519890a665f3e3eec6bd4e6f252cac0a9c3c7342a368b767c1856ed763a
MD5 a54675c98e1ecf13f84e3e4d3eee2e81
BLAKE2b-256 529995fb25723db016e6949b9a40118f61e12f18cf143fc6f4ff40cb537e7246

See more details on using hashes here.

File details

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

File metadata

  • Download URL: chuk_mcp_math-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 289.2 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.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 262b220ecb566887270d99f102a8a0ed3a9bdb421d4b23705151d3ca14479f95
MD5 8e1353ce02eba51b9bf8f0195f5d8328
BLAKE2b-256 d49df28e55545f9fc31bee8ae207740385a92200170425fd20e4b011330e6a1a

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