Skip to main content

Calculator Operations Server

This example demonstrates how to build a simple MCP server in Python using the FastMCP framework. It’s perfect for understanding the basics of MCP tool implementation.

Overview

The Calculator server shows:
  • FastMCP Framework: Quick server setup with minimal boilerplate
  • Tool Registration: Simple decorator-based tool registration
  • Input Validation: Parameter validation and error handling
  • Basic Operations: Addition, subtraction, multiplication, and division

Complete Implementation

server.py

Understanding the Code

FastMCP Initialization

FastMCP provides a simple way to create MCP servers with minimal configuration. The server name is used for identification.

Tool Decorator

The @mcp.tool() decorator automatically:
  • Registers the function as an MCP tool
  • Extracts parameter types from type hints
  • Generates JSON schema for the tool
  • Handles serialization/deserialization

Error Handling

Errors are propagated to the client as tool execution errors, making debugging easier.

Installation & Setup

Dependencies

Create a pyproject.toml or requirements.txt:
pyproject.toml
Or using requirements.txt:
requirements.txt

Installation

Running the Server

Standalone Mode

The server runs in stdio mode, waiting for MCP client connections.

With MCP Inspector

Use the MCP Inspector to test your server:

Using the Calculator

From Python Client

client.py

Expected Output

Testing Operations

Addition

Subtraction

Multiplication

Division

Error Case: Division by Zero

Configuration for Claude Desktop

claude_desktop_config.json
Restart Claude Desktop after adding the configuration.

Extending the Calculator

Adding More Operations

Scientific Calculator

Key Advantages of FastMCP

  1. Minimal Boilerplate: No need to manually define schemas
  2. Type Hints: Automatic parameter validation from Python types
  3. Easy Debugging: Clear error messages and stack traces
  4. Rapid Development: Get a server running in minutes

Common Patterns

Input Validation

Default Parameters

Troubleshooting

Server Not Starting

  • Ensure mcp package is installed: pip install mcp
  • Check Python version: python --version (should be 3.10+)
  • Verify the script has no syntax errors

Tool Not Found

  • Ensure the @mcp.tool() decorator is present
  • Check that the function is defined before mcp.run()
  • Verify the server is running in stdio mode

Type Errors

  • Use proper type hints: float, int, str, etc.
  • FastMCP uses type hints for validation

Next Steps