Skip to main content
Glama
cthunter01

BC Calculator MCP Server

by cthunter01

calculate_advanced

Execute advanced BC scripts with variables, functions, and control flow for arbitrary precision arithmetic and complex mathematical computations.

Instructions

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

Input Schema

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

Implementation Reference

  • Main handler for calculate_advanced tool: validates script and precision, sanitizes input, executes BC script via process pool, returns result with metrics or error.
    async function handleCalculateAdvanced(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 { script, precision = globalPrecision } = args as {
        script?: string;
        precision?: number;
      };
    
      if (!script) {
        return {
          content: [{
            type: 'text',
            text: 'Missing required argument: script'
          }],
          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 script
        const validation = InputValidator.validate(script);
        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
          await process.setPrecision(precision);
          
          // Execute script
          const result = await process.evaluate(validation.sanitized!);
          
          // Release process
          pool.releaseProcess(process);
          
          const executionTime = Date.now() - startTime;
          
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                result,
                script: script.substring(0, 100) + (script.length > 100 ? '...' : ''),
                precision,
                executionTimeMs: executionTime
              }, null, 2)
            }]
          };
        } catch (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: `Script execution error: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • Python handler for calculate_advanced tool: similar logic to TS version, validates args, executes sanitized BC script via pool, returns JSON response.
    async def handle_calculate_advanced(args: dict[str, Any]) -> list[TextContent]:
        """Handle advanced calculation requests with multi-line scripts"""
        import time
        start_time = time.time()
        
        # Get arguments with defaults
        script = args.get("script")
        precision = args.get("precision", global_precision)
        
        if not script:
            return [TextContent(
                type="text",
                text="Missing required argument: script"
            )]
        
        # 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 script
            validation = InputValidator.validate(script)
            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
                await process.set_precision(precision)
                
                # Execute script
                result = await process.evaluate(validation.sanitized or script)
                
                # Release process
                pool.release_process(process)
                
                execution_time = (time.time() - start_time) * 1000
                
                # Truncate script in response if too long
                script_preview = script[:100] + ("..." if len(script) > 100 else "")
                
                return [TextContent(
                    type="text",
                    text=json.dumps({
                        "result": result,
                        "script": script_preview,
                        "precision": precision,
                        "executionTimeMs": execution_time
                    }, indent=2)
                )]
            except Exception as 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"Script execution error: {str(error)}"
            )]
  • Input schema definition for the calculate_advanced tool in the TOOLS array.
    {
      name: 'calculate_advanced',
      description: 'Execute advanced BC scripts with variables, functions, and control flow. ' +
                   'Supports multi-line scripts, variable assignments, loops, and conditionals.',
      inputSchema: {
        type: 'object',
        properties: {
          script: {
            type: 'string',
            description: 'Multi-line BC script with variables, loops, or functions'
          },
          precision: {
            type: 'number',
            description: 'Number of decimal places for results (0-100, default: 20)',
            minimum: 0,
            maximum: 100
          }
        },
        required: ['script']
      }
    },
  • Input schema definition for the calculate_advanced tool in Python TOOLS list.
    Tool(
        name="calculate_advanced",
        description=(
            "Execute advanced BC scripts with variables, functions, and control flow. "
            "Supports multi-line scripts, variable assignments, loops, and conditionals."
        ),
        inputSchema={
            "type": "object",
            "properties": {
                "script": {
                    "type": "string",
                    "description": "Multi-line BC script with variables, loops, or functions"
                },
                "precision": {
                    "type": "number",
                    "description": "Number of decimal places for results (0-100, default: 20)",
                    "minimum": 0,
                    "maximum": 100
                }
            },
            "required": ["script"]
        }
    ),
  • Dispatch/registration in the tool execution switch statement.
    case 'calculate_advanced':
      return await handleCalculateAdvanced(args);
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