Skip to main content
Glama
Mathematics MCP Server

Mathematics MCP Server

by tanishra

Mathematics MCP Server ๐Ÿงฎ

A comprehensive FastMCP server providing 22 mathematical operations for AI assistants like Claude.

A Model Context Protocol (MCP) server that provides mathematical operations as tools for AI assistants like Claude. This server enables Claude to perform accurate arithmetic calculations through a standardized interface.

๐Ÿ“‹ Table of Contents

Related MCP server: MCP Mathematics

What is Mathematics MCP Server?

Mathematics MCP Server is a lightweight server that exposes mathematical operations through the Model Context Protocol (MCP). It allows AI assistants to perform precise calculations by calling dedicated tools rather than relying on their internal reasoning capabilities.

Why Use This?

  • Accuracy: Ensures precise mathematical calculations

  • Reliability: Eliminates calculation errors that can occur with AI reasoning

  • Extensibility: Easy to add new mathematical operations

  • Logging: All operations are logged for debugging and audit purposes

Features

  • 22 Mathematical Operations:

    • Basic (8): Addition, subtraction, multiplication, division, modulus, power, square, square root

    • Advanced (2): Factorial, absolute value

    • Logarithms (2): Logarithm (custom base), natural log

    • Trigonometry (3): Sine, cosine, tangent (degree-based)

    • Number Theory (2): GCD, LCM

    • Statistics (3): Mean, median, standard deviation

    • Rounding (2): Ceiling, floor

  • Error Handling: Robust error handling for edge cases (division by zero, negative square roots, etc.)

  • Comprehensive Logging: All operations logged to both file and stderr

  • Type Safety: Built with Pydantic models for input validation

  • MCP Compliant: Fully compatible with the Model Context Protocol standard

How It Works

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Claude Desktop โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ”‚ JSON-RPC over stdio
         โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   FastMCP       โ”‚
โ”‚   Mathematics   โ”‚
โ”‚   MCP Server    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ”‚ Python Functions
         โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Math Operationsโ”‚
โ”‚  (add, subtract,โ”‚
โ”‚   multiply...)  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  1. Claude sends a tool call request via JSON-RPC

  2. FastMCP receives and validates the request

  3. Python functions perform the calculation

  4. Result is returned to Claude in structured format

  5. Logging records the operation for debugging

Installation

Prerequisites

  • Python 3.8 or higher

  • uv package manager (recommended)

Step 1: Clone the Repository

git clone https://github.com/tanishra/math-mcp-server.git
cd mathematics-mcp

Step 2: Install uv (if not already installed)

# On macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# On Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"

# Or using pip
pip install uv

Step 3: Install Dependencies

The project uses pyproject.toml for dependency management:

# Install all dependencies (uv automatically reads pyproject.toml)
uv sync

# Or using pip
pip install -e .

Alternatively, you can install dependencies directly:

uv pip install fastmcp pydantic

Step 4: Test the Server

Using the MCP Inspector (recommended for development):

# This opens an interactive web interface to test your MCP server
uv run fastmcp dev main.py

Or run the server directly:

# This runs the server in production mode
uv run fastmcp run main.py

You should see:

Starting Mathematics MCP Server...

Usage

The MCP Inspector provides a web-based interface to test your server:

uv run fastmcp dev main.py

This will:

  1. Start the MCP server

  2. Open a web interface in your browser

  3. Allow you to test all tools interactively

  4. Show request/response details in real-time

Running the Server in Production Mode

uv run fastmcp run main.py

The server will start and listen for MCP protocol messages on stdin/stdout.

Using with Claude Desktop

See the Integration with Claude Desktop section below.

Integration with Claude Desktop

The easiest way to integrate with Claude Desktop is using the FastMCP installer:

uv run fastmcp install claude-desktop main.py

This command will:

  • Automatically locate your Claude Desktop configuration file

  • Add the Mathematics MCP server configuration

  • Use the correct paths for your system

  • Restart Claude Desktop if needed

Manual Installation (Alternative)

If you prefer to configure manually or the automatic installation doesn't work:

Step 1: Locate Claude Desktop Configuration

