Skip to main content
Glama
BC Calculator MCP Server

BC Calculator MCP Server

by cthunter01

BC Calculator MCP Server

A Model Context Protocol (MCP) server that provides numerical computation capabilities by integrating with the Unix bc (Basic Calculator) command-line tool. This server exposes arbitrary precision arithmetic operations, mathematical functions, and complex expressions through the MCP protocol.

Features

  • โœจ Arbitrary Precision Arithmetic: Support for calculations with configurable decimal precision (0-100 digits)

  • ๐Ÿงฎ Advanced Math Functions: Access to bc's math library including sqrt, sin, cos, arctan, natural log, exponential

  • ๐Ÿ”„ Concurrent Processing: Process pool management for handling multiple calculations simultaneously

  • ๐Ÿ›ก๏ธ Security First: Input validation and sanitization to prevent command injection

  • โšก Performance Optimized: Process pooling for fast response times

  • ๐ŸŽฏ MCP Compliant: Full MCP protocol implementation with tool discovery and JSON-RPC communication

Related MCP server: Math MCP Server

Installation

Prerequisites

  • Node.js (v18 or higher)

  • TypeScript (v5.3 or higher)

  • bc calculator (standard on most Unix systems)

Verify bc is installed:

which bc
bc --version

If not installed:

# Ubuntu/Debian
sudo apt-get install bc

# macOS
brew install bc

# Fedora/RHEL
sudo dnf install bc

Setup

  1. Navigate to MCP servers directory:

cd /home/travis/.local/share/Roo-Code/MCP
  1. Bootstrap the project (if using create-server):

npx @modelcontextprotocol/create-server bc-calculator
cd bc-calculator

Or manually create the project structure:

mkdir -p bc-calculator/src
cd bc-calculator
  1. Install dependencies:

npm install
  1. Build the server:

npm run build
  1. Configure MCP settings:

Add to ~/.config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json:

{
  "mcpServers": {
    "bc-calculator": {
      "command": "node",
      "args": ["/home/travis/.local/share/Roo-Code/MCP/bc-calculator/build/index.js"]
    }
  }
}

Usage

Available Tools

1. calculate

Evaluate basic mathematical expressions with configurable precision.

Parameters:

  • expression (string, required): Mathematical expression to evaluate

  • precision (number, optional): Decimal places for the result (default: 20, range: 0-100)

Examples:

// Basic arithmetic
calculate({ expression: "2 + 2" })
// โ†’ { result: "4", expression: "2 + 2", precision: 20 }

// Division with precision
calculate({ expression: "355/113", precision: 15 })
// โ†’ { result: "3.141592920353982", expression: "355/113", precision: 15 }

// Powers and roots
calculate({ expression: "2^10" })
// โ†’ { result: "1024", expression: "2^10", precision: 20 }

calculate({ expression: "sqrt(2)", precision: 10 })
// โ†’ { result: "1.4142135623", expression: "sqrt(2)", precision: 10 }

2. calculate_advanced

Execute advanced BC scripts with variables, functions, and control flow.

Parameters:

  • script (string, required): Multi-line BC script

  • precision (number, optional): Decimal places for results (default: 20)

Examples:

// Variables
calculate_advanced({
  script: `
    a = 5
    b = 10
    a * b + sqrt(a)
  `,
  precision: 5
})

// Computing pi
calculate_advanced({
  script: `
    scale=15
    pi = 4*a(1)
    pi
  `
})
// โ†’ { result: "3.141592653589793", ... }

// Fibonacci sequence
calculate_advanced({
  script: `
    a = 0
    b = 1
    for (i = 0; i < 10; i++) {
      c = a + b
      a = b
      b = c
    }
    b
  `
})

3. set_precision

Set the default precision for subsequent calculations.

Parameters:

  • precision (number, required): Number of decimal places (0-100)

Example:

set_precision({ precision: 50 })
// All subsequent calculations will use 50 decimal places

Mathematical Functions (with -l flag)

When using the math library, these functions are available:

Function

Description

Example

sqrt(x)

Square root

sqrt(2) โ†’ 1.41421...

s(x)

Sine (radians)

s(3.14159/2) โ†’ 1.0

