Skip to main content
Glama
yigitkonur

example-mcp-server-stdio

by yigitkonur

Solve Math Problem

solve_math_problem

Solve mathematical word problems and expressions by providing step-by-step solutions upon request.

Instructions

Solve a word problem or mathematical expression (may request user input)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
problemYesThe math problem to solve
showStepsNoShow step-by-step solution

Implementation Reference

  • Handler logic for 'solve_math_problem' tool. Parses the problem string to detect area calculations for basic shapes (rectangle, circle), uses elicitInput to request missing dimensions, computes area using basic arithmetic, returns formatted text response with optional step-by-step explanation, handles user cancellation and elicitInput errors.
      async ({ problem, showSteps }) => {
        log.info('Solving math problem');
        requestCount++;
    
        // Check for ambiguous area problems
        if (problem.toLowerCase().includes('area') && !problem.match(/\d+/)) {
          // Determine shape type
          let shape = 'unknown';
          if (problem.toLowerCase().includes('rectangle')) shape = 'rectangle';
          else if (problem.toLowerCase().includes('circle')) shape = 'circle';
          else if (problem.toLowerCase().includes('triangle')) shape = 'triangle';
    
          if (shape === 'rectangle') {
            try {
              const result = await server.server.elicitInput({
                message: 'I need the dimensions to calculate the area of a rectangle.',
                requestedSchema: {
                  type: 'object',
                  properties: {
                    length: { type: 'number', description: 'Length of the rectangle' },
                    width: { type: 'number', description: 'Width of the rectangle' },
                  },
                  required: ['length', 'width'],
                },
              });
    
              if (result.action === 'accept') {
                const { length, width } = result.content as { length: number; width: number };
                const area = length * width;
                const steps = showSteps
                  ? `\n### Steps:\n1. Formula: Area = length × width\n2. Substitution: Area = ${length} × ${width}\n3. Calculation: Area = ${area}\n`
                  : '';
                return {
                  content: [
                    {
                      type: 'text',
                      text: `## Area of Rectangle\n\nThe area is ${length} × ${width} = ${area} square units.${steps}`,
                    },
                  ],
                };
              } else {
                return { content: [{ type: 'text', text: 'Area calculation cancelled by user.' }] };
              }
            } catch (e) {
              // NOTE: `elicitInput` can fail for several reasons: the transport
              // was closed, the request timed out, or the client explicitly
              // rejected the elicitation. We wrap this in a generic InternalError
              // because from the tool's perspective, its interactive flow was
              // unexpectedly interrupted.
              throw new McpError(
                ErrorCode.InternalError,
                'Failed to complete interactive input with the user.',
              );
            }
          } else if (shape === 'circle') {
            try {
              const result = await server.server.elicitInput({
                message: 'I need the radius to calculate the area of a circle.',
                requestedSchema: {
                  type: 'object',
                  properties: {
                    radius: { type: 'number', description: 'Radius of the circle' },
                  },
                  required: ['radius'],
                },
              });
    
              if (result.action === 'accept') {
                const { radius } = result.content as { radius: number };
                const area = Math.PI * radius * radius;
                const steps = showSteps
                  ? `\n### Steps:\n1. Formula: Area = π × r²\n2. Substitution: Area = π × ${radius}²\n3. Calculation: Area = ${area.toFixed(2)}\n`
                  : '';
                return {
                  content: [
                    {
                      type: 'text',
                      text: `## Area of Circle\n\nThe area is π × ${radius}² = ${area.toFixed(2)} square units.${steps}`,
                    },
                  ],
                };
              } else {
                return { content: [{ type: 'text', text: 'Area calculation cancelled by user.' }] };
              }
            } catch (e) {
              // NOTE: `elicitInput` can fail for several reasons: the transport
              // was closed, the request timed out, or the client explicitly
              // rejected the elicitation. We wrap this in a generic InternalError
              // because from the tool's perspective, its interactive flow was
              // unexpectedly interrupted.
              throw new McpError(
                ErrorCode.InternalError,
                'Failed to complete interactive input with the user.',
              );
            }
          }
        }
    
        // Default response for non-area or non-ambiguous problems
        return {
          content: [
            {
              type: 'text',
              text:
                `## Solving: ${problem}\n\n` +
                `This problem would be solved using appropriate mathematical methods.\n` +
                `${showSteps ? '\n### Steps:\n1. Analyze the problem\n2. Identify key values\n3. Apply appropriate formula\n4. Calculate result\n' : ''}`,
            },
          ],
        };
      },
    );
  • Input schema using Zod for the 'solve_math_problem' tool, defining required 'problem' string parameter and optional 'showSteps' boolean.
    const solveMathProblemInputSchema = {
      problem: z.string().describe('The math problem to solve'),
      showSteps: z.boolean().optional().describe('Show step-by-step solution'),
    };
  • src/server.ts:629-635 (registration)
    Registration of the 'solve_math_problem' tool on the MCP server, specifying name, title, description, and input schema reference. The handler is provided inline immediately after.
    server.registerTool(
      'solve_math_problem',
      {
        title: 'Solve Math Problem',
        description: 'Solve a word problem or mathematical expression (may request user input)',
        inputSchema: solveMathProblemInputSchema,
      },
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'may request user input', which is useful context about potential interactive behavior. However, it doesn't address important aspects like whether this is a read-only operation, computational limits, error handling, or output format.

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

Conciseness4/5

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

The description is very concise - just one sentence that efficiently communicates the core functionality. It's appropriately sized and front-loaded with the main purpose, though the parenthetical about user input could be integrated more smoothly.

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?

For a tool with no annotations and no output schema, the description is insufficient. It doesn't explain what kind of output to expect, what mathematical domains are supported, computational limitations, or how the 'may request user input' feature works. The agent would be left guessing about important behavioral aspects.

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?

Schema description coverage is 100%, so the schema already documents both parameters thoroughly. The description doesn't add any additional meaning about the parameters beyond what's in the schema. The baseline of 3 is appropriate when the schema does the heavy lifting.

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: 'Solve a word problem or mathematical expression' with the additional context 'may request user input'. This specifies both the verb ('solve') and the resource ('math problem'), though it doesn't explicitly differentiate from sibling tools like 'calculate' or 'advanced_calculate'.

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?

No guidance is provided on when to use this tool versus alternatives like 'calculate', 'advanced_calculate', or 'explain_formula'. The description only states what the tool does, not when it's appropriate or what distinguishes it from similar tools in the server.

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