The configuration file location depends on your operating system:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows: %APPDATA%\Claude\claude_desktop_config.json

  • Linux: ~/.config/Claude/claude_desktop_config.json

Step 2: Update Configuration

Open the configuration file and add the Mathematics MCP server:

{
  "mcpServers": {
    "mathematics": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/mathematics-mcp",
        "run",
        "fastmcp",
        "run",
        "main.py"
      ]
    }
  }
}

Important: Replace /absolute/path/to/mathematics-mcp with the actual path to your project directory.

Example for macOS/Linux:

{
  "mcpServers": {
    "mathematics": {
      "command": "uv",
      "args": [
        "--directory",
        "/Users/yourusername/projects/mathematics-mcp",
        "run",
        "fastmcp",
        "run",
        "main.py"
      ]
    }
  }
}

Example for Windows:

{
  "mcpServers": {
    "mathematics": {
      "command": "uv",
      "args": [
        "--directory",
        "C:\\Users\\YourUsername\\projects\\mathematics-mcp",
        "run",
        "fastmcp",
        "run",
        "main.py"
      ]
    }
  }
}

Step 3: Restart Claude Desktop

  1. Quit Claude Desktop completely (Cmd+Q on Mac, Alt+F4 on Windows)

  2. Relaunch Claude Desktop

  3. Look for the ๐Ÿ”Œ icon in the bottom right indicating MCP servers are connected

  4. Click the icon to see "mathematics" server listed

Step 4: Verify Installation

In Claude, try asking:

  • "What's 12345 + 67890?"

  • "Calculate the square root of 144"

  • "What's 25 to the power of 3?"

  • "Calculate the factorial of 10"

  • "What's the sine of 30 degrees?"

  • "Find the GCD of 48 and 18"

  • "Calculate the mean of these numbers: 10, 20, 30, 40, 50"

Claude should use the Mathematics MCP tools to provide accurate answers.

Troubleshooting Installation

If the automatic installation fails:

# Check if uv is installed correctly
uv --version

# Verify the server works
uv run fastmcp dev main.py

# Try manual configuration following the steps above

Available Tools

1. Addition (add)

Input: {"a": 10, "b": 5}
Output: {"status": "success", "operation": "add", "result": 15}

2. Subtraction (subtract)

Input: {"a": 10, "b": 5}
Output: {"status": "success", "operation": "subtract", "result": 5}

3. Multiplication (multiply)

Input: {"a": 10, "b": 5}
Output: {"status": "success", "operation": "multiply", "result": 50}

4. Division (divide)

Input: {"a": 10, "b": 5}
Output: {"status": "success", "operation": "divide", "result": 2.0}

Note: Throws error on division by zero

5. Modulus (modulus)

Input: {"a": 10, "b": 3}
Output: {"status": "success", "operation": "modulus", "result": 1}

Note: Throws error on modulus by zero

6. Power (power)

Input: {"base": 2, "exponent": 8}
Output: {"status": "success", "operation": "power", "result": 256}

7. Square (square)

Input: {"a": 5}
Output: {"status": "success", "operation": "square", "result": 25}

8. Square Root (sqrt)

Input: {"a": 144}
Output: {"status": "success", "operation": "sqrt", "result": 12.0}

Note: Throws error on negative numbers

9. Factorial (factorial)

Input: {"a": 5}
Output: {"status": "success", "operation": "factorial", "result": 120}

Note: Only works with non-negative integers

10. Absolute Value (absolute)

Input: {"a": -15}
Output: {"status": "success", "operation": "absolute", "result": 15}

11. Logarithm (logarithm)

Input: {"value": 100, "base": 10}
Output: {"status": "success", "operation": "logarithm", "result": 2.0}

Note: Default base is 10 if not specified

12. Natural Logarithm (natural_log)

Input: {"a": 2.718281828}
Output: {"status": "success", "operation": "natural_log", "result": 1.0}

Note: Uses base e (approximately 2.718)

13. Sine (sine)

Input: {"angle": 90}
Output: {"status": "success", "operation": "sine", "result": 1.0}

Note: Input angle in degrees

14. Cosine (cosine)

Input: {"angle": 0}
Output: {"status": "success", "operation": "cosine", "result": 1.0}

Note: Input angle in degrees

15. Tangent (tangent)