c(x)

Cosine (radians)

c(0) โ†’ 1.0

a(x)

Arctangent (radians)

a(1) โ†’ 0.78539...

l(x)

Natural logarithm

l(2.71828) โ†’ 1.0

e(x)

Exponential (e^x)

e(1) โ†’ 2.71828...

Supported Operators

  • Arithmetic: +, -, *, /, ^ (power), % (modulo)

  • Comparison: <, >, <=, >=, ==, !=

  • Logical: &&, ||, !

  • Assignment: =

  • Increment/Decrement: ++, --

BC Language Features

  • Variables: a = 5; b = 10; a + b

  • Arrays: a[0] = 1; a[1] = 2

  • Conditionals: if (x > 0) { ... }

  • Loops: while (i < 10) { ... }, for (i=0; i<10; i++) { ... }

  • Functions: Define custom functions with define

Architecture

Process Pool

The server maintains a pool of 3 BC processes to handle concurrent requests:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚     BC Calculator MCP Server         โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  Process Pool Manager                โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚
โ”‚  โ”‚ BC #1   โ”‚ โ”‚ BC #2   โ”‚ โ”‚ BC #3   โ”‚โ”‚
โ”‚  โ”‚ (ready) โ”‚ โ”‚ (busy)  โ”‚ โ”‚ (ready) โ”‚โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  Request Queue                       โ”‚
โ”‚  โ€ข Validation                        โ”‚
โ”‚  โ€ข Sanitization                      โ”‚
โ”‚  โ€ข Timeout Management                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Security Features

  1. Input Validation

    • Character whitelist enforcement

    • Maximum expression length (10KB)

    • Dangerous pattern detection

  2. Command Injection Prevention

    • No shell execution (spawn with shell: false)

    • Input sanitization before BC

    • Blocked patterns: system(), exec(), backticks, file redirects

  3. Resource Protection

    • 30-second timeout per calculation

    • Process pool size limit (3 processes)

    • Automatic process recovery on failures

Error Handling

The server provides detailed error messages for common issues:

Validation Errors

{
  "isError": true,
  "content": [{
    "type": "text",
    "text": "Validation error: Expression contains invalid characters"
  }]
}

BC Runtime Errors

{
  "isError": true,
  "content": [{
    "type": "text", 
    "text": "BC error: divide by zero"
  }]
}

Timeout Errors

{
  "isError": true,
  "content": [{
    "type": "text",
    "text": "Calculation timeout after 30000ms"
  }]
}

Configuration

Default Settings

  • Process Pool Size: 3 concurrent BC processes

  • Default Precision: 20 decimal places

  • Calculation Timeout: 30 seconds

  • Max Expression Length: 10,000 characters

Environment Variables

None required - bc is a standard system utility.

Optional: Custom Pool Size

Edit src/index.ts to adjust pool configuration:

const pool = new BCProcessPool({
  poolSize: 5,          // Increase for more concurrency
  defaultPrecision: 20,
  defaultTimeout: 60000 // Increase for longer calculations
});

Development

Project Structure

bc-calculator/
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ tsconfig.json
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts              # MCP server entry point
โ”‚   โ”œโ”€โ”€ types.ts              # TypeScript definitions
โ”‚   โ”œโ”€โ”€ bc-process.ts         # BC process wrapper
โ”‚   โ”œโ”€โ”€ bc-process-pool.ts    # Process pool manager
โ”‚   โ”œโ”€โ”€ input-validator.ts    # Security validation
โ”‚   โ””โ”€โ”€ request-queue.ts      # Request management
โ””โ”€โ”€ build/                     # Compiled JavaScript
    โ””โ”€โ”€ index.js

Build Commands

# Build once
npm run build

# Watch mode (rebuild on changes)
npm run watch

# Clean build
rm -rf build && npm run build

Testing

# Manual testing via MCP client
# Use the Roo-Code interface to invoke tools

# Example test cases:
# 1. Basic: calculate("2+2")
# 2. Precision: calculate("22/7", precision=10)
# 3. Math: calculate("sqrt(2)*sqrt(2)", precision=15)
# 4. Error: calculate("2/0")
# 5. Advanced: calculate_advanced("a=5; b=10; a+b")

