calculate
Perform mathematical calculations on the MCP Test Server by entering expressions or selecting operations like add, subtract, multiply, or divide with specific numbers.
Instructions
执行数学计算
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| a | No | 第一个数字 | |
| b | No | 第二个数字 | |
| expression | No | 数学表达式,如 '2 + 3 * 4' | |
| operation | No | 基本运算操作 |
Implementation Reference
- src/index.ts:186-257 (handler)The main execution handler for the 'calculate' tool. It evaluates mathematical expressions safely or performs basic arithmetic operations (add, subtract, multiply, divide) based on input parameters, handles errors, logs the operation, and returns the result in MCP content format.}, async (args) => { let result: number; let operation: string; if (args.expression) { // 简单的表达式求值(仅支持基本运算) try { // 安全的数学表达式求值 const sanitized = args.expression.replace(/[^0-9+\-*/().\s]/g, ''); result = Function(`"use strict"; return (${sanitized})`)(); operation = args.expression; } catch (error) { return { content: [{ type: "text", text: `❌ 无效的数学表达式: ${args.expression}` }] }; } } else if (args.operation && args.a !== undefined && args.b !== undefined) { const { operation: op, a, b } = args; switch (op) { case "add": result = a + b; operation = `${a} + ${b}`; break; case "subtract": result = a - b; operation = `${a} - ${b}`; break; case "multiply": result = a * b; operation = `${a} * ${b}`; break; case "divide": if (b === 0) { return { content: [{ type: "text", text: "❌ 错误: 除数不能为零" }] }; } result = a / b; operation = `${a} / ${b}`; break; default: return { content: [{ type: "text", text: `❌ 未知的运算操作: ${op}` }] }; } } else { return { content: [{ type: "text", text: "❌ 请提供数学表达式或运算操作参数" }] }; } testData.logs.push(`计算: ${operation} = ${result}`); return { content: [{ type: "text", text: `🧮 计算结果: ${operation} = ${result}` }] }; });
- src/index.ts:182-185 (schema)Zod input schema defining optional parameters for the calculate tool: expression (string), operation (enum: add/subtract/multiply/divide), a and b (numbers).expression: z.string().optional().describe("数学表达式,如 '2 + 3 * 4'"), operation: z.enum(["add", "subtract", "multiply", "divide"]).optional().describe("基本运算操作"), a: z.number().optional().describe("第一个数字"), b: z.number().optional().describe("第二个数字")
- src/index.ts:181-181 (registration)Registers the 'calculate' tool with the MCP server, specifying name, description, input schema, and handler function.server.tool("calculate", "执行数学计算", {