calculate
Perform mathematical operations like addition, subtraction, multiplication, and division using defined inputs for precise calculations on the MCP Server.
Instructions
Perform basic mathematical calculations
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| a | Yes | First number | |
| b | Yes | Second number | |
| operation | Yes | The mathematical operation to perform |
Implementation Reference
- src/index.ts:135-170 (handler)The core handler logic for the 'calculate' tool within the CallToolRequestSchema handler. It validates inputs, executes the arithmetic operation, handles errors like division by zero, and formats the result.case 'calculate': const operation = validateString(args.operation, 'operation'); const a = validateNumber(args.a, 'a'); const b = validateNumber(args.b, 'b'); let result: number; switch (operation) { case 'add': result = a + b; break; case 'subtract': result = a - b; break; case 'multiply': result = a * b; break; case 'divide': if (b === 0) { throw new Error('Division by zero is not allowed'); } result = a / b; break; default: throw new Error(`Unknown operation: ${operation}`); } return { content: [ { type: 'text', text: `Result: ${result}`, } as TextContent, ], };
- src/index.ts:61-79 (schema)JSON schema defining the input parameters for the 'calculate' tool: operation as enum, and numeric arguments a and b.inputSchema: { type: 'object', properties: { operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'], description: 'The mathematical operation to perform', }, a: { type: 'number', description: 'First number', }, b: { type: 'number', description: 'Second number', }, }, required: ['operation', 'a', 'b'], },
- src/index.ts:58-80 (registration)Registration of the 'calculate' tool in the tools array, which is returned by ListToolsRequestSchema handler.{ name: 'calculate', description: 'Perform basic mathematical calculations', inputSchema: { type: 'object', properties: { operation: { type: 'string', enum: ['add', 'subtract', 'multiply', 'divide'], description: 'The mathematical operation to perform', }, a: { type: 'number', description: 'First number', }, b: { type: 'number', description: 'Second number', }, }, required: ['operation', 'a', 'b'], }, },
- src/index.ts:20-26 (helper)Helper function to validate and parse numeric inputs, used in the 'calculate' handler.const validateNumber = (value: unknown, fieldName: string): number => { const num = Number(value); if (isNaN(num)) { throw new Error(`${fieldName} must be a valid number`); } return num; };