Troubleshooting

BC Not Found

Error: spawn bc ENOENT

Solution: Install bc calculator

sudo apt-get install bc  # Ubuntu/Debian
brew install bc          # macOS

Permission Denied

Error: Cannot execute build/index.js

Solution:

chmod +x build/index.js

Module Import Errors

Error: Cannot find module

Solution: Ensure "type": "module" is in package.json

Timeout on Complex Calculations

Symptom: Long-running calculations fail

Solution: Increase timeout in tool parameters or pool config

Process Pool Exhausted

Symptom: Delayed responses under heavy load

Solution: Increase poolSize in BCProcessPool configuration

Performance

Benchmarks

  • Simple arithmetic: <10ms

  • Math functions: <50ms

  • Complex scripts: <200ms

  • Concurrent requests: 3 parallel calculations

Optimization Tips

  1. Reuse connections: The process pool automatically optimizes this

  2. Batch operations: Use calculate_advanced for multiple related calculations

  3. Adjust precision: Lower precision = faster calculations

  4. Increase pool: For heavy concurrent use, increase pool size

Contributing

Contributions welcome! Please:

  1. Maintain TypeScript strict mode compliance

  2. Add tests for new features

  3. Update documentation

  4. Follow existing code style

  5. Ensure security validations remain intact

License

MIT License - See LICENSE file for details

Acknowledgments

Support

For issues, questions, or feature requests:

  1. Check the troubleshooting section

  2. Review the implementation guide (IMPLEMENTATION_GUIDE.md)

  3. Examine the architecture documentation (ARCHITECTURE.md)

Version History

1.0.0 (Initial Release)

  • Basic calculation support

  • Advanced scripting support

  • Process pool management

  • Security validation

  • MCP protocol compliance

Available Tools

3 tools
calculateA

Evaluate mathematical expressions using BC calculator with arbitrary precision arithmetic. Supports basic operations (+, -, *, /, ^, %), comparisons, and math library functions (sqrt, sine, cosine, arctan, log, exp).

Inputs: expression (required), precision.

calculate_advancedB

Execute advanced BC scripts with variables, functions, and control flow. Supports multi-line scripts, variable assignments, loops, and conditionals.

Inputs: script (required), precision.

set_precisionA

Set the default precision (decimal places) for subsequent calculations. This affects all calculations until changed again.

Inputs: precision (required).

Tool Schema Changelog

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

Loading tool schema changelogโ€ฆ

    TDQS

    A3.7/5.0

    Scored across 3 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose: 'calculate' handles basic expressions, 'calculate_advanced' supports complex scripts, and 'set_precision' configures precision settings. There is no overlap or ambiguity between them.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern with snake_case: 'calculate', 'calculate_advanced', and 'set_precision'. The naming is predictable and readable throughout.

    Tool Count5/5

    With 3 tools, the server is well-scoped for a calculator domain, covering basic calculations, advanced scripting, and precision configuration. Each tool earns its place without being too sparse or overloaded.

    Completeness4/5

    The tool set provides robust coverage for a calculator server, including expression evaluation, advanced scripting, and precision control. A minor gap might be the lack of a tool to reset or retrieve current precision, but core workflows are fully supported.

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Provides basic arithmetic operations and advanced mathematical functions through the Model Context Protocol (MCP), with features like calculation history tracking and expression evaluation.
      1
      -
    • A
      license
      A
      quality
      D
      maintenance
      Enables basic arithmetic operations (addition, subtraction, multiplication, division) with 64-bit precision and matrix multiplication capabilities. Provides mathematical computation tools for AI assistants through the Model Context Protocol.
      5
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides a comprehensive set of mathematical functions as MCP tools, enabling language models to perform calculations including arithmetic, trigonometry, logarithms, and more.
      10 npm
      1
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Provides LLMs with deterministic math tools for sandboxed expression evaluation, descriptive statistics, primality testing, prime factorization, GCD/LCM, quadratic solving, and base conversion. Every operation runs real code rather than relying on the model's arithmetic, with expression parsing restricted to a whitelist of operators, constants, and functions.
      21
      13 PyPI
      MIT