Skip to main content
Glama

calculator_tool

Perform mathematical calculations including basic expressions, statistics, geometry, finance, logic, number theory, combinatorics, probability, set theory, and complex numbers.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
calculation_typeYesThe type of calculation to perform.
expressionNoThe mathematical expression to evaluate (for 'evaluate_expression').
statistics_operationNo
data_pointsNo
data_set_xNo
data_set_yNo
geometry_operationNo
radiusNo
lengthNo
widthNo
sideNo
financial_math_operationNo
principalNo
rateNoInterest rate as a percentage (e.g., 5 for 5%).
timeNoTime in years.
n_compounding_periodsNo
future_valueNo
logic_operationNo
operand_aNo
operand_bNo
number_theory_operationNo
number_aNo
number_bNo
number_theory_modulusNo
combinatorics_operationNo
n_valueNo
r_valueNo
probability_operationNo
probability_aNo
probability_bNo
probability_a_given_bNo
probability_b_given_aNo
set_theory_operationNo
set_aNo
set_bNo
complex_number_operationNo
complex_aNoFirst complex number (e.g., '3 + 4i').
complex_bNoSecond complex number (e.g., '1 - 2i').
precision_levelNo

Implementation Reference

  • The main handler function exported as default. It parses the request, sets precision, dispatches to specific helper functions based on calculation_type, and returns the result or error in MCP format.
    export default async function (request: any) {
        try {
            const { calculation_type, ...params } = request.params.arguments;
            const precisionLevel = params.precision_level || 64;
            Decimal.set({ precision: precisionLevel });
    
            let result;
    
            switch (calculation_type) {
                case "evaluate_expression":
                    if (!params.expression) throw new Error("An expression is required.");
                    result = evaluate(params.expression);
                    break;
                case "calculate_statistics":
                    result = handleStatistics(params);
                    break;
                case "perform_geometry":
                    result = handleGeometry(params);
                    break;
                case "perform_financial_math":
                    result = handleFinancialMath(params);
                    break;
                case "perform_logic_operations":
                    result = handleLogicOperations(params);
                    break;
                case "perform_number_theory":
                    result = handleNumberTheory(params);
                    break;
                case "perform_combinatorics":
                    result = handleCombinatorics(params);
                    break;
                case "calculate_probability":
                    result = handleProbability(params);
                    break;
                case "perform_set_theory":
                    result = handleSetTheory(params);
                    break;
                case "perform_complex_number":
                    result = handleComplexNumber(params);
                    break;
                default:
                    throw new Error(`Unsupported calculation type: ${calculation_type}`);
            }
    
            return {
                content: [{
                    type: "text",
                    text: JSON.stringify({ result }, null, 2),
                }],
            };
        } catch (error) {
            return {
                content: [{
                    type: "text",
                    text: JSON.stringify({ error: error instanceof Error ? error.message : String(error) }, null, 2),
                }],
                isError: true,
            };
        }
    }
  • The JSON schema defining the tool's input parameters, including calculation_type and specific params for each operation type.
    export const schema = {
        name: "calculator_tool",
        description: "A powerful universal calculator supporting basic expressions, statistics, geometry, finance, logic, number theory, combinatorics, probability, set theory, and complex numbers.",
        type: "object",
        properties: {
            calculation_type: {
                type: "string",
                enum: [
                    "evaluate_expression", "calculate_statistics", "perform_geometry",
                    "perform_financial_math", "perform_logic_operations", "perform_number_theory",
                    "perform_combinatorics", "calculate_probability", "perform_set_theory",
                    "perform_complex_number"
                ],
                description: "The type of calculation to perform.",
            },
            // Common params
            expression: { type: "string", description: "The mathematical expression to evaluate (for 'evaluate_expression')." },
            // Statistics params
            statistics_operation: { type: "string", enum: ["mean", "median", "mode", "standard_deviation", "variance", "correlation", "regression"] },
            data_points: { type: "array", items: { type: "number" } },
            data_set_x: { type: "array", items: { type: "number" } },
            data_set_y: { type: "array", items: { type: "number" } },
            // Geometry params
            geometry_operation: { type: "string", enum: ["area_circle", "area_rectangle", "volume_cube"] },
            radius: { type: "number" },
            length: { type: "number" },
            width: { type: "number" },
            side: { type: "number" },
            // Financial params
            financial_math_operation: { type: "string", enum: ["simple_interest", "compound_interest", "present_value", "future_value"] },
            principal: { type: "number" },
            rate: { type: "number", description: "Interest rate as a percentage (e.g., 5 for 5%)." },
            time: { type: "number", description: "Time in years." },
            n_compounding_periods: { type: "integer" },
            future_value: { type: "number" },
            // Logic params
            logic_operation: { type: "string", enum: ["AND", "OR", "NOT", "XOR"] },
            operand_a: { type: "boolean" },
            operand_b: { type: "boolean" },
            // Number Theory params
            number_theory_operation: { type: "string", enum: ["gcd", "lcm", "prime_factorization", "is_prime", "modular_exponentiation"] },
            number_a: { type: "integer" },
            number_b: { type: "integer" },
            number_theory_modulus: { type: "integer" },
            // Combinatorics params
            combinatorics_operation: { type: "string", enum: ["permutation", "combination", "factorial", "binomial_coefficient"] },
            n_value: { type: "integer" },
            r_value: { type: "integer" },
            // Probability params
            probability_operation: { type: "string", enum: ["probability_event", "conditional_probability", "bayes_theorem"] },
            probability_a: { type: "number" },
            probability_b: { type: "number" },
            probability_a_given_b: { type: "number" },
            probability_b_given_a: { type: "number" },
            // Set Theory params
            set_theory_operation: { type: "string", enum: ["union", "intersection", "difference", "symmetric_difference", "is_subset"] },
            set_a: { type: "array", items: { "anyOf": [{ "type": "number" }, { "type": "string" }] } },
            set_b: { type: "array", items: { "anyOf": [{ "type": "number" }, { "type": "string" }] } },
            // Complex Number params
            complex_number_operation: { type: "string", enum: ["add", "subtract", "multiply", "divide", "modulus", "argument", "conjugate"] },
            complex_a: { type: "string", description: "First complex number (e.g., '3 + 4i')." },
            complex_b: { type: "string", description: "Second complex number (e.g., '1 - 2i')." },
            // Global params
            precision_level: { type: "number", enum: [32, 64, 128], default: 64 },
        },
        required: ["calculation_type"]
    };
  • The loadTools function dynamically discovers and registers all tools from src/tools directory by filename (e.g., calculator_tool.ts -> calculator_tool), importing their default handler, schema, and destroy functions into global tools and handlers maps.
    export async function loadTools(reload: boolean = false): Promise<{ [key: string]: (request: ToolRequest) => Promise<ToolResponse> }> {
      // 如果是初始加载且已加载,则直接返回
      if (!reload && isLoaded) return;
    
      // 如果是重新加载,则重置状态
      if (reload) {
        for (const tool of tools) {
          await tool?.destroy?.();
          delete handlers[tool.name];
        }
        tools.length = 0;
        isLoaded = false;
      }
    
      // 获取所有工具文件
      const toolFiles = fs.readdirSync(toolsDir).filter(file => file.endsWith('.js') || file.endsWith('.ts'));
    
      // 加载每个工具
      for (const file of toolFiles) {
        const toolPath = path.join(toolsDir, file);
        try {
          // 如果是重新加载,清除模块缓存
          if (reload) clearModuleCache(toolPath);
    
          // 导入模块,重新加载时添加时间戳防止缓存
          const importPath = 'file://' + toolPath + (reload ? `?update=${Date.now()}` : '');
          const { default: tool, schema, destroy } = await import(importPath);
          const toolName = path.parse(toolPath).name;
    
          // 注册工具
          tools.push({
            name: toolName,
            description: tool.description,
            inputSchema: schema,
            destroy: destroy
          });
    
          // 注册处理函数
          handlers[toolName] = async (request: ToolRequest) => { return await tool(request); };
        } catch (error) {
          console.error(`Failed to ${reload ? 'reload' : 'load'} tool ${file}:`, error);
        }
      }
    
      isLoaded = true;
      if (reload) console.log(`Successfully reloaded ${tools.length} tools`);
    
      return handlers;
    }
  • Example helper function for statistics operations, one of many handle* functions that implement specific calculation categories called from the main handler.
    function handleStatistics(params: any) {
        const { statistics_operation, data_points, data_set_x, data_set_y } = params;
        if (!statistics_operation) throw new Error("A statistics operation is required.");
    
        const checkDataPoints = () => {
            if (!data_points || !Array.isArray(data_points) || data_points.length === 0) {
                throw new Error("A non-empty data_points array is required.");
            }
        };
        const checkDataSets = () => {
            if (!data_set_x || !data_set_y || data_set_x.length !== data_set_y.length || data_set_x.length === 0) {
                throw new Error("Two equal-length, non-empty datasets (data_set_x and data_set_y) are required.");
            }
        };
    
        switch (statistics_operation) {
            case "mean": checkDataPoints(); return mean(data_points);
            case "median": checkDataPoints(); return median(data_points);
            case "mode": checkDataPoints(); return mode(data_points);
            case "standard_deviation": checkDataPoints(); return std(data_points);
            case "variance": checkDataPoints(); return variance(data_points);
            case "correlation": checkDataSets(); return evaluate('corr(x, y)', { x: data_set_x, y: data_set_y });
            case "regression":
                checkDataSets();
                const n = data_set_x.length;
                const sumX = data_set_x.reduce((s, v) => s + v, 0);
                const sumY = data_set_y.reduce((s, v) => s + v, 0);
                const sumXY = data_set_x.reduce((s, v, i) => s + v * data_set_y[i], 0);
                const sumX2 = data_set_x.reduce((s, v) => s + v * v, 0);
                const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
                const intercept = (sumY - slope * sumX) / n;
                return { slope, intercept, equation: `y = ${round(slope, 4)}x + ${round(intercept, 4)}` };
            default: throw new Error(`Unsupported statistics operation: ${statistics_operation}`);
        }
    }

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/xiaoguomeiyitian/ToolBox'

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