Input: {"angle": 45}
Output: {"status": "success", "operation": "tangent", "result": 1.0}

Note: Input angle in degrees, undefined at 90ยฐ, 270ยฐ, etc.

16. Greatest Common Divisor (gcd)

Input: {"a": 48, "b": 18}
Output: {"status": "success", "operation": "gcd", "result": 6}

Note: Both numbers must be integers

17. Least Common Multiple (lcm)

Input: {"a": 12, "b": 18}
Output: {"status": "success", "operation": "lcm", "result": 36}

Note: Both numbers must be integers

18. Mean (mean)

Input: {"numbers": [10, 20, 30, 40, 50]}
Output: {"status": "success", "operation": "mean", "result": 30.0}

Note: Calculates average of all numbers in the list

19. Median (median)

Input: {"numbers": [1, 3, 5, 7, 9]}
Output: {"status": "success", "operation": "median", "result": 5}

Note: Middle value when sorted; average of two middle values for even-length lists

20. Standard Deviation (standard_deviation)

Input: {"numbers": [2, 4, 4, 4, 5, 5, 7, 9]}
Output: {"status": "success", "operation": "standard_deviation", "result": 2.138}

Note: Uses sample standard deviation (n-1); requires at least 2 numbers

21. Ceiling (ceiling)

Input: {"a": 3.2}
Output: {"status": "success", "operation": "ceiling", "result": 4}

Note: Always rounds up

22. Floor (floor)

Input: {"a": 3.8}
Output: {"status": "success", "operation": "floor", "result": 3}

Note: Always rounds down

Contributing

Contributions are welcome! Here's how you can help:

Reporting Bugs

  1. Check if the issue already exists

  2. Create a new issue with:

    • Clear description

    • Steps to reproduce

    • Expected vs actual behavior

    • Log output from math_mcp.log

Suggesting Features

  1. Open an issue describing the feature

  2. Explain the use case

  3. Provide examples if possible

Pull Requests

  1. Fork the repository

  2. Create a feature branch:

   git checkout -b feature/amazing-feature
  1. Make your changes

  2. Add tests if applicable

  3. Commit with clear messages:

   git commit -m "Add: New trigonometric functions"
  1. Push to your fork:

   git push origin feature/amazing-feature
  1. Open a Pull Request

Troubleshooting

Server Not Appearing in Claude Desktop

Problem: MCP server doesn't show up in Claude Desktop

Solutions:

  1. Check the configuration file path is correct

  2. Verify JSON syntax in claude_desktop_config.json

  3. Ensure absolute paths are used (not relative paths)

  4. Restart Claude Desktop completely

  5. Check math_mcp.log for startup errors

"Unexpected non-whitespace character after JSON" Error

Problem: Claude Desktop shows JSON parsing errors

Solutions:

  1. Ensure logging is NOT writing to sys.stdout

  2. Use sys.stderr or file logging only

  3. Remove any print() statements from the code

Import Errors

Problem: ModuleNotFoundError: No module named 'fastmcp'

Solutions:

  1. Activate your virtual environment

  2. Install dependencies: pip install fastmcp pydantic

  3. If using venv, point to venv Python in config

Permission Errors

Problem: Cannot write to log file

Solutions:

  1. Check write permissions on the directory

  2. Use a different log location:

   LOG_FILE = Path.home() / "math_mcp.log"

Testing Connection

To test if the server is working:

# Run the server
python main.py

# In another terminal, send a test message (requires jq)
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | python main.py

Future Enhancement Ideas

  • Add complex number support

  • Implement matrix operations

  • Add unit conversion tools

  • Support for symbolic math (using SymPy)

  • Inverse trigonometric functions (arcsin, arccos, arctan)

  • Hyperbolic functions (sinh, cosh, tanh)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Star โญ this repo if you find it helpful!

Available Tools

22 tools
absoluteA

Calculate the absolute value of a given number. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Returns the absolute (non-negative) value of the input. - Logs the operation and result.

Inputs: data (required). Returns: object

addA

Perform addition of two numbers provided in the data object. Args: data (TwoNumberOperation): An object containing two numbers a and b to be added. Returns: Dict[str, Any]: A dictionary containing the operation name ("add") and the result of the addition if successful, or an error message if an exception occurs. Logs: Logs the operation and result in the format: "ADD | {data.a} + {data.b} = {result}"

