calculator-mcp-server

cvicens/calculator-mcp-server

3.1

If you are the rightful owner of calculator-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

The Calculator MCP Server is a high-performance mathematical calculator server built in Rust, supporting both Model Context Protocol (MCP) for Claude Desktop and HTTP API for integration with Llamastack and other AI frameworks.

Tools
5
Resources
0
Prompts
0

🧮 Calculator MCP Server

A high-performance mathematical calculator server built in Rust that supports both Model Context Protocol (MCP) for Claude Desktop and HTTP API for integration with Llamastack and other AI frameworks.

Rust MCP HTTP API

✨ Features

🔢 Mathematical Operations

  • Basic Arithmetic: Addition, subtraction, multiplication, division with multiple operands
  • Advanced Math: Powers, square roots, nth roots
  • Trigonometry: Sin, cos, tan, and their inverses (degrees/radians)
  • Logarithms: Natural log, base-10, base-2, and custom bases
  • Combinatorics: Factorials, permutations, combinations
  • Statistics: Mean, median, mode, variance, standard deviation
  • Number Systems: Binary, octal, decimal, hexadecimal conversions (base 2-36)

🚀 Dual Interface Support

  • MCP Server: Direct integration with Claude Desktop
  • HTTP API: RESTful endpoints for Llamastack and web services
  • Shared Core: Same high-performance Rust logic for both interfaces

⚡ Performance

  • Native Rust Speed: Zero-overhead abstractions
  • Arbitrary Precision: Support for large factorials using BigInt
  • Sub-millisecond Calculations: Lightning-fast mathematical operations
  • Memory Efficient: Minimal resource usage

🏗️ Architecture

┌─────────────────┐    ┌─────────────────┐
│   Claude Desktop │    │   Llamastack   │
│                 │    │   / Web Apps    │
└─────────┬───────┘    └─────────┬───────┘
          │                      │
          │ JSON-RPC             │ HTTP/REST
          │ (stdin/stdout)       │ (TCP:8080)
          │                      │
          ▼                      ▼
┌─────────────────────────────────────────┐
│           Calculator Core               │
│    (Shared Rust Implementation)        │
└─────────────────────────────────────────┘

🚀 Quick Start

Prerequisites

  • Rust 1.70+ installed
  • Claude Desktop (for MCP usage)

Build Both Servers

# Clone the repository
git clone <your-repo-url>
cd calculator-mcp-server

# Build both MCP and HTTP servers
make all

For Claude Desktop (MCP)

# Package for Claude Desktop
make pack-mcp

# Install the generated calculator-mcp-server.dxt file in Claude Desktop
# Settings > Extensions > Install Extension

For Llamastack/HTTP (API)

# Start HTTP server
make test-http

# Server runs on http://localhost:8080

📋 Usage Examples

Claude Desktop Integration

Once installed as an MCP extension, simply ask Claude:

"Calculate the factorial of 15"
"Convert binary 1101 to hexadecimal" 
"What's the combination C(10,3)?"
"Calculate statistics for: 23, 45, 12, 67, 34, 89, 56"

HTTP API Usage

Health Check
curl http://localhost:8080/health
Calculate Factorial
curl -X POST http://localhost:8080/factorial \
  -H 'Content-Type: application/json' \
  -d '{"n": 20}'
Number Base Conversion
curl -X POST http://localhost:8080/convert \
  -H 'Content-Type: application/json' \
  -d '{"value": "FF", "from_base": 16, "to_base": 2}'
Basic Arithmetic
curl -X POST http://localhost:8080/arithmetic \
  -H 'Content-Type: application/json' \
  -d '{"operation": "multiply", "operands": [12, 15, 8]}'

🛠️ Available Tools/Endpoints

Tool/EndpointDescriptionParameters
basic_arithmeticAddition, subtraction, multiplication, divisionoperation, operands[]
power_and_rootsPowers, square roots, nth rootsoperation, base, exponent?
trigonometryTrigonometric functionsfunction, value, angle_unit?
logarithmsLogarithmic calculationsvalue, base?
factorial_combinatoricsFactorials, permutations, combinationsoperation, n, r?
statisticsDescriptive statisticsvalues[]
number_conversionBase conversion (2-36)value, from_base, to_base

🔧 Development

Project Structure

