Skip to main content
Glama
yigitkonur

example-mcp-server-stdio

by yigitkonur

Calculate

calculate

Perform basic arithmetic calculations with two numbers using addition, subtraction, multiplication, or division operations.

Instructions

Perform a basic arithmetic calculation

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
aYesFirst operand
bYesSecond operand
opYesOperation to perform
streamNoIf true, emit progress notifications

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
metaYes
valueYes

Implementation Reference

  • The handler function for the 'calculate' tool. It handles input parameters, optional streaming progress, calls the core calculation helper, manages history, and returns structured output with error handling.
    async ({ a, b, op, stream }, { sendNotification }) => {
      log.info(`Executing calculate: ${a} ${op} ${b}`);
      requestCount++;
    
      try {
        // FEATURE: Progress notifications for streaming calculations
        // WHY: Demonstrates real-time feedback using sendNotification
        if (stream) {
          const progressId = `calc-${Date.now()}`;
          await sendNotification({
            method: 'notifications/progress',
            params: {
              progressToken: progressId,
              progress: 33,
              message: `Calculating ${a} ${op} ${b}`,
            },
          });
          await new Promise((resolve) => setTimeout(resolve, 100));
          await sendNotification({
            method: 'notifications/progress',
            params: { progressToken: progressId, progress: 66 },
          });
          await new Promise((resolve) => setTimeout(resolve, 100));
          await sendNotification({
            method: 'notifications/progress',
            params: { progressToken: progressId, progress: 100, message: 'Complete' },
          });
          await new Promise((resolve) => setTimeout(resolve, 100));
        }
    
        // Core business logic: perform the calculation
        const result = performBasicCalculation(op, a, b);
    
        // Create and store history entry
        const historyEntry = createHistoryEntry(op, a, b, result);
        addToHistory(historyEntry);
    
        // SDK-NOTE: The return object must match the `outputSchema`.
        // The SDK will validate this before sending the response.
        // We provide both a simple text `content` for basic UIs and a
        // `structuredContent` for richer clients.
        return {
          content: [
            {
              type: 'text',
              text: historyEntry.expression,
            },
          ],
          structuredContent: {
            value: result,
            meta: {
              calculationId: historyEntry.id,
              timestamp: historyEntry.timestamp,
            },
          },
        };
      } catch (error) {
        // CAVEAT: We catch the error from our business logic and re-throw it.
        // While `performBasicCalculation` already returns an McpError, this pattern
        // is crucial for wrapping any *unexpected* errors that might occur,
        // preventing stack traces from leaking to the client.
        log.error(`Calculation failed: ${error instanceof Error ? error.message : String(error)}`);
        throw new McpError(
          ErrorCode.InvalidParams,
          `Calculation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
          { operation: op, a, b },
        );
      }
    },
  • Zod input and output schemas for the 'calculate' tool, defining parameters a, b, op (enum of arithmetic operations), optional stream flag, and output value with metadata.
    const calculateInputSchema = {
      a: z.number().describe('First operand'),
      b: z.number().describe('Second operand'),
      op: z.enum(['add', 'subtract', 'multiply', 'divide']).describe('Operation to perform'),
      stream: z.boolean().optional().describe('If true, emit progress notifications'),
    };
    
    const calculateOutputSchema = {
      value: z.number(),
      meta: z.object({
        calculationId: z.string(),
        timestamp: z.string(),
      }),
    };
  • src/server.ts:274-355 (registration)
    Registration of the 'calculate' tool with the MCP server, including title, description, schemas, and handler function.
    server.registerTool(
      'calculate',
      {
        title: 'Calculate',
        description: 'Perform a basic arithmetic calculation',
        inputSchema: calculateInputSchema,
        outputSchema: calculateOutputSchema,
      },
      // HANDLER LOGIC:
      // - Async function, receives validated & typed parameters.
      // - The SDK automatically parses the input against `inputSchema`.
      // - If validation fails, the SDK sends the error; this code doesn't run.
      async ({ a, b, op, stream }, { sendNotification }) => {
        log.info(`Executing calculate: ${a} ${op} ${b}`);
        requestCount++;
    
        try {
          // FEATURE: Progress notifications for streaming calculations
          // WHY: Demonstrates real-time feedback using sendNotification
          if (stream) {
            const progressId = `calc-${Date.now()}`;
            await sendNotification({
              method: 'notifications/progress',
              params: {
                progressToken: progressId,
                progress: 33,
                message: `Calculating ${a} ${op} ${b}`,
              },
            });
            await new Promise((resolve) => setTimeout(resolve, 100));
            await sendNotification({
              method: 'notifications/progress',
              params: { progressToken: progressId, progress: 66 },
            });
            await new Promise((resolve) => setTimeout(resolve, 100));
            await sendNotification({
              method: 'notifications/progress',
              params: { progressToken: progressId, progress: 100, message: 'Complete' },
            });
            await new Promise((resolve) => setTimeout(resolve, 100));
          }
    
          // Core business logic: perform the calculation
          const result = performBasicCalculation(op, a, b);
    
          // Create and store history entry
          const historyEntry = createHistoryEntry(op, a, b, result);
          addToHistory(historyEntry);
    
          // SDK-NOTE: The return object must match the `outputSchema`.
          // The SDK will validate this before sending the response.
          // We provide both a simple text `content` for basic UIs and a
          // `structuredContent` for richer clients.
          return {
            content: [
              {
                type: 'text',
                text: historyEntry.expression,
              },
            ],
            structuredContent: {
              value: result,
              meta: {
                calculationId: historyEntry.id,
                timestamp: historyEntry.timestamp,
              },
            },
          };
        } catch (error) {
          // CAVEAT: We catch the error from our business logic and re-throw it.
          // While `performBasicCalculation` already returns an McpError, this pattern
          // is crucial for wrapping any *unexpected* errors that might occur,
          // preventing stack traces from leaking to the client.
          log.error(`Calculation failed: ${error instanceof Error ? error.message : String(error)}`);
          throw new McpError(
            ErrorCode.InvalidParams,
            `Calculation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
            { operation: op, a, b },
          );
        }
      },
    );
  • Core helper function that executes the basic arithmetic logic based on the operation type, with validation for division by zero and unknown operations.
    function performBasicCalculation(op: string, a: number, b: number): number {
      switch (op) {
        case 'add':
          return a + b;
        case 'subtract':
          return a - b;
        case 'multiply':
          return a * b;
        case 'divide':
          if (b === 0) throw new McpError(ErrorCode.InvalidParams, 'Division by zero');
          return a / b;
        default:
          throw new McpError(ErrorCode.InvalidParams, `Unknown operation: ${op}`);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'Perform a basic arithmetic calculation' implies a read-only operation but doesn't specify if it's stateless, has side effects, requires permissions, or handles errors. It mentions nothing about the 'stream' parameter's behavior (progress notifications), rate limits, or output format, leaving significant gaps in understanding how the tool behaves beyond its basic function.

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: 'Perform a basic arithmetic calculation'. It's front-loaded with the core purpose, has zero wasted words, and is appropriately sized for a simple tool. Every part of the sentence earns its place by conveying the essential action and resource.

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

Completeness3/5

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

Given the tool's low complexity (basic arithmetic) and the presence of a rich input schema (100% coverage) and output schema, the description is minimally adequate. However, with no annotations and multiple sibling tools, it fails to provide context on differentiation or behavioral details like error handling. The description covers the 'what' but lacks the 'when' and 'how' needed for full completeness in this environment.

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

Parameters3/5

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

The schema description coverage is 100%, with clear descriptions for all parameters (e.g., 'First operand', 'Operation to perform', 'If true, emit progress notifications'). The description adds no additional meaning beyond what the schema provides, as it doesn't explain parameter interactions, constraints, or examples. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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

Purpose3/5

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

The description 'Perform a basic arithmetic calculation' clearly states the tool's purpose with a specific verb ('perform') and resource ('arithmetic calculation'). However, it doesn't distinguish this from sibling tools like 'advanced_calculate', 'batch_calculate', or 'solve_math_problem', leaving the scope of 'basic' ambiguous. The description is functional but lacks differentiation from alternatives.

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 its siblings. With tools like 'advanced_calculate', 'batch_calculate', and 'solve_math_problem' available, there's no indication of what makes this tool 'basic' or when to choose it over others. No context, exclusions, or alternatives are mentioned, leaving usage decisions unclear.

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/yigitkonur/example-mcp-server-stdio'

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