Inputs: data (required). Returns: object

ceilingA

Round a number up to the nearest integer. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Always rounds up (e.g., 3.1 -> 4, -3.1 -> -3). - Logs the operation and result.

Inputs: data (required). Returns: object

cosineA

Calculate the cosine of an angle in degrees. Args: data (AngleOperation): An object containing the angle in degrees. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Input angle should be in degrees (not radians). - Result is between -1 and 1. - Logs the operation and result.

Inputs: data (required). Returns: object

divideA

Perform division of two numbers provided in the TwoNumberOperation object. Args: data (TwoNumberOperation): An object containing two numbers, a and b, where a is the numerator and b is the denominator. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ZeroDivisionError: If the denominator (b) is zero. Notes: - Logs the division operation and its result. - Returns a success response if the operation is successful. - Returns an error response if an exception occurs.

Inputs: data (required). Returns: object

factorialA

Calculate the factorial of a given number. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If the input is negative or not an integer. Notes: - Only works with non-negative integers. - Logs the operation and result.

Inputs: data (required). Returns: object

floorA

Round a number down to the nearest integer. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Always rounds down (e.g., 3.9 -> 3, -3.1 -> -4). - Logs the operation and result.

Inputs: data (required). Returns: object

gcdA

Calculate the Greatest Common Divisor (GCD) of two numbers. Args: data (TwoNumberOperation): An object containing two numbers, a and b. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If inputs are not integers. Notes: - Both numbers must be integers. - Returns the largest number that divides both inputs. - Logs the operation and result.

Inputs: data (required). Returns: object

lcmA

Calculate the Least Common Multiple (LCM) of two numbers. Args: data (TwoNumberOperation): An object containing two numbers, a and b. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If inputs are not integers. Notes: - Both numbers must be integers. - Returns the smallest number that is divisible by both inputs. - Logs the operation and result.

Inputs: data (required). Returns: object

logarithmA

Calculate the logarithm of a value with a specified base. Args: data (LogOperation): An object containing the value and base for logarithm. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If value is non-positive or base is invalid. Notes: - Default base is 10 (common logarithm). - Use base 'e' (2.718...) for natural logarithm. - Logs the operation and result.

Inputs: data (required). Returns: object

meanA

Calculate the mean (average) of a list of numbers. Args: data (ListOperation): An object containing a list of numbers. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If the list is empty. Notes: - Mean is the sum of all numbers divided by count. - Logs the operation and result.

Inputs: data (required). Returns: object

medianA

Calculate the median of a list of numbers. Args: data (ListOperation): An object containing a list of numbers. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If the list is empty. Notes: - Median is the middle value when numbers are sorted. - For even-length lists, returns average of two middle values. - Logs the operation and result.

Inputs: data (required). Returns: object

modulusA

Calculate the modulus (remainder) of two numbers provided in the data object. Args: data (TwoNumberOperation): An object containing two numbers, a and b. Returns: Dict[str, Any]: A dictionary containing the operation result if successful, or an error message if an exception occurs. Raises: ZeroDivisionError: If the second number (b) is zero, as modulus by zero is not allowed. Logs: Logs the operation and result in the format "MOD | a % b = result" if successful. Example: data = TwoNumberOperation(a=10, b=3) result = modulus(data) # result -> {"status": "success", "operation": "modulus", "result": 1}

Inputs: data (required). Returns: object

multiplyA

Perform multiplication of two numbers provided in the data object. Args: data (TwoNumberOperation): An object containing two numbers a and b to be multiplied. Returns: Dict[str, Any]: A dictionary containing the result of the multiplication operation or an error message in case of failure. Logs: Logs the multiplication operation in the format: "MUL | {data.a} * {data.b} = {result}" Exceptions: Catches any exceptions that occur during the operation and returns an error response with the exception message.

Inputs: data (required). Returns: object

natural_logA

Calculate the natural logarithm (base e) of a given number. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If the input is non-positive. Notes: - Natural log uses base e (approximately 2.718). - Logs the operation and result.

Inputs: data (required). Returns: object

