Math_Agent

Ananyamorab/Math_Agent

3.2

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.

Tools
5
Resources
0
Prompts
0

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

ToolDescriptionExample
add(a, b)Addition25 + 75 = 100
subtract(a, b)Subtraction100 - 25 = 75
multiply(a, b)Multiplication12 ร— 12 = 144
divide(a, b)Division144 รท 12 = 12
power(a, b)Exponentiation3^4 = 81
square_root(a)Square rootโˆš169 = 13
factorial(n)Factorial5! = 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)Logarithmlog(8, 2) = 3
modulus(a, b)Modulo17 % 5 = 2
degrees_to_radians(d)Convert degrees180ยฐ = ฯ€ 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

  1. User asks a math question (natural language)
  2. Groq AI analyzes the problem and extracts:
    • Required mathematical operations
    • Numbers involved
    • Solution approach
  3. Agent uses real MCP tools:
    • Imports functions from math_functions.py
    • Executes calculations with external tools
    • Returns precise numerical results
  4. 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

  1. MCP Server (main.py) - Provides mathematical tools
  2. Math Agent (math_agent.py) - Orchestrates problem solving using Groq API
  3. MCP Client - Connects agent to tools
  4. Standard Logging - Basic logging for debugging and monitoring

๐Ÿงฎ Available Mathematical Tools

Basic Operations

  • add(a, b) - Addition
  • subtract(a, b) - Subtraction
  • multiply(a, b) - Multiplication
  • divide(a, b) - Division
  • modulus(a, b) - Modulus/Remainder

Advanced Operations

  • power(a, b) - Exponentiation (a^b)
  • square_root(a) - Square root
  • log(a, base) - Logarithm with custom base
  • factorial(n) - Factorial
  • absolute_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 radians
  • radians_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

  1. Fork the repository
  2. Create a feature branch
  3. Add new mathematical tools to main.py
  4. Update documentation
  5. 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

  1. MCP Connection Failed

    • Ensure main.py is running
    • Check file paths are correct
    • Verify Python environment
  2. API Key Issues

    • Set GROQ_API_KEY in .env file (recommended)
    • Or set OPENAI_API_KEY as fallback
    • Check API key validity
  3. Import Errors

    • Run python setup.py
    • Check Python version (3.8+)
    • Verify all dependencies installed

๐Ÿ“„ 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
  1. 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"
    ]
)
  1. 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

Contributing

Thank you for your interest! Contributions are welcomeโ€”feel free to open issues or submit pull requests.