Math MCP Server
Math MCP Server
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.
Related MCP server: MathJS Calculator MCP Server
✨ 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/jsonHealth 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
backpressureeventsAutomatic 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
evaluate - Evaluate mathematical expressions with variables
simplify - Simplify algebraic expressions
derivative - Calculate derivatives
solve - Solve equations
matrix_operations ⚡ - Matrix operations (WASM-accelerated)
statistics ⚡ - Statistical calculations (WASM-accelerated)
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 testVerify 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\*.wasmExpected 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 evaluatescope(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 differentiatevariable(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 solvevariable(string): Variable to solve for
Examples:
solve("x^2 - 4 = 0", "x") // Solutions for x
solve("2*x + 3 = 7", "x") // x = 25. matrix_operations (Multi-Tier Accelerated ⚡⚡⚡)
Perform matrix operations with intelligent multi-tier acceleration.
Parameters:
operation(string): Operation to performmultiply,inverse,determinant,transpose,eigenvalues,add,subtract
matrix_a(string): First matrix in JSON formatmatrix_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 operationmean,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]") // 247. 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 → mathjsIf 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) │ │ │
│ │ └──────────┘ │ │
└───────┴──────────┴──────────────┴────────┘
↓
ResultArchitecture 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
docs/README.md - ⚡ NEW v3.2.0: Complete documentation index
ACCELERATION_ARCHITECTURE.md - Multi-tier acceleration architecture guide
BUILD_GUIDE.md - Build and compilation guide
DEPLOYMENT_PLAN.md - Production deployment instructions
IMPLEMENTATION_PLAN.md - Implementation strategy and architecture
SPRINT_9_PLAN.md - ⚡ NEW v3.2.0: Sprint 9 observability & security features
PRODUCT_SPECIFICATION.md - Complete product specification
Code Quality & Review
docs/code-review/CODE_REVIEW.md - ⚡ NEW v3.2.0: Initial code review
docs/code-review/CODE_REVIEW_ANALYSIS.md - ⚡ NEW v3.2.0: Detailed analysis
docs/code-review/CODE_QUALITY_IMPROVEMENTS.md - ⚡ NEW v3.2.0: Quality tracking
Development Guides
STYLE_GUIDE.md - Coding standards and conventions
TEST_GUIDE.md - Testing procedures and guidelines
TEST_VERIFICATION_PLAN.md - Test verification strategy
BENCHMARKS.md - Performance benchmarks and results
Project Management
docs/planning/IMPLEMENTATION_PLAN_VERIFICATION.md - ⚡ NEW v3.2.0: Verification report
docs/planning/REFACTORING_PLAN.md - ⚡ COMPLETE v3.5.0: All 7 sprints done (44% code reduction)
docs/planning/PROJECT_HISTORY.md - ⚡ NEW v3.2.0: Project evolution timeline
CHANGELOG.md - Version history and changes
CONTRIBUTING.md - Contribution guidelines
SECURITY.md - Security policy
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
Quick Contribution Guide
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Make your changes
Run tests (
npm test)Commit your changes (
git commit -m 'feat: add amazing feature')Push to the branch (
git push origin feature/amazing-feature)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 initializedSolutions:
Verify Node.js version:
node --version # Must be v18.0.0 or higherCheck 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); }Rebuild native modules (if needed):
npm rebuild npm installPlatform-specific issues:
Docker: Ensure Node.js base image is v18+
WSL/Windows: May need
--experimental-workerflag (Node <16)Alpine Linux: Use
nodepackage, notnodejs-current
Worker Crashes Repeatedly
Symptoms:
[WARN] Worker exited unexpectedly { workerId: 'worker-0', exitCode: 1 }
[ERROR] Worker terminated due to reaching memory limitSolutions:
Enable debug logging:
LOG_LEVEL=debug npm startIncrease Node.js memory limit:
node --max-old-space-size=4096 dist/index-wasm.jsReduce worker count:
MAX_WORKERS=2 npm startCheck for WASM corruption:
# Rebuild WASM modules cd wasm npm install npx gulp cd .. npm run generate:hashesMonitor 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 rejectedSolutions:
Increase operation timeout:
OPERATION_TIMEOUT=60000 npm startIncrease task timeout:
TASK_TIMEOUT=60000 npm startCheck 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)
Monitor worker pool status:
ENABLE_PERF_LOGGING=true npm start # Check for: "Worker pool at capacity"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:
Verify MIN_WORKERS configuration:
# Set MIN_WORKERS=0 for auto-scaling MIN_WORKERS=0 npm start # Or keep workers warm MIN_WORKERS=2 npm startAdjust idle timeout:
# Workers terminate after 60s idle by default WORKER_IDLE_TIMEOUT=120000 npm start # 2 minutesMonitor 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.wasmSolutions:
Rebuild WASM modules:
cd wasm npm install npx gulp cd ..Regenerate hash manifest:
npm run generate:hashesDisable integrity checks (development only):
DISABLE_WASM_INTEGRITY=true npm startVerify 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 mathjsSolutions:
Check WASM files exist:
ls wasm/build/ # Should contain: release.wasm, debug.wasmRebuild from scratch:
cd wasm rm -rf node_modules build npm install npx gulp cd ..Verify AssemblyScript toolchain:
cd wasm npx asc --version # Should show AssemblyScript compiler versionCheck 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 usageCommon Issues:
Input sizes too small - Acceleration only activates above thresholds:
WASM: 10×10+ matrices, 100+ elements
Workers: 100×100+ matrices, 100k+ elements
WASM not initialized - Check startup logs:
[INFO] WASM modules initialized successfully [INFO] WorkerPool initialized successfully { activeWorkers: 2 }Using wrong entry point:
# ✓ Correct (with acceleration) node dist/index-wasm.js # ✗ Wrong (mathjs only) node dist/index.js
Performance Not Improving
Verify using
index-wasm.jsnotindex.jsCheck input sizes exceed acceleration thresholds (see docs/BENCHMARKS.md)
Monitor routing statistics in logs:
ENABLE_PERF_LOGGING=true npm start # Look for: "WASM calls: 70%, mathjs calls: 30%"Ensure worker threads are available (
node --version >= 18)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 testExpected output:
✓ All integration tests passed!
✓ WASM integration working correctly
Success rate: 100.0%Common failures:
WASM modules not built:
npm run build:wasm npm run generate:hashesTypeScript compilation errors:
npm run type-check # Fix any errors before running testsNode.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 memorySolutions:
Scale down workers:
MIN_WORKERS=0 MAX_WORKERS=2 npm startEnable auto-scaling to zero:
MIN_WORKERS=0 WORKER_IDLE_TIMEOUT=30000 npm startIncrease Node.js heap:
node --max-old-space-size=2048 dist/index-wasm.jsDisable performance tracking:
DISABLE_PERF_TRACKING=true npm start
Memory Leaks
Symptoms:
Memory usage increases over time
Workers not being garbage collectedSolutions:
Monitor worker lifecycle:
LOG_LEVEL=debug npm start # Look for: "Terminating idle worker" # Check: workers.size in logsForce garbage collection (debugging):
node --expose-gc dist/index-wasm.jsReduce worker idle timeout:
WORKER_IDLE_TIMEOUT=30000 npm start # 30 seconds
Getting Help
If you're still experiencing issues:
Enable debug logging:
LOG_LEVEL=debug npm start 2>&1 | tee debug.logCollect system information:
node --version npm --version uname -a # Linux/macOS systeminfo # WindowsRun diagnostic:
npm run type-check npm test npm run lintCreate an issue:
Include: Debug logs, system info, steps to reproduce
Attach: Relevant error messages
Performance Tuning
For optimal performance, see:
Benchmark documentation:
docs/BENCHMARKS.mdThreshold configuration:
src/wasm-wrapper.ts:39-74Worker 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 reportQuality 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
Recent updates
See CHANGELOG.md for recent changes — telemetry init fix, 8MB JSON response cap, and worker-pool ready-gate.
Made with ❤️ by the math-mcp contributors
Available Tools
7 toolsderivativeA
Calculate the derivative of an expression with respect to a variable. Example: derivative('x^2', 'x') returns '2*x'
| Name | Required | Description | Default |
|---|---|---|---|
| variable | Yes | Variable to differentiate with respect to | |
| expression | Yes | Mathematical expression |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, and the description only covers basic functionality. It lacks disclosure of limitations, error handling, or behavior for complex expressions (e.g., multivariate or implicit differentiation).
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise: one sentence and an example. Every part is necessary and front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple tool with no output schema, the description provides a basic understanding and example. However, it does not explain return format or behavior for edge cases, leaving some gaps.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Both parameters have schema descriptions. The description adds value with an example showing correct parameter order and usage, clarifying syntax beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool computes derivatives of expressions with respect to a variable, and the example reinforces this. It distinguishes from sibling tools like solve or simplify by focusing solely on differentiation.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage through the example but does not explicitly state when to use this tool versus alternatives like evaluate or simplify. No exclusions or context are provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
evaluateC
Evaluate a mathematical expression. Supports arithmetic, algebra, calculus, matrices, and more. Example: '2 + 2', 'sqrt(16)', 'derivative(x^2, x)', 'det([[1,2],[3,4]])'
| Name | Required | Description | Default |
|---|---|---|---|
| scope | No | Optional variables to use in the expression (e.g., {x: 5, y: 10}) | |
| expression | Yes | Mathematical expression to evaluate |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, and the description does not disclose any behavioral traits such as side effects, performance considerations, or error handling. The tool is presented as a black box.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise, consisting of one declarative sentence followed by examples. It front-loads the core purpose and is free of unnecessary words, though the examples could be more systematically structured.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
There is no output schema, yet the description does not mention return types or format. The nested 'scope' object lacks explanation of structure. Given the complexity and multiple siblings, the description is insufficient for an agent to fully understand the tool's capabilities and boundaries.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has 100% coverage, describing both parameters. The description adds a concrete example for 'scope', clarifying its usage. However, no additional semantics are provided for 'expression' beyond what the schema offers.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states 'Evaluate a mathematical expression' and lists examples covering arithmetic, calculus, matrices, etc. However, sibling tools like 'derivative' and 'matrix_operations' overlap with the claimed capabilities, creating ambiguity about when to use this tool versus more specific tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance is provided on when to use this tool versus siblings. There are no conditions, limitations, or examples of appropriate use cases, leaving the agent to infer from context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
matrix_operationsB
Perform matrix operations like multiply, inverse, determinant, transpose, eigenvalues. Matrices should be in array format like [[1,2],[3,4]].
| Name | Required | Description | Default |
|---|---|---|---|
| matrix_a | Yes | First matrix in JSON array format (e.g., '[[1,2],[3,4]]') | |
| matrix_b | No | Second matrix (for operations that require two matrices) | |
| operation | Yes | Matrix operation to perform |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden, yet it only mentions input formatting, not output shapes, constraints (e.g., square matrices for inverse/determinant/eigenvalues), or error behavior. It does not contradict annotations, but it is not transparent about the operation's behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two sentences, front-loaded with the core purpose and immediately followed by an input format example. No wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Despite having no output schema, the description does not describe return values or per-operation output differences (e.g., determinant returns a scalar, eigenvalues return a list). For a multi-operation tool with several operations and a required schema, the description leaves significant gaps for an agent trying to interpret results.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema descriptions cover all three parameters at 100%, and the description's matrix-format example is already present in the schema ('e.g., [[1,2],[3,4]]'). It adds no new parameter-level meaning beyond what the schema provides, so it meets the baseline.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description specifies 'Perform matrix operations' and lists concrete operations (multiply, inverse, determinant, transpose, eigenvalues), clearly identifying the action and resource. The sibling tools are non-matrix math utilities, so the matrix focus distinguishes it.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides an input-format guideline ('Matrices should be in array format like [[1,2],[3,4]]'), which is helpful, but it never explicitly states when to prefer this tool over alternatives or when not to use it. The difference from siblings is implied by the matrix-specific language rather than spelled out.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
simplifyC
Simplify a mathematical expression. Example: '2 * x + x' becomes '3 * x'
| Name | Required | Description | Default |
|---|---|---|---|
| rules | No | Optional simplification rules | |
| expression | Yes | Mathematical expression to simplify |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, yet the description discloses no behavioral traits beyond the basic operation. It does not mention whether it handles various expression types, side effects, or output format.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence plus an example, which is concise and front-loaded. Every part is relevant, though it could be slightly more informative.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the lack of output schema and annotations, the description is incomplete. It does not explain the return value or provide sufficient context for the two parameters.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the baseline is 3. The description does not add meaning beyond the schema's parameter descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool simplifies a mathematical expression and provides an example, making its purpose unambiguous. It implicitly distinguishes from sibling tools like derivative or evaluate.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No guidance on when to use this tool versus alternatives such as evaluate or solve. The description lacks context for appropriate usage.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
solveA
Solve an equation. Example: solve('x^2 - 4 = 0', 'x') returns the solutions
| Name | Required | Description | Default |
|---|---|---|---|
| equation | Yes | Equation to solve | |
| variable | Yes | Variable to solve for |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Without annotations, the description carries full burden but only provides a single example. It does not specify the nature of solutions, error handling, or limitations, leaving behavioral ambiguity.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise with one sentence and an example, no extra words, front-loaded with the core purpose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Adequately states purpose and provides an example, but lacks details on return value structure, supported equation types, or error scenarios, making it minimally complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema already describes parameters, but the description adds a concrete example demonstrating expected input format and syntax, adding value beyond the schema's generic descriptions.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states 'Solve an equation' and provides a concrete example showing usage and output, effectively distinguishing it from sibling tools like derivative and simplify.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit guidance on when to use this tool versus alternatives. The example illustrates usage but does not set boundaries or mention when not to use solve.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
statisticsA
Calculate statistical values like mean, median, mode (returns array), std (standard deviation), variance, min, max, sum, product.
| Name | Required | Description | Default |
|---|---|---|---|
| data | Yes | Data array in JSON format (e.g., '[1, 2, 3, 4, 5]') | |
| operation | Yes | Statistical operation to perform. Note: mode returns an array (single mode: [value], multiple modes: [value1, value2]) |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description bears the full burden of behavioral disclosure. It only notes that mode returns an array, which is already stated in the schema's operation description. It does not clarify return types for other operations, error handling, or edge cases like empty data, so transparency is limited.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, efficient sentence that clearly lists the operation names. It is front-loaded with the verb 'Calculate' and leaves no unnecessary words. Every part of the sentence contributes to understanding the tool's purpose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (2 parameters, enum, no output schema), the description is mostly complete. It lists all supported operations and highlights mode's array return. However, it could mention that other operations return numeric values or that data must be a JSON array string, but the schema covers the latter, so the overall context is adequate.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the baseline is 3. The description does not add significant meaning beyond the schema; it lists operation names that are already in the enum and does not elaborate on the data format beyond what the schema states. Thus it provides no extra value.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool calculates statistical values and enumerates the specific operations (mean, median, mode, etc.), which is a specific verb+resource. It distinguishes itself from sibling tools like evaluate, simplify, and derivative, which handle other types of math operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage for statistical calculations by listing supported operations, but it does not explicitly state when to use this tool over alternatives or provide exclusions. No sibling alternatives are mentioned, so guidance is implied rather than explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
unit_conversionA
Convert between units. Example: convert '5 inches to cm' or '100 fahrenheit to celsius'
| Name | Required | Description | Default |
|---|---|---|---|
| value | Yes | Value with unit (e.g., '5 inches', '100 km/h') | |
| target_unit | Yes | Target unit to convert to (e.g., 'cm', 'mi/h'). Use compound forms like 'mi/h' / 'km/h' for speed; 'mph'/'kph'/'knot' are not recognized (same as mathjs). |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, and the description does not disclose any behavioral traits beyond the conversion operation. It does not mention side effects (likely none), permissions, or error handling, but for a simple conversion tool, this is acceptable. No contradictions with annotations as none exist.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is very concise at one sentence plus an example, lacking any structural elements like headings or bullet points. However, it efficiently conveys the core purpose, earning a high score for brevity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity and complete schema, the description is mostly adequate. However, it does not explain the return format (e.g., numeric value with unit string) or acknowledge potential limitations (e.g., unit compatibility), leaving some gap for the agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with clear descriptions for both parameters (value and target_unit). The description adds an example but no additional semantic detail beyond what the schema provides, so baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states 'Convert between units' and provides concrete examples ('5 inches to cm' and '100 fahrenheit to celsius'), making the tool's purpose unambiguous. It distinguishes from sibling tools like derivative or solve which handle different mathematical operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives examples of how to use the tool but does not explicitly state when to prefer it over alternatives or when not to use it. There is no guidance on unsupported conversions or edge cases, leaving the agent to infer usage from context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
7 tool updates
v4.1.3- First observed
derivative - First observed
evaluate - First observed
matrix_operations - First observed
simplify - First observed
solve - First observed
statistics - First observed
unit_conversion
TDQS
Scored across 7 tools
The tools are mostly distinct in their specialized purposes (derivative, solve, matrix_operations, statistics, unit_conversion), but the 'evaluate' tool is a catch-all that can also handle calculus and matrices, creating ambiguity with the specialized tools. An agent might struggle to decide whether to use 'evaluate' or a dedicated tool for a given task.
Naming is consistently lowercase and uses underscores for multi-word names, but the pattern mixes verbs (evaluate, simplify, solve) and nouns (derivative, matrix_operations, statistics, unit_conversion). This is readable but not a uniform verb_noun convention.
With 7 tools, the server is well-scoped for a math toolkit, covering algebra, calculus, linear algebra, statistics, and unit conversion. Each tool has a clear domain, and the count is within the ideal range.
The server covers core math operations well (evaluate, simplify, derivative, solve, matrices, statistics, conversions), but integration (antiderivatives) is a notable missing calculus operation. This is a minor gap that agents might work around with 'evaluate' if supported, but it's not explicitly included.
Maintenance
Related MCP Connectors
Precision math engine for AI agents. 203 exact methods. Zero hallucination.
Exact arithmetic, algebra, calculus, physics, chemistry and finance with a checkable formula.
Free deterministic tools for math, data transforms, dates, text, statistics, finance, and units.
Related MCP Servers
- AlicenseAqualityCmaintenanceProvides 21 mathematical tools across 6 domains including basic calculations, array operations, statistics, financial mathematics, linear algebra, and calculus. Supports batch execution for complex multi-step workflows with intelligent dependency resolution.215MIT
- AlicenseBqualityDmaintenanceProvides mathematical calculation capabilities using MathJS, enabling expression evaluation and derivative calculation.25 npmMIT
- AlicenseNot gradedqualityAmaintenanceEvaluate, simplify, and differentiate mathematical expressions via MCP. Provides a single tool for arithmetic, algebra, and symbolic differentiation with secure sandboxing.136 npm2Apache 2.0
- AlicenseAqualityBmaintenanceEnables reliable engineering and scientific computation through tools for exact arithmetic, unit-aware formulas, calculus, linear algebra, statistics, uncertainty propagation, and physical constants, all executed safely in reproducible subprocesses.8MIT