powerA

Calculate the power of a given base raised to a given exponent. Args: data (PowerOperation): An object containing the base and exponent values. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Logs: Logs the operation in the format "POW | base ^ exponent = result". Exceptions: Catches any exceptions during the calculation and returns an error response.

Inputs: data (required). Returns: object

sineA

Calculate the sine of an angle in degrees. Args: data (AngleOperation): An object containing the angle in degrees. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Input angle should be in degrees (not radians). - Result is between -1 and 1. - Logs the operation and result.

Inputs: data (required). Returns: object

sqrtA

Calculate the square root of a given number. Args: data (SingleNumberOperation): An object containing the input number a. Returns: Dict[str, Any]: A dictionary containing the operation name, result, and status of the operation. Raises: ValueError: If the input number a is negative. Notes: - Logs the operation and result using the logger. - Returns a success response if the operation is successful. - Returns an error response if an exception occurs.

Inputs: data (required). Returns: object

squareA

Calculate the square of a given number. Args: data (SingleNumberOperation): An object containing the number to be squared. Returns: Dict[str, Any]: A dictionary containing the operation name ("square") and the result of squaring the input number. In case of an error, returns an error response. Logs: Logs the operation and the result in the format "SQUARE | ^2 = ". Raises: Exception: If an error occurs during the calculation.

Inputs: data (required). Returns: object

standard_deviationA

Calculate the standard deviation of a list of numbers. Args: data (ListOperation): An object containing a list of numbers. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Raises: ValueError: If the list has fewer than 2 numbers. Notes: - Measures the amount of variation in the dataset. - Uses sample standard deviation (n-1 denominator). - Logs the operation and result.

Inputs: data (required). Returns: object

subtractB

Perform subtraction of two numbers provided in the data object. Args: data (TwoNumberOperation): An object containing two numbers, a and b. Returns: Dict[str, Any]: A dictionary containing the operation name ("subtract") and the result of the subtraction if successful, or an error message if an exception occurs. Logs: Logs the subtraction operation and its result in the format: "SUB | {data.a} - {data.b} = {result}".

Inputs: data (required). Returns: object

tangentA

Calculate the tangent of an angle in degrees. Args: data (AngleOperation): An object containing the angle in degrees. Returns: Dict[str, Any]: A dictionary containing the operation result or an error message. Notes: - Input angle should be in degrees (not radians). - Undefined at 90ยฐ, 270ยฐ, etc. (will return very large values). - Logs the operation and result.

Inputs: data (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    TDQS

    A3.8/5.0

    Scored across 22 tools

    Disambiguation4/5

    Most tools target distinct mathematical operations with clear boundaries. The main overlap is `logarithm` and `natural_log`, since natural_log is just a special case of logarithm with base e.

    Naming Consistency4/5

    Tool names are mostly lowercase single-word operation names like add, divide, sine, and median. Minor deviations include the abbreviation `sqrt`, and snake_case names `natural_log` and `standard_deviation`, but the naming style is still predictable and readable.

    Tool Count3/5

    At 22 tools, this is on the heavier side for a math operation server. Most tools are individually useful, but the redundancy between logarithm and natural_log suggests the set could be slightly trimmed.

    Completeness4/5

    The tool surface covers arithmetic, powers, roots, logs, trig, rounding, number theory, and basic statistics, which is a solid range for a mathematics server. Minor gaps like inverse trig or hyperbolic functions are not critical for a general-purpose math toolkit.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      D
      maintenance
      A basic MCP server built with the FastMCP framework that provides fundamental mathematical operations like addition, subtraction, multiplication, and division. It serves as a demonstration for integrating math-based tools into MCP-compatible environments like Cursor IDE.
      4
      -
    • A
      license
      C
      quality
      D
      maintenance
      A comprehensive MCP server that turns any AI assistant into a powerful mathematical computation engine, providing 52 advanced functions, 158 unit conversions, financial calculations, and secure AST-based evaluation.
      18
      16
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      A FastMCP server that provides mathematical tools (addition, multiplication, temperature conversion) for Claude to execute via natural language.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      A simple MCP server that provides basic arithmetic operations like add and multiply, enabling Claude to perform math calculations.
      -