leksval/proportio
If you are the rightful owner of proportio and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
Proportio is a precision proportion calculator designed for LLM agents and applications requiring accurate mathematical operations.
percent_of
Calculate percentage relationships.
solve_proportion
Solve missing proportion terms.
scale_by_ratio
Apply scaling ratios.
direct_k
Find proportionality constants.
resize_dimensions
Scale dimensional pairs.
title: Proportio โ Precision Proportion Calculator emoji: ๐งฎ colorFrom: red colorTo: gray sdk: gradio app_file: app.py pinned: false license: apache-2.0 tags:
- mcp-server
- proportion-calculator
- gradio
- python
- mathematics
- llm-tools

Professional mathematical calculations for proportions, percentages, and scaling operations with assertion-based validation and MCP server integration.
Live Demo
๐ฏ Overview
Proportio is a specialized mathematical calculation server designed for LLM agents and applications requiring precise proportion calculations. Built with assertion-based validation and zero-tolerance error handling, it provides reliable mathematical operations through both a web interface and Model Context Protocol (MCP) integration.
Key Use Cases
- Recipe Scaling: Scale ingredient quantities for different serving sizes
- Financial Calculations: Calculate percentages, ratios, and proportional growth
- Engineering: Resize dimensions, scale measurements, and maintain proportional relationships
- Data Analysis: Compute percentages, ratios, and proportional transformations
- LLM Integration: Provide reliable mathematical operations through MCP protocol
https://github.com/user-attachments/assets/96d30b20-1bf0-4b2b-a1ea-d0a5776f547c
โจ Features
๐ข Mathematical Functions
- Percentage Calculations - Convert parts to percentages with precision
- Proportion Solving - Solve missing terms in a/b = c/d relationships
- Ratio Scaling - Scale values by precise ratios
- Proportionality Constants - Find k in y = kx relationships
- Dimension Resizing - Uniform scaling of width/height pairs
๐ก๏ธ Validation Architecture
- Assertion-Based Validation - Explicit mathematical preconditions
- Zero Exception Handling - No try-catch blocks, fast failure detection
- Precise Error Messages - Clear, actionable error descriptions
- Type Safety - Robust input validation and type checking
๐ Integration Options
- Web Interface - Professional Gradio-based UI with custom branding
- MCP Server - Native Model Context Protocol support for LLM agents
- Docker Ready - Containerized deployment with security best practices
- API Access - Direct function calls with comprehensive documentation
๐จ Professional Design
- Custom Branding - Red-black-white theme with geometric logo
- Responsive Layout - Optimized for desktop and mobile devices
- Split Results - Clear separation of input/output sections
- Error Handling - User-friendly error messages and validation
๐ Table of Contents
- ๐ฏ Overview
- โจ Features
- ๐ Quick Start
- ๐ง Core Functions
- ๐๏ธ Architecture
- ๐ฆ Installation
- ๐ณ Docker Deployment
- ๐งช Testing
- ๐ MCP Integration
- ๐ API Reference
- ๐ ๏ธ Development
- ๐ License
๐ Quick Start
Using Docker (Recommended)
# Clone the repository
git clone https://github.com/leksval/proportio.git
cd proportio
# Build and run with Docker
docker build -t proportio-server .
docker run -p 7860:7860 proportio-server
# Access the web interface
open http://localhost:7860
Local Development
# Install dependencies
pip install -r requirements.txt
# Run the server
python proportion_server.py
# Access the web interface
open http://localhost:7860
Quick Function Examples
from proportion_server import percent_of, solve_proportion, resize_dimensions
# Calculate percentage
result = percent_of(25, 100) # Returns: 25.0
# Solve proportion: 3/4 = 6/?
result = solve_proportion(3, 4, 6, None) # Returns: 8.0
# Resize dimensions by 2x
width, height = resize_dimensions(100, 50, 2.0) # Returns: (200.0, 100.0)
๐ง Core Functions
1. percent_of(part, whole)
Calculate what percentage the part is of the whole.
percent_of(25, 100) # โ 25.0%
percent_of(3, 4) # โ 75.0%
percent_of(150, 100) # โ 150.0%
Mathematical Preconditions:
whole != 0
(division by zero protection)
Real-world Examples:
- Sales conversion rates
- Test score percentages
- Growth rate calculations
2. solve_proportion(a, b, c, d)
Solve missing term in proportion a/b = c/d (exactly one parameter must be None).
solve_proportion(3, 4, 6, None) # โ 8.0 (3/4 = 6/8)
solve_proportion(None, 4, 6, 8) # โ 3.0 (?/4 = 6/8)
solve_proportion(2, None, 6, 9) # โ 3.0 (2/? = 6/9)
Mathematical Preconditions:
- Exactly one value must be None (missing)
- Division denominators != 0 (varies by missing value)
Real-world Examples:
- Recipe scaling (4 servings : 2 cups = 6 servings : ? cups)
- Currency exchange rates
- Map scale calculations
3. scale_by_ratio(value, ratio)
Scale a value by a given ratio.
scale_by_ratio(100, 1.5) # โ 150.0
scale_by_ratio(200, 0.5) # โ 100.0
scale_by_ratio(50, 2.0) # โ 100.0
Use Cases:
- Applying discount percentages
- Scaling measurements
- Financial calculations
4. direct_k(x, y)
Find proportionality constant k in direct variation y = kx.
direct_k(5, 15) # โ 3.0 (15 = 3 ร 5)
direct_k(4, 12) # โ 3.0 (12 = 3 ร 4)
direct_k(2, 7) # โ 3.5 (7 = 3.5 ร 2)
Mathematical Preconditions:
x != 0
(division by zero protection)
Applications:
- Physics calculations (force = k ร displacement)
- Economics (cost = k ร quantity)
- Engineering (stress = k ร strain)
5. resize_dimensions(width, height, scale)
Resize dimensions with uniform scale factor.
resize_dimensions(100, 50, 2.0) # โ (200.0, 100.0)
resize_dimensions(200, 100, 0.5) # โ (100.0, 50.0)
resize_dimensions(150, 75, 1.5) # โ (225.0, 112.5)
Mathematical Preconditions:
width >= 0
(dimensions must be non-negative)height >= 0
(dimensions must be non-negative)scale > 0
(scale factor must be positive)
Applications:
- Image resizing
- Screen resolution scaling
- Architectural drawings
๐๏ธ Architecture
Assertion-Based Validation
Proportio uses assertion-based validation throughout, providing several key advantages:
def percent_of(part: float, whole: float) -> float:
# Mathematical preconditions
assert whole != 0, "Division by zero: whole cannot be zero"
# Direct calculation
percentage = (part / whole) * 100
return percentage
Benefits:
- Fast Failure: Immediate error detection with precise messages
- No Exception Overhead: Zero try-catch complexity
- Clear Preconditions: Mathematical requirements explicitly documented
- Predictable Behavior: Consistent error handling across all functions
Project Structure
proportio/
โโโ proportion_server.py # Core mathematical functions + Gradio server
โโโ models.py # Pydantic data models (simplified)
โโโ config.py # Configuration and logging setup
โโโ styles.css # Custom branding and responsive design
โโโ tests/
โ โโโ test_tools.py # Comprehensive test suite (58 tests)
โโโ requirements.txt # Minimal dependencies (3 packages)
โโโ Dockerfile # Single-stage containerization
โโโ README.md # This documentation
Dependency Architecture
Streamlined Dependencies (only 3 required):
gradio[mcp]>=5.0.0
- Web framework with MCP server capabilitiespydantic>=2.8.0
- Data validation and parsingpytest>=8.0.0
- Testing framework
Error Handling Philosophy
No Try-Catch Blocks - All validation done through assertions:
# โ Old approach (complex exception handling)
try:
if whole == 0:
raise ValueError("Division by zero")
result = part / whole
except ValueError as e:
# Handle error...
# โ
New approach (assertion-based)
assert whole != 0, "Division by zero: whole cannot be zero"
result = part / whole
๐ฆ Installation
System Requirements
- Python 3.11+
- pip package manager
- Docker (optional, for containerized deployment)
Local Installation
# Clone repository
git clone https://github.com/leksval/proportio.git
cd proportio
# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Verify installation
python -c "from proportion_server import percent_of; print(percent_of(25, 100))"
Development Installation
# Install with development dependencies
pip install -r requirements.txt
# Run tests to verify setup
python -m pytest tests/test_tools.py -v
# Start development server
python proportion_server.py
๐ณ Docker Deployment
Building the Container
# Build image
docker build -t proportio-server .
# Run container
docker run -p 7860:7860 proportio-server
# Run with custom configuration
docker run -p 8080:7860 -e PORT=7860 proportio-server
Container Features
- Security: Non-root user execution
- Optimization: Single-stage build for minimal image size
- Flexibility: Configurable port and environment settings
- Health: Automatic process management
Production Deployment
# Run detached with restart policy
docker run -d \
--name proportio \
--restart unless-stopped \
-p 7860:7860 \
proportio-server
# View logs
docker logs proportio
# Stop container
docker stop proportio
๐งช Testing
Test Suite Coverage
58 comprehensive tests covering:
- โ Basic functionality for all 5 core functions
- โ Edge cases and boundary conditions
- โ Error handling and assertion validation
- โ Integration workflows and chained calculations
- โ Floating-point precision and mathematical accuracy
- โ Type validation and input sanitization
Running Tests
# Run all tests
python -m pytest tests/test_tools.py -v
# Run specific test class
python -m pytest tests/test_tools.py::TestPercentOf -v
# Run with coverage (if pytest-cov installed)
python -m pytest tests/test_tools.py --cov=proportion_server
# Run tests in Docker
docker run --rm proportio-server python -m pytest tests/test_tools.py -v
Test Categories
Unit Tests
- Individual function validation
- Mathematical accuracy verification
- Error condition testing
Integration Tests
- Chained calculation workflows
- Real-world scenario testing
- Cross-function compatibility
Edge Case Tests
- Floating-point precision limits
- Very large and very small numbers
- Boundary condition validation
Sample Test Output
==================== test session starts ====================
collected 58 items
tests/test_tools.py::TestPercentOf::test_basic_percentage PASSED
tests/test_tools.py::TestPercentOf::test_zero_part PASSED
tests/test_tools.py::TestPercentOf::test_negative_values PASSED
...
tests/test_tools.py::TestIntegration::test_real_world_recipe_scaling PASSED
tests/test_tools.py::TestIntegration::test_financial_calculation_workflow PASSED
==================== 58 passed in 0.45s ====================
๐ MCP Integration
Model Context Protocol Support
Proportio provides native MCP server capabilities for seamless LLM integration:
# Launch with MCP support
demo.launch(
server_name="0.0.0.0",
server_port=7860,
mcp_server=True, # Enable MCP functionality
show_error=True
)
Using with LLM Agents
The MCP server exposes all mathematical functions as tools that LLMs can call directly:
Available MCP Tools:
percent_of
- Calculate percentage relationshipssolve_proportion
- Solve missing proportion termsscale_by_ratio
- Apply scaling ratiosdirect_k
- Find proportionality constantsresize_dimensions
- Scale dimensional pairs
MCP Connection Example
{
"name": "proportio",
"type": "sse",
"url": "http://localhost:7860/mcp"
}
Integration Benefits
- Reliable Math: LLMs can delegate complex calculations
- Error Handling: Clear error messages for invalid inputs
- Type Safety: Automatic input validation and conversion
- Performance: Fast, direct mathematical operations
๐ API Reference
Function Signatures
def percent_of(part: float, whole: float) -> float:
"""Calculate percentage that part is of whole."""
def solve_proportion(
a: Optional[float] = None,
b: Optional[float] = None,
c: Optional[float] = None,
d: Optional[float] = None
) -> float:
"""Solve missing term in proportion a/b = c/d."""
def scale_by_ratio(value: float, ratio: float) -> float:
"""Scale value by given ratio."""
def direct_k(x: float, y: float) -> float:
"""Find proportionality constant k where y = kx."""
def resize_dimensions(width: float, height: float, scale: float) -> Tuple[float, float]:
"""Resize dimensions with uniform scale factor."""
Error Messages
All functions provide clear, actionable error messages:
# Division by zero errors
"Division by zero: whole cannot be zero"
"Division by zero: x cannot be zero"
"Division by zero: denominator"
# Validation errors
"Exactly one value must be None"
"Width must be non-negative"
"Height must be non-negative"
"Scale factor must be positive"
Return Types
- Single Values:
float
for mathematical results - Dimension Pairs:
Tuple[float, float]
for width/height - Errors:
AssertionError
with descriptive messages
๐ ๏ธ Development
Project Philosophy
- Assertion-Based Validation - No try-catch complexity
- Mathematical Precision - Accurate calculations with clear preconditions
- Minimal Dependencies - Only essential packages
- Comprehensive Testing - High test coverage with edge cases
- Professional Design - Clean, branded user interface
Code Style
# Clear function signatures with type hints
def function_name(param: Type) -> ReturnType:
"""
Brief description.
Args:
param: Parameter description
Returns:
Return value description
Mathematical preconditions:
- Explicit constraint documentation
"""
# Assertion-based validation
assert condition, "Clear error message"
# Direct calculation
result = calculation
# Optional logging
logger.debug(f"Operation completed: {result}")
return result
Adding New Functions
- Implement Core Logic - Add function to
proportion_server.py
- Add Mathematical Preconditions - Document constraints explicitly
- Create Demo Function - Add Gradio interface wrapper
- Write Comprehensive Tests - Cover all edge cases
- Update Documentation - Add examples and use cases
Contributing Guidelines
- Fork the Repository - Create your feature branch
- Follow Code Style - Use assertion-based validation
- Add Tests - Ensure comprehensive test coverage
- Update Documentation - Keep README current
- Submit Pull Request - Include description of changes
๐ License
This project is licensed under the Apache License 2.0 - see the file for details.
Key License Points
- โ Commercial Use - Use in commercial applications
- โ Modification - Modify and distribute changes
- โ Distribution - Distribute original or modified versions
- โ Patent Use - Grant of patent rights from contributors
- โ ๏ธ Attribution - Must include license and copyright notice
- โ ๏ธ State Changes - Must document modifications
๐ค Support
Getting Help
- Issues: GitHub Issues
- Documentation: This README and inline code documentation
- Examples: See
tests/test_tools.py
for usage examples
Contributing
We welcome contributions! Please see the Development section for guidelines.
Reporting Bugs
When reporting bugs, please include:
- Environment Details (Python version, OS, Docker version)
- Reproduction Steps (minimal code example)
- Expected vs Actual Behavior
- Error Messages (full stack trace if applicable)
Built with โค๏ธ for mathematical precision and LLM integration
Proportio - Where Mathematics Meets Reliability