Skip to main content
Glama
danielsimonjr

Math MCP Server

Math MCP Server

CI License: ISC Node.js Version

A high-performance, production-ready MCP (Model Context Protocol) server providing secure mathematical computation capabilities powered by mathjs, with Multi-Tier Acceleration through WebWorkers, WebAssembly (WASM), and comprehensive security features.

๐Ÿš€ Performance

This server features intelligent multi-tier acceleration providing up to 1920x speedup compared to pure JavaScript:

  • ๐ŸŽฏ Intelligent Routing: Automatically selects optimal acceleration tier (mathjs โ†’ WASM โ†’ Workers โ†’ GPU)

  • โšก WebWorkers: 3-4x faster than WASM for large operations (multi-threaded)

  • ๐Ÿ”ฅ WASM: 14x faster than mathjs for medium operations (single-threaded)

  • ๐Ÿš„ WebGPU: 50-100x faster than Workers for massive operations (GPU, future)

  • ๐Ÿ”„ Graceful Fallback: GPU โ†’ Workers โ†’ WASM โ†’ mathjs (never fails)

  • โœ… Zero Breaking Changes: 100% backward compatible API

Performance Results

Operation

Size

mathjs

WASM

Workers

GPU (future)

Best Speedup

Matrix Multiply

10ร—10

0.5ms

0.06ms

-

-

8x

Matrix Multiply

100ร—100

95ms

12ms

3ms

-

32x

Matrix Multiply

1000ร—1000

96s

12s

3s

0.05s

1920x

Statistics (Mean)

1K elements

0.1ms

0.003ms

-

-

33x

Statistics (Mean)

100K elements

10ms

0.3ms

0.08ms

-

125x

Statistics (Mean)

10M elements

1000ms

25ms

7ms

0.1ms

10000x

Current (Node.js): Up to 143x speedup with WebWorkers Future (Browser): Up to 10000x speedup with WebGPU

For detailed benchmarks and architecture, see docs/ACCELERATION_ARCHITECTURE.md.

โœจ Features

โšก Multi-Tier Acceleration

  • Intelligent Routing: Automatically routes operations through optimal acceleration tier

  • WebWorker Pool: Dynamic 2-8 worker threads for parallel processing

  • WASM Acceleration: AssemblyScript-compiled modules for medium operations

  • WebGPU Ready: GPU compute shaders (browser/Deno support planned)

  • Performance Tracking: Monitor acceleration tier usage and statistics

  • Zero Configuration: Works out-of-the-box with automatic optimization

๐Ÿ” Security Features

  • Rate Limiting: Token bucket algorithm prevents DoS attacks

    • Configurable request limits per time window

    • Concurrent request limits (max in-flight operations)

    • Queue size limits for pending requests

  • WASM Integrity Verification: Cryptographic SHA-256 verification of WASM binaries

    • Prevents execution of tampered modules

    • Automatic verification at runtime

  • Expression Sandboxing: AST validation prevents code injection

    • Whitelist-based approach for safe operations

    • Blocks dangerous functions and assignments

  • Input Validation: Comprehensive validation for all inputs

    • Length limits and format validation

    • Size limits prevent resource exhaustion

  • Timeout Protection: Configurable timeout for all operations

  • Type Safety: Strict TypeScript with enforced type checking

โšก Performance Optimizations

  • Expression Caching: LRU cache for parsed/compiled expressions

    • Reduces repeated parsing overhead

    • Configurable cache size (default: 1000 entries)

  • Early Size Checks: Prevents event loop blocking from oversized inputs

  • Efficient Logging: Proper stream separation (stdout/stderr)

