Skip to main content
Glama
cthunter01

BC Calculator MCP Server

by cthunter01

calculate

Evaluate mathematical expressions with arbitrary precision arithmetic. Supports basic operations, comparisons, and math library functions like sqrt, sine, cosine, and log.

Instructions

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

Input Schema

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

Implementation Reference

  • The handleCalculate function that executes the 'calculate' tool logic: validates input arguments, sanitizes the expression, acquires a BC process from the pool, sets precision, evaluates the expression, and returns the result with execution time.
    async function handleCalculate(args: unknown): Promise<any> {
      const startTime = Date.now();
      
      // Validate arguments
      if (!args || typeof args !== 'object') {
        return {
          content: [{
            type: 'text',
            text: 'Invalid arguments: expected an object'
          }],
          isError: true
        };
      }
    
      const { expression, precision = globalPrecision } = args as {
        expression?: string;
        precision?: number;
      };
    
      if (!expression) {
        return {
          content: [{
            type: 'text',
            text: 'Missing required argument: expression'
          }],
          isError: true
        };
      }
    
      // Validate precision
      if (precision !== undefined && (precision < 0 || precision > 100)) {
        return {
          content: [{
            type: 'text',
            text: 'Invalid precision: must be between 0 and 100'
          }],
          isError: true
        };
      }
    
      try {
        // Validate input expression
        const validation = InputValidator.validate(expression);
        if (!validation.valid) {
          return {
            content: [{
              type: 'text',
              text: `Validation error: ${validation.error}`
            }],
            isError: true
          };
        }
    
        // Acquire process from pool
        const process = await pool.acquireProcess();
        
        try {
          // Set precision if different from current
          await process.setPrecision(precision);
          
          // Evaluate expression
          const result = await process.evaluate(validation.sanitized!);
          
          // Release process back to pool
          pool.releaseProcess(process);
          
          const executionTime = Date.now() - startTime;
          
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                result,
                expression,
                precision,
                executionTimeMs: executionTime
              }, null, 2)
            }]
          };
        } catch (error) {
          // Always release process even on error
          pool.releaseProcess(process);
          throw error;
        }
      } catch (error) {
        if (error instanceof BCCalculatorError) {
          return {
            content: [{
              type: 'text',
              text: `BC Calculator Error [${error.code}]: ${error.message}`
            }],
            isError: true
          };
        }
        
        return {
          content: [{
            type: 'text',
            text: `Calculation error: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • The handle_calculate function that executes the 'calculate' tool logic in Python: validates input, sanitizes expression, acquires BC process, sets precision, evaluates, and returns result.
    async def handle_calculate(args: dict[str, Any]) -> list[TextContent]:
        """Handle basic calculation requests"""
        import time
        start_time = time.time()
        
        # Get arguments with defaults
        expression = args.get("expression")
        precision = args.get("precision", global_precision)
        
        if not expression:
            return [TextContent(
                type="text",
                text="Missing required argument: expression"
            )]
        
        # Validate precision
        if precision is not None and (precision < 0 or precision > 100):
            return [TextContent(
                type="text",
                text="Invalid precision: must be between 0 and 100"
            )]
        
        try:
            # Validate input expression
            validation = InputValidator.validate(expression)
            if not validation.valid:
                return [TextContent(
                    type="text",
                    text=f"Validation error: {validation.error}"
                )]
            
            # Acquire process from pool
            process = await pool.acquire_process()
            
            try:
                # Set precision if different from current
                await process.set_precision(precision)
                
                # Evaluate expression
                result = await process.evaluate(validation.sanitized or expression)
                
                # Release process back to pool
                pool.release_process(process)
                
                execution_time = (time.time() - start_time) * 1000
                
                return [TextContent(
                    type="text",
                    text=json.dumps({
                        "result": result,
                        "expression": expression,
                        "precision": precision,
                        "executionTimeMs": execution_time
                    }, indent=2)
                )]
            except Exception as error:
                # Always release process even on error
                pool.release_process(process)
                raise
                
        except BCCalculatorError as error:
            return [TextContent(
                type="text",
                text=f"BC Calculator Error [{error.code.value}]: {error.message}"
            )]
        except Exception as error:
            return [TextContent(
                type="text",
                text=f"Calculation error: {str(error)}"
            )]
  • Input schema definition for the 'calculate' tool, specifying expression as required string and optional precision number.
    {
      name: 'calculate',
      description: 'Evaluate mathematical expressions using BC calculator with arbitrary precision arithmetic. ' +
                   'Supports basic operations (+, -, *, /, ^, %), comparisons, and math library functions ' +
                   '(sqrt, sine, cosine, arctan, log, exp).',
      inputSchema: {
        type: 'object',
        properties: {
          expression: {
            type: 'string',
            description: 'Mathematical expression to evaluate (e.g., "2+2", "sqrt(144)", "355/113")'
          },
          precision: {
            type: 'number',
            description: 'Number of decimal places for the result (0-100, default: 20)',
            minimum: 0,
            maximum: 100
          }
        },
        required: ['expression']
      }
  • Input schema definition for the 'calculate' tool in Python.
    Tool(
        name="calculate",
        description=(
            "Evaluate mathematical expressions using BC calculator with arbitrary precision arithmetic. "
            "Supports basic operations (+, -, *, /, ^, %), comparisons, and math library functions "
            "(sqrt, sine, cosine, arctan, log, exp)."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": 'Mathematical expression to evaluate (e.g., "2+2", "sqrt(144)", "355/113")'
                },
                "precision": {
                    "type": "number",
                    "description": "Number of decimal places for the result (0-100, default: 20)",
                    "minimum": 0,
                    "maximum": 100
                }
            },
            "required": ["expression"]
        }
    ),
  • Tool dispatch/registration in the CallToolRequestSchema handler switch statement, mapping 'calculate' to handleCalculate.
        switch (name) {
          case 'calculate':
            return await handleCalculate(args);
          
          case 'calculate_advanced':
            return await handleCalculateAdvanced(args);
          
          case 'set_precision':
            return await handleSetPrecision(args);
          
          default:
            return {
              content: [{
                type: 'text',
                text: `Unknown tool: ${name}`
              }],
              isError: true
            };
        }
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Error: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    });
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.

Install Server

Other Tools

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