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
| Name | Required | Description | Default |
|---|---|---|---|
| calculation_type | Yes | The type of calculation to perform. | |
| expression | No | The mathematical expression to evaluate (for 'evaluate_expression'). | |
| statistics_operation | No | ||
| data_points | No | ||
| data_set_x | No | ||
| data_set_y | No | ||
| geometry_operation | No | ||
| radius | No | ||
| length | No | ||
| width | No | ||
| side | No | ||
| financial_math_operation | No | ||
| principal | No | ||
| rate | No | Interest rate as a percentage (e.g., 5 for 5%). | |
| time | No | Time in years. | |
| n_compounding_periods | No | ||
| future_value | No | ||
| logic_operation | No | ||
| operand_a | No | ||
| operand_b | No | ||
| number_theory_operation | No | ||
| number_a | No | ||
| number_b | No | ||
| number_theory_modulus | No | ||
| combinatorics_operation | No | ||
| n_value | No | ||
| r_value | No | ||
| probability_operation | No | ||
| probability_a | No | ||
| probability_b | No | ||
| probability_a_given_b | No | ||
| probability_b_given_a | No | ||
| set_theory_operation | No | ||
| set_a | No | ||
| set_b | No | ||
| complex_number_operation | No | ||
| complex_a | No | First complex number (e.g., '3 + 4i'). | |
| complex_b | No | Second complex number (e.g., '1 - 2i'). | |
| precision_level | No |
Implementation Reference
- src/tools/calculator_tool.ts:283-342 (handler)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, }; } }
- src/tools/calculator_tool.ts:5-71 (schema)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"] };
- src/handler/ToolHandler.ts:91-139 (registration)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; }
- src/tools/calculator_tool.ts:75-109 (helper)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}`); } }