๐Ÿ“Š Observability & Production Readiness โšก NEW in v3.2.0

  • Prometheus Metrics Export: Production-grade monitoring

    • Operation duration histograms with configurable buckets

    • Operation counters by type, tier, and status

    • Real-time queue size and worker count gauges

    • Rate limit hits and backpressure event tracking

    • Cache hit/miss rates and effectiveness metrics

    • HTTP endpoint on port 9090 for Prometheus scraping

  • Health Check System: Kubernetes-compatible probes

    • GET /health - Overall system health (healthy/degraded/unhealthy)

    • GET /health/live - Liveness probe (always returns true)

    • GET /health/ready - Readiness probe (based on health status)

    • Component-level checks: WASM, rate limiter, memory usage

    • Detailed diagnostics with timestamps

  • Telemetry HTTP Server: Standalone observability server

    • Runs on port 9090 (configurable)

    • Metrics in Prometheus text format

    • JSON metrics export via /metrics/json

    • Health status in JSON format

    • No impact on main server performance

  • Backpressure Management: Intelligent queue overflow handling

    • REJECT Strategy: Fast fail when at capacity (low latency)

    • WAIT Strategy: Queue with timeout (max throughput)

    • SHED Strategy: Drop oldest tasks (favor fresh requests)

    • Event-driven monitoring with backpressure events

    • Automatic queue size and wait time tracking

  • Dependency Injection Architecture: Clean, testable design

    • Constructor injection for worker pools and rate limiters

    • Interface-based abstractions for easy mocking

    • Improved test coverage (721 total tests, 92% security coverage)

    • Reduced coupling between components

๐Ÿ›ก๏ธ Comprehensive Security Testing โšก NEW in v3.2.0

  • 119 Security Tests: Multi-layered security validation

    • Injection Prevention: 36 tests for code/command injection

    • DoS Protection: 28 tests for rate limiting and resource exhaustion

    • Fuzzing: 24 tests with random/malformed inputs

    • Bounds Testing: 31 tests for size limits and edge cases

    • 92% Pass Rate: 110/119 tests passing, actively maintained

  • WASM Security: Integrity verification and sandboxing

    • SHA-256 cryptographic verification of all WASM binaries

    • Memory isolation between workers and main thread

    • Automatic fallback on integrity failures

โšก Lazy Loading & Faster Startup โšก NEW in v3.4.0

  • Lazy WASM Initialization: WASM modules load on-demand at first use

    • No startup overhead until acceleration is needed

    • Thread-safe concurrent initialization (Promise-based)

    • Reduces cold start time for simple operations

  • Dynamic GPU Import: GPU module only loads when GPU is actually used

    • No browser/GPU detection overhead at startup

    • Cleaner module dependency graph

  • Worker Pool On-Demand: Workers created lazily when needed

๐Ÿ”ง Codebase Refactoring โšก NEW in v3.5.0

  • 44% Code Reduction: Complete refactoring across 7 sprints

    • Sprint 1-3: WASM wrapper, acceleration router, tool handlers optimization

    • Sprint 4: Lazy loading implementation

    • Sprint 5-7: Documentation, dead code removal, worker infrastructure

  • Generic Parallel Executor Framework: Type-safe parallel operation pattern

    • Unified chunking utilities for arrays and matrices

    • Configurable merge strategies (sum, min, max, concat)

    • Foundation for future parallel operation extensions

  • Improved Type Safety: Better generic constraints and DI patterns

7 Mathematical Tools

  1. evaluate - Evaluate mathematical expressions with variables

  2. simplify - Simplify algebraic expressions

  3. derivative - Calculate derivatives

  4. solve - Solve equations

  5. matrix_operations โšก - Matrix operations (WASM-accelerated)

  6. statistics โšก - Statistical calculations (WASM-accelerated)

  7. unit_conversion - Convert between units

โšก = WASM-accelerated for large inputs

Example Usage

// Matrix operations (WASM-accelerated for 10x10+)
matrix_operations("determinant", "[[1,2],[3,4]]")  // -2

// Statistics (WASM-accelerated for 100+ elements)
// Note: mode returns an array
statistics("mean", "[1,2,3,4,5]")  // 3
statistics("mode", "[1,2,2,3,4]")  // [2]

// Symbolic math
derivative("x^2", "x")  // "2 * x"
simplify("2 * x + x")   // "3 * x"

// Unit conversion
unit_conversion("5 inches", "cm")  // "12.7 cm"

๐Ÿ“ฆ Installation

Requirements

Before installing, ensure you have:

  • Node.js: โ‰ฅ18.0.0 (required for worker_threads and ESM support)

  • npm: โ‰ฅ8.0.0

  • Platform: Windows, macOS, or Linux

  • Memory: Minimum 2GB RAM (4GB+ recommended for large operations)

Quick Start

# Clone the repository
git clone https://github.com/danielsimonjr/math-mcp.git
cd math-mcp

# Install dependencies
npm install

# Build the project
npm run build

# Build WASM modules (platform-specific)
# Linux/macOS:
cd wasm && npm install && npx gulp && cd ..