calculator-mcp-server/
├── src/
│   ├── lib.rs           # Shared calculator logic
│   ├── mcp_server.rs    # MCP JSON-RPC server
│   └── http_server.rs   # HTTP API server (Axum)
├── Makefile            # Build automation
├── manifest.json       # MCP extension manifest
└── README.md          # This file

Build Commands

make build-mcp      # Build MCP server only
make build-http     # Build HTTP server only  
make pack-mcp       # Package for Claude Desktop
make test-mcp       # Test MCP server
make test-http      # Start HTTP server for testing
make clean          # Clean build artifacts
make help           # Show all commands

Testing

# Test MCP server
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | ./target/release/mcp-server

# Test HTTP endpoints
curl http://localhost:8080/tools
curl -X POST http://localhost:8080/factorial -H 'Content-Type: application/json' -d '{"n": 12}'

📊 Performance Benchmarks

OperationInputTimeResult
Factorial170!<1ms7.257415615...e+306
Base Conversion32-bit number<1msAny base 2-36
Statistics1000 numbers<5msComplete analysis
TrigonometryAny angle<1msHigh precision

🌐 HTTP API Reference

Base URL

http://localhost:8080

Endpoints

GET /health

Health check endpoint

{
  "status": "healthy",
  "version": "1.0.0"
}
GET /tools

List available mathematical tools

{
  "tools": [
    {
      "name": "basic_arithmetic",
      "description": "Basic arithmetic operations",
      "parameters": {...}
    }
  ]
}
POST /calculate

Generic calculation endpoint

{
  "tool": "factorial_combinatorics",
  "arguments": {
    "operation": "factorial",
    "n": 15
  }
}
Response Format
{
  "success": true,
  "result": "1307674368000",
  "calculation_details": {
    "operation": "15!",
    "result": "1307674368000",
    "decimal_approximation": 1307674368000.0,
    "calculation_time_ms": 0
  }
}

🔌 Integration Examples

Python Client

import requests

class CalculatorClient:
    def __init__(self, base_url="http://localhost:8080"):
        self.base_url = base_url
    
    def factorial(self, n):
        response = requests.post(f"{self.base_url}/factorial", 
                               json={"n": n})
        return response.json()
    
    def convert_base(self, value, from_base, to_base):
        response = requests.post(f"{self.base_url}/convert", 
                               json={
                                   "value": value, 
                                   "from_base": from_base, 
                                   "to_base": to_base
                               })
        return response.json()

# Usage
calc = CalculatorClient()
result = calc.factorial(20)
print(f"20! = {result['result']}")

JavaScript/Node.js Client

class CalculatorClient {
    constructor(baseUrl = 'http://localhost:8080') {
        this.baseUrl = baseUrl;
    }
    
    async factorial(n) {
        const response = await fetch(`${this.baseUrl}/factorial`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ n })
        });
        return await response.json();
    }
    
    async convertBase(value, fromBase, toBase) {
        const response = await fetch(`${this.baseUrl}/convert`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                value, 
                from_base: fromBase, 
                to_base: toBase 
            })
        });
        return await response.json();
    }
}

// Usage
const calc = new CalculatorClient();
const result = await calc.factorial(15);
console.log(`15! = ${result.result}`);

🎯 Use Cases

Claude Desktop Users

  • Mathematical Research: Complex calculations with detailed results
  • Programming: Base conversions and combinatorial calculations
  • Statistics: Data analysis and descriptive statistics
  • Education: Step-by-step mathematical operations

Llamastack Integration

  • AI Model Enhancement: Provide precise mathematical capabilities to LLMs
  • Scientific Computing: High-performance calculations for research
  • Web Applications: Mathematical microservice for web apps
  • API Integration: RESTful mathematical operations

🚦 Status & Compatibility

✅ Supported Platforms

  • Claude Desktop: macOS, Windows, Linux
  • HTTP API: Any platform with HTTP client support
  • MCP Version: 2024-11-05 protocol

❌ Not Supported

  • claude.ai (web client) - MCP extensions not supported
  • Claude mobile apps - MCP extensions not supported

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

# Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Clone and build
git clone <repo-url>
cd calculator-mcp-server
make all

📄 License

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

🙏 Acknowledgments

📞 Support


Built with ❤️ in Rust | Powered by MCP | Ready for AI Integration