calculate
Perform basic mathematical operations like addition, subtraction, multiplication, and division with two numbers to solve calculation problems.
Instructions
Perform basic mathematical calculations
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| operation | Yes | The mathematical operation to perform | |
| a | Yes | First number | |
| b | Yes | Second number |
Implementation Reference
- src/index.ts:135-170 (handler)The execution logic for the 'calculate' tool. Validates inputs using helper functions, performs the arithmetic operation based on the 'operation' parameter, handles errors like division by zero, and returns 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:58-80 (schema)The tool definition and input schema for 'calculate' used in tool listing (registration). Defines required parameters: operation (enum), a and b (numbers).{ 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 for input validation of numbers, 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; };
- src/index.ts:13-18 (helper)Helper function for input validation of strings, used in the calculate handler for operation.const validateString = (value: unknown, fieldName: string): string => { if (typeof value !== 'string') { throw new Error(`${fieldName} must be a string`); } return value; };