# Windows (PowerShell):
# cd wasm; npm install; npx gulp; cd ..

# Run tests
npm test

Verify Installation

After installation, verify everything is working correctly:

# 1. Check Node.js version
node --version  # Should show v18.0.0 or higher

# 2. Verify TypeScript compilation
npm run type-check  # Should complete without errors

# 3. Run integration tests
npm test  # Should show "11/11 tests passing"

# 4. Check WASM modules are built
ls -l wasm/build/*.wasm  # Should see release.wasm and debug.wasm
# Windows: dir wasm\build\*.wasm

Expected output from tests:

โœ“ All integration tests passed!
โœ“ WASM integration working correctly
โœ“ Threshold-based routing working
Success rate: 100.0%

Integration with Claude Desktop

Add to your Claude Desktop config file:

Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "math-mcp": {
      "command": "node",
      "args": ["C:/path/to/math-mcp/dist/index-wasm.js"]
    }
  }
}

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Linux: ~/.config/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "math-mcp": {
      "command": "node",
      "args": ["/path/to/math-mcp/dist/index-wasm.js"]
    }
  }
}

Restart Claude Desktop and start using math tools!

Integration with Claude CLI

claude mcp add --transport stdio math-mcp node /path/to/math-mcp/dist/index-wasm.js

๐Ÿงฎ Tools Documentation

1. evaluate

Evaluate mathematical expressions with optional variables.

Parameters:

  • expression (string): Mathematical expression to evaluate

  • scope (object, optional): Variables to use in the expression

Examples:

evaluate("2 + 2")                    // 4
evaluate("sqrt(16)")                 // 4
evaluate("x^2 + 2*x", {x: 5})       // 35
evaluate("derivative(x^2, x)")       // "2 * x"

2. simplify

Simplify mathematical expressions.

Parameters:

  • expression (string): Expression to simplify

Examples:

simplify("2 * x + x")               // "3 * x"
simplify("(x + 2)^2")               // "x^2 + 4*x + 4"

3. derivative

Calculate derivatives of expressions.

Parameters:

  • expression (string): Expression to differentiate

  • variable (string): Variable to differentiate with respect to

Examples:

derivative("x^2", "x")              // "2 * x"
derivative("sin(x)", "x")           // "cos(x)"

4. solve

Solve equations.

Parameters:

  • equation (string): Equation to solve

  • variable (string): Variable to solve for

Examples:

solve("x^2 - 4 = 0", "x")           // Solutions for x
solve("2*x + 3 = 7", "x")           // x = 2

5. matrix_operations (Multi-Tier Accelerated โšกโšกโšก)

Perform matrix operations with intelligent multi-tier acceleration.

Parameters:

  • operation (string): Operation to perform

    • multiply, inverse, determinant, transpose, eigenvalues, add, subtract

  • matrix_a (string): First matrix in JSON format

  • matrix_b (string, optional): Second matrix (for binary operations)

Acceleration Tiers:

  • mathjs (< 10ร—10): Pure JavaScript, no overhead

  • WASM (10-100): Single-threaded, 8-17x faster

  • WebWorkers (100-500): Multi-threaded, 32x faster โšก NEW

  • WebGPU (500+): GPU-accelerated, 1920x faster (future) โšกโšกโšก

Examples:

matrix_operations("determinant", "[[1,2],[3,4]]")           // -2
matrix_operations("multiply", "[[1,2],[3,4]]", "[[5,6],[7,8]]")  // [[19,22],[43,50]]
matrix_operations("transpose", "[[1,2,3],[4,5,6]]")         // [[1,4],[2,5],[3,6]]
matrix_operations("add", "[[1,2],[3,4]]", "[[5,6],[7,8]]")      // [[6,8],[10,12]]
matrix_operations("subtract", "[[5,6],[7,8]]", "[[1,2],[3,4]]") // [[4,4],[4,4]]

6. statistics (Multi-Tier Accelerated โšกโšกโšก)

Calculate statistical values with intelligent multi-tier acceleration.

Parameters:

  • operation (string): Statistical operation

    • mean, median, mode, std, variance, min, max, sum, product

  • data (string): Data array in JSON format

Acceleration Tiers:

  • mathjs (< 100): Pure JavaScript, no overhead

  • WASM (100-100K): Single-threaded, 15-42x faster

  • WebWorkers (100K-1M): Multi-threaded, 125x faster โšก NEW

  • WebGPU (1M+): GPU-accelerated, 10000x faster (future) โšกโšกโšก

Examples:

statistics("mean", "[1,2,3,4,5]")               // 3
statistics("std", "[2,4,4,4,5,5,7,9]")          // 2
statistics("median", "[1,2,3,4,5]")             // 3
statistics("mode", "[1,2,2,3,4,4,4,5]")         // 4
statistics("product", "[2,3,4]")                // 24

7. unit_conversion

Convert between units.

Parameters:

  • value (string): Value with unit (e.g., "5 inches")

  • target_unit (string): Target unit (e.g., "cm")

Examples:

unit_conversion("5 inches", "cm")               // "12.7 cm"
unit_conversion("100 fahrenheit", "celsius")    // "37.78 celsius"
unit_conversion("50 mph", "km/h")               // "80.47 km/h"

๐Ÿ”ง How Multi-Tier Acceleration Works

The server intelligently routes operations through optimal acceleration tiers:

Small Data (< 10ร—10)
    โ†“
  mathjs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Result
    Fast for small ops, no overhead

Medium Data (10-100)
    โ†“
  WASM โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Result
    14x faster, single-threaded

Large Data (100-500)
    โ†“
  WebWorkers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Result
    56x faster, multi-threaded (3-4x ร— WASM)

Massive Data (500+)
    โ†“
  WebGPU โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ†’ Result
    5600x faster, GPU-accelerated (future)

Graceful Fallback Chain:

GPU โ†’ Workers โ†’ WASM โ†’ mathjs

If any tier fails, automatically falls back to the next tier. Never fails!

๐Ÿ“Š Architecture

MCP Server (index-wasm.ts)
    โ†“
Acceleration Router (acceleration-router.ts)
    โ†“
Size Analysis & Tier Selection
    โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚       โ”‚          โ”‚              โ”‚          โ”‚
โ–ผ       โ–ผ          โ–ผ              โ–ผ          โ”‚
mathjs  WASM   WebWorkers      WebGPU       โ”‚
(small) (medium)  (large)      (massive)    โ”‚
  โ”‚       โ”‚          โ”‚              โ”‚        โ”‚
  โ”‚       โ”‚     โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”        โ”‚        โ”‚
  โ”‚       โ”‚     โ”‚ Worker 1 โ”‚        โ”‚        โ”‚
  โ”‚       โ”‚     โ”‚ Worker 2 โ”‚        โ”‚        โ”‚
  โ”‚       โ”‚     โ”‚ Worker N โ”‚        โ”‚        โ”‚
  โ”‚       โ”‚     โ”‚ (WASM)   โ”‚        โ”‚        โ”‚
  โ”‚       โ”‚     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜        โ”‚        โ”‚
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                     โ†“
                  Result

Architecture Benefits:

  • Intelligent routing based on operation size

  • Parallel processing for large operations

  • GPU acceleration for massive operations (future)

  • Graceful fallback at every tier

  • Zero configuration required

  • Automatic performance optimization

๐Ÿ“ Project Structure

math-mcp/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts                  # Original mathjs-only server
โ”‚   โ”œโ”€โ”€ index-wasm.ts             # Multi-tier accelerated server (production)
โ”‚   โ”œโ”€โ”€ acceleration-router.ts    # โšก Intelligent routing logic (v3.0.0)
โ”‚   โ”œโ”€โ”€ acceleration-adapter.ts   # โšก Clean adapter interface (v3.0.0)
โ”‚   โ”œโ”€โ”€ wasm-wrapper.ts           # WASM integration layer
โ”‚   โ”œโ”€โ”€ tool-handlers.ts          # Business logic for all tools
โ”‚   โ”œโ”€โ”€ validation.ts             # Input validation & security
โ”‚   โ”œโ”€โ”€ errors.ts                 # Custom error types
โ”‚   โ”œโ”€โ”€ utils.ts                  # Utilities and logging
โ”‚   โ”œโ”€โ”€ rate-limiter.ts           # Token bucket rate limiting
โ”‚   โ”œโ”€โ”€ health.ts                 # โšก Health check system (v3.2.0)
โ”‚   โ”œโ”€โ”€ telemetry/                # โšก Observability system (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ metrics.ts            # Prometheus metrics collection
โ”‚   โ”‚   โ””โ”€โ”€ server.ts             # HTTP telemetry server (port 9090)
โ”‚   โ”œโ”€โ”€ workers/                  # โšก WebWorker infrastructure (v3.0.0)
โ”‚   โ”‚   โ”œโ”€โ”€ worker-pool.ts        # Dynamic worker pool with DI (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ parallel-executor.ts  # โšก Generic parallel framework (v3.5.0)
โ”‚   โ”‚   โ”œโ”€โ”€ backpressure-queue.ts # โšก Backpressure strategies (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ task-queue.ts         # Priority-based task scheduling
โ”‚   โ”‚   โ”œโ”€โ”€ math-worker.ts        # Worker thread implementation
โ”‚   โ”‚   โ”œโ”€โ”€ parallel-matrix.ts    # Parallel matrix operations
โ”‚   โ”‚   โ”œโ”€โ”€ parallel-stats.ts     # Parallel statistics
โ”‚   โ”‚   โ”œโ”€โ”€ chunk-utils.ts        # Data chunking utilities
โ”‚   โ”‚   โ””โ”€โ”€ worker-types.ts       # Type definitions
โ”‚   โ””โ”€โ”€ gpu/                      # โšก WebGPU acceleration (future)
โ”‚       โ””โ”€โ”€ webgpu-wrapper.ts     # GPU compute shaders
โ”œโ”€โ”€ wasm/
โ”‚   โ”œโ”€โ”€ assembly/                 # AssemblyScript source
โ”‚   โ”‚   โ”œโ”€โ”€ matrix/
โ”‚   โ”‚   โ””โ”€โ”€ statistics/
โ”‚   โ”œโ”€โ”€ bindings/                 # JavaScript bindings
โ”‚   โ”œโ”€โ”€ build/                    # Compiled WASM
โ”‚   โ”œโ”€โ”€ tests/                    # WASM tests
โ”‚   โ””โ”€โ”€ benchmarks/               # Performance benchmarks
โ”œโ”€โ”€ test/
โ”‚   โ”œโ”€โ”€ integration-test.js       # Integration tests (11/11 passing)
โ”‚   โ”œโ”€โ”€ unit/                     # โšก Unit tests (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ telemetry/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ metrics.test.ts   # Prometheus metrics tests (36 tests)
โ”‚   โ”‚   โ”œโ”€โ”€ health.test.ts        # Health check tests (30 tests)
โ”‚   โ”‚   โ””โ”€โ”€ backpressure.test.ts  # Backpressure tests (33 tests)
โ”‚   โ””โ”€โ”€ security/                 # โšก Security test suite (v3.2.0)
โ”‚       โ”œโ”€โ”€ injection.test.ts     # Injection prevention (36 tests)
โ”‚       โ”œโ”€โ”€ dos.test.ts           # DoS protection (28 tests)
โ”‚       โ”œโ”€โ”€ fuzzing.test.ts       # Fuzzing tests (24 tests)
โ”‚       โ””โ”€โ”€ bounds.test.ts        # Bounds testing (31 tests)
โ”œโ”€โ”€ dist/                         # Compiled JavaScript
โ”œโ”€โ”€ docs/                         # Documentation
โ”‚   โ”œโ”€โ”€ README.md                 # โšก Documentation index (v3.2.0)
โ”‚   โ”œโ”€โ”€ ACCELERATION_ARCHITECTURE.md  # Multi-tier architecture guide
โ”‚   โ”œโ”€โ”€ BUILD_GUIDE.md
โ”‚   โ”œโ”€โ”€ DEPLOYMENT_PLAN.md
โ”‚   โ”œโ”€โ”€ IMPLEMENTATION_PLAN.md
โ”‚   โ”œโ”€โ”€ PRODUCT_SPECIFICATION.md
โ”‚   โ”œโ”€โ”€ SPRINT_9_PLAN.md          # โšก Sprint 9 planning (v3.2.0)
โ”‚   โ”œโ”€โ”€ STYLE_GUIDE.md
โ”‚   โ”œโ”€โ”€ TEST_GUIDE.md
โ”‚   โ”œโ”€โ”€ TEST_VERIFICATION_PLAN.md
โ”‚   โ”œโ”€โ”€ BENCHMARKS.md
โ”‚   โ”œโ”€โ”€ code-review/              # โšก Code review reports (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ CODE_REVIEW.md
โ”‚   โ”‚   โ”œโ”€โ”€ CODE_REVIEW_ANALYSIS.md
โ”‚   โ”‚   โ””โ”€โ”€ CODE_QUALITY_IMPROVEMENTS.md
โ”‚   โ”œโ”€โ”€ planning/                 # โšก Planning documents (v3.2.0)
โ”‚   โ”‚   โ”œโ”€โ”€ IMPLEMENTATION_PLAN_VERIFICATION.md
โ”‚   โ”‚   โ”œโ”€โ”€ REFACTORING_PLAN.md
โ”‚   โ”‚   โ””โ”€โ”€ PROJECT_HISTORY.md
โ”‚   โ””โ”€โ”€ pull-requests/            # โšก PR documentation (v3.2.0)
โ”‚       โ”œโ”€โ”€ PR_DESCRIPTION.md
โ”‚       โ””โ”€โ”€ PR_TASK_19.md
โ”œโ”€โ”€ .github/
โ”‚   โ”œโ”€โ”€ workflows/ci.yml
โ”‚   โ””โ”€โ”€ ISSUE_TEMPLATE/
โ”œโ”€โ”€ CHANGELOG.md
โ”œโ”€โ”€ CONTRIBUTING.md
โ”œโ”€โ”€ SECURITY.md
โ”œโ”€โ”€ LICENSE
โ””โ”€โ”€ package.json

๐Ÿงช Development

# Build TypeScript
npm run build

# Build WASM modules
npm run build:wasm

# Build everything
npm run build:all

# Run tests
npm test

# Run server
npm start

# Development mode
npm run dev

๐Ÿ“š Documentation

Core Documentation

Code Quality & Review

Development Guides

Project Management

๐Ÿค Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

Quick Contribution Guide

  1. Fork the repository

  2. Create a feature branch (git checkout -b feature/amazing-feature)

  3. Make your changes

  4. Run tests (npm test)

  5. Commit your changes (git commit -m 'feat: add amazing feature')

  6. Push to the branch (git push origin feature/amazing-feature)

  7. Open a Pull Request

๐Ÿ”’ Security

See SECURITY.md for security policy and vulnerability reporting.

๐Ÿ› Troubleshooting

Worker Pool Issues

Workers Fail to Initialize

Symptoms:

[ERROR] Failed to create worker: Error: worker_threads not available
[ERROR] WorkerPool not initialized

Solutions:

  1. Verify Node.js version:

    node --version  # Must be v18.0.0 or higher
  2. Check worker_threads support:

    // test-workers.js
    try {
      const { Worker } = require('worker_threads');
      console.log('โœ“ worker_threads available');
    } catch (err) {
      console.error('โœ— worker_threads not available:', err.message);
    }
  3. Rebuild native modules (if needed):

    npm rebuild
    npm install
  4. Platform-specific issues:

    • Docker: Ensure Node.js base image is v18+

    • WSL/Windows: May need --experimental-worker flag (Node <16)

    • Alpine Linux: Use node package, not nodejs-current

Worker Crashes Repeatedly

Symptoms:

[WARN] Worker exited unexpectedly { workerId: 'worker-0', exitCode: 1 }
[ERROR] Worker terminated due to reaching memory limit

Solutions:

  1. Enable debug logging:

    LOG_LEVEL=debug npm start
  2. Increase Node.js memory limit:

    node --max-old-space-size=4096 dist/index-wasm.js
  3. Reduce worker count:

    MAX_WORKERS=2 npm start
  4. Check for WASM corruption:

    # Rebuild WASM modules
    cd wasm
    npm install
    npx gulp
    cd ..
    npm run generate:hashes
  5. Monitor worker health:

    ENABLE_PERF_LOGGING=true npm start
    # Watch for patterns in worker exits

Operations Timeout

Symptoms:

[ERROR] Operation timed out after 30000ms
[ERROR] Task queue full, operation rejected

Solutions:

  1. Increase operation timeout:

    OPERATION_TIMEOUT=60000 npm start
  2. Increase task timeout:

    TASK_TIMEOUT=60000 npm start
  3. Check input size (may be too large):

    • Maximum matrix size: 1000ร—1000 (configurable via MAX_MATRIX_SIZE)

    • Maximum array length: 100,000 (configurable via MAX_ARRAY_LENGTH)

  4. Monitor worker pool status:

    ENABLE_PERF_LOGGING=true npm start
    # Check for: "Worker pool at capacity"
  5. Scale up workers:

    MIN_WORKERS=4 MAX_WORKERS=8 npm start

Worker Pool Not Scaling

Symptoms:

[DEBUG] Pool empty, creating worker on-demand
[INFO] WorkerPool initialized successfully { activeWorkers: 0 }

Solutions:

  1. Verify MIN_WORKERS configuration:

    # Set MIN_WORKERS=0 for auto-scaling
    MIN_WORKERS=0 npm start
    
    # Or keep workers warm
    MIN_WORKERS=2 npm start
  2. Adjust idle timeout:

    # Workers terminate after 60s idle by default
    WORKER_IDLE_TIMEOUT=120000 npm start  # 2 minutes
  3. Monitor scaling behavior:

    LOG_LEVEL=debug npm start
    # Look for: "Pool empty, creating worker on-demand"
    # Look for: "Terminating idle worker"

WASM Issues

WASM Integrity Verification Fails

Symptoms:

[ERROR] WASM integrity verification failed
[ERROR] Hash mismatch for wasm/build/release.wasm

Solutions:

  1. Rebuild WASM modules:

    cd wasm
    npm install
    npx gulp
    cd ..
  2. Regenerate hash manifest:

    npm run generate:hashes
  3. Disable integrity checks (development only):

    DISABLE_WASM_INTEGRITY=true npm start
  4. Verify file permissions:

    ls -l wasm/build/*.wasm
    # Should be readable by current user

WASM Module Not Loading

Symptoms:

[ERROR] Failed to load WASM module
[WARN] WASM not initialized, falling back to mathjs

Solutions:

  1. Check WASM files exist:

    ls wasm/build/
    # Should contain: release.wasm, debug.wasm
  2. Rebuild from scratch:

    cd wasm
    rm -rf node_modules build
    npm install
    npx gulp
    cd ..
  3. Verify AssemblyScript toolchain:

    cd wasm
    npx asc --version
    # Should show AssemblyScript compiler version
  4. Check Node.js WASM support:

    // test-wasm.js
    try {
      new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]));
      console.log('โœ“ WASM supported');
    } catch (err) {
      console.error('โœ— WASM not supported:', err.message);
    }

Acceleration Not Working

Check server startup logs:

MathJS MCP Server (Multi-tier Accelerated) running on stdio
Acceleration Status: 0% ops use acceleration  โ† Should increase with usage

Common Issues:

  1. Input sizes too small - Acceleration only activates above thresholds:

    • WASM: 10ร—10+ matrices, 100+ elements

    • Workers: 100ร—100+ matrices, 100k+ elements

  2. WASM not initialized - Check startup logs:

    [INFO] WASM modules initialized successfully
    [INFO] WorkerPool initialized successfully { activeWorkers: 2 }
  3. Using wrong entry point:

    # โœ“ Correct (with acceleration)
    node dist/index-wasm.js
    
    # โœ— Wrong (mathjs only)
    node dist/index.js

Performance Not Improving

  1. Verify using index-wasm.js not index.js

  2. Check input sizes exceed acceleration thresholds (see docs/BENCHMARKS.md)

  3. Monitor routing statistics in logs:

    ENABLE_PERF_LOGGING=true npm start
    # Look for: "WASM calls: 70%, mathjs calls: 30%"
  4. Ensure worker threads are available (node --version >= 18)

  5. Check system resources:

    # Monitor CPU/memory during operations
    top -p $(pgrep -f "node.*index-wasm")

Integration Tests Failing

npm install
npm run build:all
npm test

Expected output:

โœ“ All integration tests passed!
โœ“ WASM integration working correctly
Success rate: 100.0%

Common failures:

  1. WASM modules not built:

    npm run build:wasm
    npm run generate:hashes
  2. TypeScript compilation errors:

    npm run type-check
    # Fix any errors before running tests
  3. Node.js version too old:

    node --version  # Must be >=18.0.0
    nvm install 18  # If using nvm

Memory Issues

High Memory Usage

Symptoms:

[WARN] Memory usage high: 1.2GB
[ERROR] JavaScript heap out of memory

Solutions:

  1. Scale down workers:

    MIN_WORKERS=0 MAX_WORKERS=2 npm start
  2. Enable auto-scaling to zero:

    MIN_WORKERS=0 WORKER_IDLE_TIMEOUT=30000 npm start
  3. Increase Node.js heap:

    node --max-old-space-size=2048 dist/index-wasm.js
  4. Disable performance tracking:

    DISABLE_PERF_TRACKING=true npm start

Memory Leaks

Symptoms:

Memory usage increases over time
Workers not being garbage collected

Solutions:

  1. Monitor worker lifecycle:

    LOG_LEVEL=debug npm start
    # Look for: "Terminating idle worker"
    # Check: workers.size in logs
  2. Force garbage collection (debugging):

    node --expose-gc dist/index-wasm.js
  3. Reduce worker idle timeout:

    WORKER_IDLE_TIMEOUT=30000 npm start  # 30 seconds

Getting Help

If you're still experiencing issues:

  1. Enable debug logging:

    LOG_LEVEL=debug npm start 2>&1 | tee debug.log
  2. Collect system information:

    node --version
    npm --version
    uname -a  # Linux/macOS
    systeminfo  # Windows
  3. Run diagnostic:

    npm run type-check
    npm test
    npm run lint
  4. Create an issue:

Performance Tuning

For optimal performance, see:

  • Benchmark documentation: docs/BENCHMARKS.md

  • Threshold configuration: src/wasm-wrapper.ts:39-74

  • Worker pool tuning: Environment variables section above

Expected: 11/11 tests passing

๐Ÿ”ง Configuration

The server supports several environment variables for customization:

# Logging configuration
LOG_LEVEL=debug|info|warn|error    # Control log verbosity (default: info)

# Acceleration tier configuration
ENABLE_GPU=false                   # Enable WebGPU acceleration tier (default: false, not yet implemented)
ENABLE_WORKERS=true                # Enable WebWorkers acceleration tier (default: true)
ENABLE_WASM=true                   # Enable WASM acceleration tier (default: true)
NOTIFY_DEGRADATION=true            # Log when acceleration tier degradation occurs (default: true)

# Performance tuning
DISABLE_PERF_TRACKING=true         # Disable performance tracking for minimal overhead
ENABLE_PERF_LOGGING=true           # Enable periodic performance statistics logging

# Worker pool configuration
MIN_WORKERS=0                      # Minimum workers to keep alive (default: 2, set to 0 for auto-scaling)
MAX_WORKERS=8                      # Maximum concurrent workers (default: CPU cores - 1)
WORKER_IDLE_TIMEOUT=60000          # Idle timeout in ms before worker termination (default: 60000)
TASK_TIMEOUT=30000                 # Task timeout in milliseconds (default: 30000)

# Security limits
MAX_MATRIX_SIZE=1000               # Maximum matrix dimension (1000ร—1000)
MAX_ARRAY_LENGTH=100000            # Maximum array length for statistics
MAX_EXPRESSION_LENGTH=10000        # Maximum expression length (characters)
MAX_NESTING_DEPTH=50               # Maximum parentheses/bracket nesting
OPERATION_TIMEOUT=30000            # Operation timeout in milliseconds

๐Ÿ› ๏ธ Development

Code Quality Tools

# Linting and formatting
npm run lint              # Run ESLint on TypeScript files
npm run lint:fix          # Auto-fix linting issues
npm run format            # Format code with Prettier
npm run format:check      # Check code formatting
npm run type-check        # Run TypeScript type checking

# Testing
npm run test             # Run integration tests
npm run test:unit        # Run unit tests (Vitest)
npm run test:coverage    # Generate test coverage report

Quality Features

  • ESLint: TypeScript + JSDoc validation

  • Prettier: Consistent code formatting

  • Husky: Git hooks for pre-commit quality checks

  • Vitest: Modern, fast testing framework

  • 100% JSDoc Coverage: All public APIs documented

๐Ÿ“„ License

ISC License - see LICENSE file for details.

๐Ÿ™ Acknowledgments

  • mathjs - Excellent JavaScript math library

  • AssemblyScript - TypeScript-to-WASM compiler

  • MCP SDK - Model Context Protocol implementation


Made with โค๏ธ by the math-mcp contributors

-
security - not tested
A
license - permissive license
-
quality - not tested

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/danielsimonjr/math-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server