Skip to main content
Glama
dhinojosac

TypeScript MCP Server Template

by dhinojosac

Calculate

calculate

Perform basic arithmetic operations including addition, subtraction, multiplication, and division within the TypeScript MCP Server Template.

Instructions

Performs basic arithmetic calculations (add, subtract, multiply, divide)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The calculate tool handler: validates args, performs arithmetic operation (add, subtract, multiply, divide), and returns formatted result as text content.
    async (args: { [x: string]: any }) => {
      const { operation, a, b }: CalculateArgs = validateToolArgs(
        CalculateSchema,
        args
      );
    
      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':
          result = a / b;
          break;
        default:
          // This should never happen due to Zod validation, but keeping for safety
          throw new Error(
            `Unknown operation: ${operation}. Supported: add, subtract, multiply, divide`
          );
      }
    
      return {
        content: [
          {
            type: 'text',
            text: `${a} ${operation} ${b} = ${result}`,
          },
        ],
      };
    }
  • Zod schema defining CalculateArgs: operation enum, numbers a/b, with refinement to prevent division by zero.
    export const CalculateSchema = z
      .object({
        operation: z
          .enum(['add', 'subtract', 'multiply', 'divide'], {
            errorMap: () => ({
              message: 'Operation must be one of: add, subtract, multiply, divide',
            }),
          })
          .describe('The arithmetic operation to perform'),
        a: z.number().describe('First number for the calculation'),
        b: z.number().describe('Second number for the calculation'),
      })
      .refine(
        data => {
          if (data.operation === 'divide' && data.b === 0) {
            return false;
          }
          return true;
        },
        {
          message: 'Division by zero is not allowed',
          path: ['b'],
        }
      );
  • src/server.ts:51-94 (registration)
    Registers the 'calculate' tool on the MCP server with title, description, and handler function.
    server.registerTool(
      'calculate',
      {
        title: 'Calculate',
        description:
          'Performs basic arithmetic calculations (add, subtract, multiply, divide)',
      },
      async (args: { [x: string]: any }) => {
        const { operation, a, b }: CalculateArgs = validateToolArgs(
          CalculateSchema,
          args
        );
    
        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':
            result = a / b;
            break;
          default:
            // This should never happen due to Zod validation, but keeping for safety
            throw new Error(
              `Unknown operation: ${operation}. Supported: add, subtract, multiply, divide`
            );
        }
    
        return {
          content: [
            {
              type: 'text',
              text: `${a} ${operation} ${b} = ${result}`,
            },
          ],
        };
      }
    );
  • Utility function to validate tool arguments using Zod schema with custom error formatting, used in calculate handler.
    export function validateToolArgs<T>(schema: z.ZodSchema<T>, args: unknown): T {
      try {
        return schema.parse(args);
      } catch (error) {
        if (error instanceof z.ZodError) {
          const errorMessages = error.errors
            .map(err => `${err.path.join('.')}: ${err.message}`)
            .join(', ');
          throw new Error(`Validation failed: ${errorMessages}`);
        }
        throw error;
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It only states what the tool does (arithmetic operations) without mentioning any behavioral traits like error handling (e.g., division by zero), precision limits, input validation, or response format. This leaves significant gaps for a tool that performs calculations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's function with zero wasted words. It is appropriately sized and front-loaded, making it easy for an agent to quickly understand the core purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (performing calculations with potential behavioral nuances) and the absence of both annotations and an output schema, the description is incomplete. It lacks information on error conditions, result formatting, or operational limits, which are crucial for an AI agent to use this tool correctly in varied contexts.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0 parameters with 100% coverage, so the baseline is 4. The description adds value by specifying the types of calculations supported (add, subtract, multiply, divide), which provides semantic context beyond the empty schema, though it doesn't detail parameter formats since none exist.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as performing basic arithmetic calculations with specific operations listed (add, subtract, multiply, divide). It uses a specific verb ('performs') and identifies the resource (calculations), though it doesn't distinguish from siblings since this is the only calculation tool among weather and greeting siblings.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention any prerequisites, constraints, or context for choosing this tool over other methods, leaving the agent with no usage direction beyond the stated purpose.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/dhinojosac/calendar-mcp'

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