Ananyamorab/Math_Agent
If you are the rightful owner of Math_Agent 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.
The Math Agent with MCP Server Integration is a sophisticated system designed to handle mathematical queries using external Model Context Protocol (MCP) tools, ensuring precise and reliable calculations.
Math Agent with MCP Server Integration
๐ฏ Overview
This project creates a Math Agent that uses Groq AI for understanding mathematical problems and real MCP server tools for performing calculations. The agent never uses internal LLM reasoning for mathematical operations - it always delegates to external MCP tools.
๐๏ธ Architecture
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ User Input โ -> โ Groq AI โ -> โ MCP Tools โ
โ Math Question โ โ Analysis โ โ (External) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ
v v
Parse Problem Execute Calculation
Extract Numbers Return Precise Result
Identify Operations
๐ Project Structure
MathAgent/
โโโ math_agent.py # Main agent with Groq AI integration
โโโ math_functions.py # Mathematical functions (external tools)
โโโ main.py # MCP server
โโโ .env # API keys (GROQ_API_KEY)
โโโ pyproject.toml # Dependencies
โโโ README.md # This file
๐ง Key Components
1. Math Agent (math_agent.py
)
- Uses Groq AI to analyze mathematical problems
- Extracts operations and numbers from natural language
- Delegates calculations to real MCP server tools
- Returns error if MCP tools unavailable (no fallback)
2. Math Functions (math_functions.py
)
- Pure mathematical functions that can be imported directly
- No server startup when imported
- Used by both MCP server and direct agent integration
3. MCP Server (main.py
)
- FastMCP server exposing mathematical tools
- Can run standalone for external connections
- Provides 15 mathematical operations as MCP tools
๐ Quick Start
1. Install Dependencies
pip install groq python-dotenv pydantic-ai fastmcp
2. Setup API Key
Create .env
file:
GROQ_API_KEY=your_groq_api_key_here
3. Run Interactive Agent
python3 math_agent.py
4. Run MCP Server (Optional)
python3 main.py
๐ Available Mathematical Tools
Tool | Description | Example |
---|---|---|
add(a, b) | Addition | 25 + 75 = 100 |
subtract(a, b) | Subtraction | 100 - 25 = 75 |
multiply(a, b) | Multiplication | 12 ร 12 = 144 |
divide(a, b) | Division | 144 รท 12 = 12 |
power(a, b) | Exponentiation | 3^4 = 81 |
square_root(a) | Square root | โ169 = 13 |
factorial(n) | Factorial | 5! = 120 |
absolute_value(a) | Absolute value | |-5| = 5 |
sin(a) | Sine (radians) | sin(ฯ/2) = 1 |
cos(a) | Cosine (radians) | cos(0) = 1 |
tan(a) | Tangent (radians) | tan(ฯ/4) = 1 |
log(a, base) | Logarithm | log(8, 2) = 3 |
modulus(a, b) | Modulo | 17 % 5 = 2 |
degrees_to_radians(d) | Convert degrees | 180ยฐ = ฯ rad |
radians_to_degrees(r) | Convert radians | ฯ rad = 180ยฐ |
๐ฎ Usage Examples
Interactive Mode
$ python3 math_agent.py
๐งฎ Math Agent - Production Mode
==================================================
I solve mathematical problems using external MCP tools.
Requires: math_functions.py for calculations
๏ฟฝ Enter your math question: What is 156 + 244?
๐ฏ Solution: Using real MCP server tool 'add': 156 + 244 = 400
๐ Enter your math question: Calculate the square root of 625
๐ฏ Solution: Using real MCP server tool 'square_root': โ625 = 25.0
Programmatic Usage
from math_agent import MathAgent
import asyncio
async def solve_problem():
agent = MathAgent()
result = await agent.solve_math_problem("What is 7 factorial?")
print(result) # "Using real MCP server tool 'factorial': 7! = 5040"
asyncio.run(solve_problem())
๐ How It Works
- User asks a math question (natural language)
- Groq AI analyzes the problem and extracts:
- Required mathematical operations
- Numbers involved
- Solution approach
- Agent uses real MCP tools:
- Imports functions from
math_functions.py
- Executes calculations with external tools
- Returns precise numerical results
- Imports functions from
- Error handling if MCP tools unavailable (no simulation)
โ Production Features
The system ensures external tool usage by:
- No fallback simulations - only real tool calls
- Never performing calculations in LLM context
- Always delegating to imported mathematical functions
- Clear error messages when tools unavailable
- Logging which tools are used for each operation
๐ฏ Key Benefits
- ๐ Reliable: No LLM calculation errors
- ๐ฏ Precise: Uses real mathematical functions
- ๐ง External: All calculations via MCP tools
- ๐ง Smart: Natural language understanding via Groq AI
- โก Fast: Direct function calls for calculations
- ๐ก๏ธ Safe: Proper error handling and validation
- ๐ญ Production: No mock code or fallbacks
Production Math Agent using Groq AI + Real MCP Tools with MCP Tools
A sophisticated Math Agent that uses external Model Context Protocol (MCP) tools for all mathematical calculations instead of relying on LLM's internal reasoning. This ensures accurate calculations and provides transparency in the problem-solving process.
๐ฏ Project Overview
This project implements a Math Agent that:
- โ Uses external MCP tools for ALL mathematical operations
- โ Never relies on LLM internal calculations
- โ Provides step-by-step explanations
- โ Uses Groq API for fast and efficient LLM operations
- โ Supports interactive problem-solving sessions
- โ Includes comprehensive logging for debugging
๐ ๏ธ Architecture
Student Query โ Math Agent โ MCP Client โ MCP Server (Tools) โ Results โ Student
โ
Standard Logging
Components
- MCP Server (
main.py
) - Provides mathematical tools - Math Agent (
math_agent.py
) - Orchestrates problem solving using Groq API - MCP Client - Connects agent to tools
- Standard Logging - Basic logging for debugging and monitoring
๐งฎ Available Mathematical Tools
Basic Operations
add(a, b)
- Additionsubtract(a, b)
- Subtractionmultiply(a, b)
- Multiplicationdivide(a, b)
- Divisionmodulus(a, b)
- Modulus/Remainder
Advanced Operations
power(a, b)
- Exponentiation (a^b)square_root(a)
- Square rootlog(a, base)
- Logarithm with custom basefactorial(n)
- Factorialabsolute_value(a)
- Absolute value
Trigonometric Functions
sin(a)
- Sine (radians)cos(a)
- Cosine (radians)tan(a)
- Tangent (radians)degrees_to_radians(degrees)
- Convert degrees to radiansradians_to_degrees(radians)
- Convert radians to degrees
๐ Quick Start
1. Setup Environment
# Run setup script
python setup.py
# Or manual installation
pip install -e .
2. Configure Environment Variables
Edit .env
file:
# Preferred: Groq API Key (fast and efficient)
GROQ_API_KEY=your_groq_api_key_here
# Fallback: OpenAI API Key
OPENAI_API_KEY=your_openai_api_key_here
3. Start MCP Server
# Terminal 1: Start the MCP server
python main.py
4. Run Math Agent
# Terminal 2: Run the interactive agent
python math_agent.py
# Or run examples
python examples.py
๐ก Usage Examples
Interactive Mode
๐ Enter your math problem: What is 25 + 17?
๐ค Thinking...
โ
Solution:
I'll help you add 25 and 17 using the external addition tool.
Let me use the 'add' tool to calculate this:
- Adding 25 + 17 = 42
The answer is 42.
Complex Problems
๐ Enter your math problem: Calculate the area of a circle with radius 5
๐ค Thinking...
โ
Solution:
I'll calculate the area of a circle with radius 5 using the formula A = ฯ ร rยฒ.
Step 1: Calculate rยฒ (radius squared)
Using the 'power' tool: 5ยฒ = 25
Step 2: Calculate ฯ ร rยฒ
Using the 'multiply' tool: 3.14159 ร 25 = 78.54
The area of the circle is approximately 78.54 square units.
๐ Monitoring and Logging
The agent includes basic logging capabilities:
Operation Logging
- Mathematical operations performed
- Execution time tracking
- Error monitoring
- Basic performance insights
Setup Logging
The agent uses Python's standard logging module for monitoring operations and debugging. All logs are output to the console by default.
๐ Project Structure
MathAgent/
โโโ main.py # MCP Server with math tools
โโโ math_agent.py # Main Math Agent implementation
โโโ examples.py # Example usage and demonstrations
โโโ setup.py # Environment setup script
โโโ logfire_config.py # Logfire monitoring configuration
โโโ pyproject.toml # Project dependencies
โโโ README.md # This file
โโโ .env # Environment variables (create from template)
โโโ logs/ # Log files directory
๐ง Advanced Configuration
Custom Model Selection
# Use different Groq models (recommended)
agent = MathAgent(model_name="llama3-8b-8192") # Fast and efficient
agent = MathAgent(model_name="llama3-70b-8192") # More capable
agent = MathAgent(model_name="mixtral-8x7b-32768") # Alternative option
# OpenAI models (fallback)
agent = MathAgent(model_name="gpt-3.5-turbo") # If using OpenAI
Custom MCP Server Path
# Use custom MCP server
await agent.setup_mcp_client("/path/to/custom/server.py")
๐จ Key Features
1. No Internal LLM Calculations
The agent is designed with strict rules to prevent the LLM from performing any mathematical calculations internally. All math operations must use external tools.
2. Step-by-Step Solutions
Complex problems are broken down into smaller steps, each using appropriate tools, making the solution process transparent and educational.
3. Error Handling
Robust error handling for edge cases like division by zero, negative square roots, etc.
4. Performance Monitoring
Comprehensive logging and monitoring to track performance and optimize token usage.
5. Educational Focus
Designed specifically for helping students understand mathematical problem-solving processes.
๐งช Testing
Run the test examples:
python examples.py
Test specific scenarios:
from math_agent import MathAgent
async def test_agent():
agent = MathAgent()
await agent.setup_mcp_client()
agent.create_agent()
result = await agent.solve_math_problem("What is 15 ร 23?")
print(result)
๐ค Contributing
- Fork the repository
- Create a feature branch
- Add new mathematical tools to
main.py
- Update documentation
- Submit a pull request
๐ TODO
- Add more advanced mathematical functions
- Implement graph plotting capabilities
- Add support for symbolic mathematics
- Create web interface
- Add unit tests
- Performance benchmarking
๐ Troubleshooting
Common Issues
-
MCP Connection Failed
- Ensure
main.py
is running - Check file paths are correct
- Verify Python environment
- Ensure
-
API Key Issues
- Set
GROQ_API_KEY
in.env
file (recommended) - Or set
OPENAI_API_KEY
as fallback - Check API key validity
- Set
-
Import Errors
- Run
python setup.py
- Check Python version (3.8+)
- Verify all dependencies installed
- Run
๐ License
This project is created for educational purposes. Please respect OpenAI's and Groq's usage policies and terms of service.
git clone https://github.com/ArjunKrish7356/MathAgent.git
- Create an MCP server wrapper in your agent code (the
name
can be any unique id;args
are the command used to start the server process):
from pydantic_ai.mcp import MCPServerStdio
mcp_server = MCPServerStdio(
'uv'
args=[
"run",
"MathAgent/main.py"
]
)
- Register the MCP server with your Agent:
from pydantic_ai import Agent
agent = Agent(model="openai:gpt-4o", toolsets=[mcp_server])
Notes:
- Ensure the
MathAgent/main.py
path is correct relative to where the agent runs and that the script is runnable. - The Stdio transport will spawn the configured process using the provided
args
; verify any required environment or dependencies are installed before launching. - Test the connection locally before deploying.
More Resources
- Official MCP documentation: https://modelcontextprotocol.io/docs/getting-started/intro
- Introductory video on MCP: https://www.youtube.com/watch?v=N3vHJcHBS-w
Contributing
Thank you for your interest! Contributions are welcomeโfeel free to open issues or submit pull requests.