Overview
This example demonstrates how to build a calculator service with multiple operations using the LeanMCP SDK. You’ll learn how to:- Create multiple tools that share input schemas
- Add validation constraints to prevent errors
- Implement proper error handling
- Handle edge cases like division by zero
- Structure related operations in one service
Complete Example
This example is based on the calculator pattern from the LeanMCP README.Define Shared Input Schema
Create a reusable input schema for mathematical operations:Key points:
- Same schema is reused across multiple operations
minimumandmaximumprevent overflow errors- Clear descriptions help AI agents understand parameters
Define Output Schema
Create a consistent output structure:Key points:
- Simple, consistent output format
- All operations return the same structure
- Easy to extend with additional fields
Implement Basic Operations
Create tools for addition, subtraction, and multiplication:Key points:
- Each operation is a separate tool
- All use the same
CalculatorInputschema - Simple, focused implementations
Add Error Handling
Implement division with proper error handling:Key points:
- Check for edge cases before calculation
- Throw clear, descriptive errors
- Errors are automatically handled by the MCP framework
Add Advanced Operations
Extend with more complex operations:Key points:
- Validate mathematical constraints
- Handle special cases appropriately
- Keep error messages user-friendly
Project Structure
Testing the Service
Start your server:Example Operations
Addition:Enhanced Calculator with History
You can extend the calculator to track operation history:Advanced Input Validation
Add custom validation for specific use cases:Key Takeaways
- Shared Schemas: Reuse input/output classes across related tools
- Error Handling: Validate inputs and throw clear errors
- Edge Cases: Handle special cases like division by zero
- Multiple Tools: Group related operations in one service
- Extensibility: Easy to add new operations or features
- Type Safety: Schemas prevent invalid inputs at runtime
Next Steps
Schema Validation
Learn advanced validation techniques
Error Handling
Master error handling patterns