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
        };
      }
    });
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