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

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