Labsco
islobodan logo

Cruncher MCP

from islobodan

The Scientific Calculator built as a Model Context Protocol (MCP) server

πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedFreeQuick setup

Cruncher: The Scientific Calculator MCP Server

A powerful scientific calculator for your AI assistant, built as a Model Context Protocol (MCP) server. Cruncher allows compatible AI clients (like Claude Desktop) to perform complex mathematical calculations, handle memory, perform statistical analysis, and access scientific constants with a simple, secure, and standardized interface.

🌟 The Purity Promise (Zero Dependencies)

Cruncher is built as a highly educational, extremely lightweight tool. It accomplishes powerful features without pulling in any heavy external libraries (no mathjs, no zod, no @modelcontextprotocol/sdk). Everything is handled using native Node.js capabilities:

  • Safe Expression Evaluation: Instead of relying on mathjs or dangerous eval(), Cruncher uses new Function() guarded by a strict whitelist Regex that guarantees only numbers and math operators can pass.
  • Input Validation: Instead of heavy schema libraries like Zod, a custom recursive validation function rigidly enforces AI inputs against JSON Schemas directly.
  • Timeout Protection: Instead of complex process managers, it leverages Node.js worker_threads to spawn calculations. If an AI requests a multi-million loop factorial, the main thread easily terminates the worker after a strict timeout (default 3 seconds). This timeout is configurable via the CRUNCHER_TIMEOUT environment variable (in milliseconds), ensuring the server remains responsive even during heavy computational loads.
  • Floating-Point Accuracy: Instead of using decimal.js, it solves the classic JS math error (0.1 + 0.2 = 0.30000000000000004) via dynamic integer-scaling logic under the hood.

πŸ“š An Educational Approach to MCP

This project serves as an excellent learning resource for developers looking to understand the Model Context Protocol (MCP) deeply. Because it deliberately avoids using the official @modelcontextprotocol/sdk, the entire implementation of the MCP protocol, JSON-RPC message handling, input validations, and error formatting is exposed in plain JavaScript.

Reading through cruncher.js provides unparalleled, transparent insight into exactly how an MCP server communicates over stdio, parses incoming requests (initialize, tools/list, tools/call), and responds back to the AI client-demystifying the "magic" that SDKs usually hide away.

What is the Model Context Protocol?

The Model Context Protocol (MCP) is an open standard that allows AI applications to securely connect with external data sources and tools. Think of it as a universal API for AI. By implementing Cruncher as an MCP server, any AI that understands MCP can instantly gain powerful, built-in calculator capabilities without custom integrations.

✨ Features

Cruncher provides a comprehensive set of calculator functions built completely from scratch without heavy dependencies:

  • Robust Architecture:
    • Zero Dependencies: Relies purely on Node.js standard libraries.
    • Strict Input Validation: Custom schema validator prevents AI hallucinations and invalid data.
    • Infinite Loop Protection: Utilizes Node.js worker_threads with a 3-second strict timeout to prevent complex calculations from freezing the server.
    • Accurate Decimal Math: Uses an integer-scaling approach to prevent classic JS floating-point errors (e.g., 0.1 + 0.2 === 0.3).
  • Tiered Tool Exposure: Three tiers (minimal, standard default, full) to optimize context token usage.
  • Basic Arithmetic: Addition, Subtraction, Multiplication, Division, Modulo.
  • Expression Evaluation: Safely compute entire plain-text math strings (e.g. (5 + 3) * 10 / 2).
  • Power & Roots: Exponentiation (a^b), Square Root.
  • Number Theory: Factorial (n!).
  • Trigonometry: Sine, Cosine, Tangent, Arcsine (asin), Arccosine (acos), and Arctangent (atan) (with support for degrees and radians).
  • Logarithms: Base-10 Logarithm and Natural Logarithm (ln).
  • Statistical Functions: Sum, Average, Median, Min, Max, Range, Count, Variance, and Standard Deviation for arrays of numbers.
  • Percentage Functions: Percentage-of, percentage-change, and reverse-percentage calculations.
  • Unit Conversion: 80+ conversions across 8 categories (length, weight, temperature, area, volume, time, speed, digital_storage).
  • Convenience Functions: Absolute Value.
  • Constants: Easy access to Math (pi, e, tau, phi, sqrt2, euler_mascheroni), Physics (c, g, G, h, k, R), and Chemistry constants (NA, e_charge, m_e, m_p).
  • Memory Functions: M+, M-, MR (Memory Recall), and MC (Memory Clear) - full tier only.

πŸ“‹ Available Tools

Cruncher exposes its functions as individual MCP tools. Here is the full list:

Tool NameDescriptionArguments
Basic Arithmetic
evaluate_expressionEvaluates a plain text math expression (e.g. (5 + 3) * 10 / 2).expression (string)
addAdds two numbers (a + b).a (number), b (number)
subtractSubtracts the second number from the first (a - b).a (number), b (number)
multiplyMultiplies two numbers (a * b).a (number), b (number)
divideDivides the first number by the second (a / b).a (number), b (number)
moduloCalculates the remainder (a mod b).a (number), b (number)
Power & Roots
powerCalculates a raised to the power of b (a^b).base (number), exponent (number)
sqrtCalculates the square root of a value.value (number)
Number Theory
factorialCalculates the factorial of a non-negative integer (n!).n (number, non-negative integer)
Unit Conversion
convert_unitConvert between common units. 8 categories, 80+ units.value (number), category (string), from (string), to (string)
Base Conversion (Full Tier)
convert_baseConverts between bases 2, 8, 10, 16.value (string), from_base (2, 8, 10, 16), to_base (2, 8, 10, 16)
Trigonometry
sineCalculates the sine of an angle.angle (number), unit (degrees/radians, optional)
cosineCalculates the cosine of an angle.angle (number), unit (degrees/radians, optional)
tangentCalculates the tangent of an angle.angle (number), unit (degrees/radians, optional)
asinCalculates the inverse sine (arcsine) of a value. Returns an angle.value (number), unit (degrees/radians, optional)
acosCalculates the inverse cosine (arccosine) of a value. Returns an angle.value (number), unit (degrees/radians, optional)
atanCalculates the inverse tangent (arctangent) of a value. Returns an angle.value (number), unit (degrees/radians, optional)
Logarithms
logarithmCalculates the base-10 logarithm of a value.value (number)
natural_logCalculates the natural logarithm (base-e) of a value.value (number)
Statistical Functions
sumCalculates the sum of an array of numbers.numbers (array of numbers)
avgCalculates the average of an array of numbers.numbers (array of numbers)
medianCalculates the median of an array of numbers.numbers (array of numbers)
minFinds the minimum value in an array of numbers.numbers (array of numbers)
maxFinds the maximum value in an array of numbers.numbers (array of numbers)
countCounts the number of elements in an array.numbers (array of numbers)
rangeCalculates the range (max - min) of an array.numbers (array of numbers)
percentileCalculates the value at a given percentile (0-100). Full tier.numbers (array of numbers), percentile (number, 0-100)
varianceVariance of an array. Sample (n-1) or population (n).numbers (array of numbers), population (boolean, optional)
std_devStandard deviation. Sample (n-1) or population (n).numbers (array of numbers), population (boolean, optional)
percentage_ofWhat is X% of Y? e.g., 15% of 200 = 30.percent (number), total (number)
percentage_change% change from A to B. e.g., 50β†’80 = 60%.from (number), to (number)
percentage_reverseX is Y% of what? e.g., 30 is 15% of 200.value (number), percent (number)
Other
absoluteCalculates the absolute value of a number.value (number)
Constants
get_constantReturns the value of a mathematical, physical, or chemical constant.name ("pi", "e", "tau", "phi", "sqrt2", "euler_mascheroni", "c", "g", "G", "h", "k", "R", "NA", "e_charge", "m_e", "m_p")
Memory Functions (Full Tier)
memory_clearClears the calculator memory (MC).(no arguments)
memory_recallRecalls the value stored in memory (MR).(no arguments)
memory_addAdds a value to the current memory (M+).value (number)
memory_subtractSubtracts a value from the current memory (M-).value (number)
Angle Mode (Standard Tier)
set_angle_modeSet global angle mode (default: degrees).unit ("degrees" or "radians")
get_angle_modeGet current angle mode.(no arguments)
Admin Tools (Full Tier)
batchExecute multiple tool calls sequentially.operations (array of {tool, arguments})
cache_clearClear computation cache.(no arguments)
cache_infoShow cache stats.(no arguments)

⛏️ How It Works (For Developers)

Cruncher is a plain Node.js JavaScript application that communicates over standard input/output (stdio). This makes it a lightweight, portable, and secure MCP server. The entire flow for a single tool call looks like this:

  1. Initialization: On startup, the server listens for an initialize request from the MCP client and responds with its capabilities and version info (v1.2.31).
  2. Tool Discovery: The client sends a tools/list request, and the server responds with the full list of available calculator tools and their inputSchema, which defines the required arguments and their types.
  3. Input Validation: Before any tool is executed, the server runs a custom recursive validateArguments function against the tool's inputSchema. This ensures required fields are present, types are correct (number, string, array), enum values are valid, and min/max constraints are respected - all without any external library.
  4. Worker Thread Execution: Once validated, the tool call is handed off to an isolated Node.js worker_thread. This completely protects the main thread (and its stdio communication) from being blocked by a long-running or infinite calculation.
  5. Timeout Protection: A configurable timer (CRUNCHER_TIMEOUT, default 3000ms) watches the worker. If the worker takes too long, the main thread forcefully terminates it via worker.terminate() and returns a -32000 error to the AI client.
  6. Safe Math & Result: The worker executes the handler function using safeMath (integer-scaling) for decimal-safe arithmetic, then posts the result back to the main thread, which formats and writes the final JSON-RPC 2.0 response to stdout.

🀝 Contributing

Contributions are welcome! If you'd like to add a new function, fix a bug, or improve the documentation, please feel free to open an issue or submit a pull request.

πŸ“œ License

This project is licensed under the MIT License.