Skip to main content
Glama
cthunter01

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).

ParametersJSON Schema
NameRequiredDescriptionDefault
expressionYesMathematical expression to evaluate (e.g., "2+2", "sqrt(144)", "355/113")
precisionNoNumber of decimal places for the result (0-100, default: 20)

TDQS

A3.8/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes the computational behavior (BC calculator, arbitrary precision arithmetic, supported operations) but doesn't mention error handling, performance characteristics, or limitations beyond the precision parameter. It provides adequate but not comprehensive behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is efficiently structured in a single sentence that front-loads the core purpose and then lists supported features. Every element (calculator type, precision capability, operation categories, function examples) serves a clear informational purpose with zero wasted text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mathematical calculation tool with 2 parameters (1 required) and no output schema, the description provides good context about the calculator engine, precision capabilities, and supported operations/functions. However, it doesn't mention what the output looks like (numeric result format, error responses), which would be helpful given the lack of output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents both parameters. The description doesn't add any parameter-specific information beyond what's in the schema descriptions. This meets the baseline expectation when schema coverage is complete.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific verb ('evaluate') and resource ('mathematical expressions'), and distinguishes this tool from its sibling 'calculate_advanced' by specifying it uses BC calculator with arbitrary precision arithmetic and supports basic operations and math library functions. This provides immediate understanding of what the tool does.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by listing supported operations and functions, but doesn't explicitly state when to use this tool versus 'calculate_advanced' or 'set_precision'. It provides functional scope but lacks explicit guidance on tool selection or exclusion criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

calculate_advancedB

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

ParametersJSON Schema
NameRequiredDescriptionDefault
scriptYesMulti-line BC script with variables, loops, or functions
precisionNoNumber of decimal places for results (0-100, default: 20)

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions support for advanced features like multi-line scripts and control flow, which adds some context, but fails to describe critical behaviors such as error handling, execution limits, security implications, or what the output looks like (e.g., result format, potential side effects). For a tool executing scripts with no annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, stating the core purpose in the first clause. Both sentences add value by specifying capabilities (e.g., multi-line scripts, loops) without redundancy. However, it could be slightly more structured by explicitly separating features from usage context.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of executing advanced scripts with no annotations and no output schema, the description is incomplete. It lacks information on return values, error conditions, execution constraints (e.g., timeouts, resource limits), and how it differs operationally from sibling tools. This leaves the agent with insufficient context to use the tool effectively in varied scenarios.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, with clear descriptions for both parameters in the input schema. The description adds minimal value beyond the schema by implying the 'script' parameter can include advanced constructs like loops and functions, but does not provide additional syntax or format details. With high schema coverage, the baseline score of 3 is appropriate as the schema does most of the work.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Execute advanced BC scripts with variables, functions, and control flow.' It specifies the verb ('execute') and resource ('advanced BC scripts'), and distinguishes it from the simpler 'calculate' sibling tool by mentioning advanced features like multi-line scripts, loops, and conditionals. However, it doesn't explicitly contrast with 'set_precision', which slightly limits differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by stating it 'Supports multi-line scripts, variable assignments, loops, and conditionals,' suggesting it should be used for complex calculations beyond basic arithmetic. However, it lacks explicit guidance on when to choose this tool over 'calculate' or 'set_precision', and does not mention any prerequisites or exclusions, leaving some ambiguity for the agent.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

set_precisionA

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

ParametersJSON Schema
NameRequiredDescriptionDefault
precisionYesNumber of decimal places (0-100)

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the tool's effect ('affects all calculations until changed again') which is useful context, but doesn't mention potential side effects, error conditions, or what happens if precision is set to extreme values. The description doesn't contradict annotations since 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.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with two sentences that each earn their place. The first sentence states the core purpose, and the second explains the persistence effect. No wasted words or redundant information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a single-parameter configuration tool with no annotations and no output schema, the description provides adequate but minimal context. It explains what the tool does and its persistence effect, but doesn't address potential limitations, error scenarios, or how this interacts with sibling calculation tools.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents the single 'precision' parameter with its type, range, and description. The description doesn't add any additional parameter semantics beyond what's in the schema, which meets the baseline expectation when schema coverage is complete.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verb ('Set') and resource ('default precision for subsequent calculations'). It explains what the tool does (sets decimal places for calculations) but doesn't explicitly differentiate from sibling tools like 'calculate' or 'calculate_advanced'.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use this tool ('for subsequent calculations') and mentions persistence ('affects all calculations until changed again'), but doesn't provide explicit guidance on when to use this versus the sibling calculation tools or any prerequisites for usage.

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. Dates show when Glama detected each change.

  1. 3 tool updates
    • First observedcalculate
    • First observedcalculate_advanced
    • First observedset_precision

TDQS

A3.7/5.0
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.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

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
  • F
    license
    A
    quality
    D
    maintenance
    Enables mathematical calculations through basic arithmetic operations including addition, subtraction, multiplication, division, exponentiation, and logarithms. Provides a simple interface for AI agents to perform mathematical computations.
    6
    3
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides comprehensive mathematical capabilities including basic arithmetic, advanced functions, statistical tools, and access to mathematical constants. It allows users to perform computations and generate math-related prompts through a standardized MCP interface.
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cthunter01/MCPCalculator'

If you have feedback or need assistance with the MCP directory API, please join our Discord server