This project demonstrates a sophisticated AI-powered mathematical problem solver using the Model Context Protocol (MCP). The system consists of an MCP server that provides mathematical tools and TextEdit integration, and an AI client that can autonomously solve complex mathematical problems and visualize results.
The system showcases how AI agents can use MCP to:
- Access a comprehensive suite of mathematical tools
- Solve complex multi-step problems autonomously
- Generate visual representations of solutions
- Integrate with native macOS applications (TextEdit)
- Handle iterative problem-solving with feedback loops
example2.py- MCP Server providing mathematical tools and TextEdit integrationtalk2mcp-2.py- AI Client that communicates with the MCP server using Google Gemini
AI Client (talk2mcp-2.py)
โ (MCP Protocol)
MCP Server (example2.py)
โ (Tool Execution)
Mathematical Tools + TextEdit Integration
โ (Results)
AI Client (Processes & Iterates)
- Basic Operations: Addition, subtraction, multiplication, division
- Advanced Math: Power, square root, cube root, factorial
- Trigonometric: Sine, cosine, tangent
- Logarithmic: Natural logarithm
- Specialized: Remainder, custom mining function
- List Operations: Sum of lists, exponential sums
- Sequences: Fibonacci number generation
- String Processing: ASCII value extraction
- Visual Documentation: Create formatted documents with solutions
- Rectangle Drawing: ASCII art rectangles with dynamic sizing
- Text Formatting: Professional solution presentation
- File Management: Automatic temporary file creation and cleanup
- Autonomous Problem Solving: Multi-step mathematical reasoning
- Tool Discovery: Dynamic exploration of available MCP tools
- Iterative Processing: Up to 3 iterations with feedback loops
- Error Handling: Robust error recovery and reporting
- Timeout Management: Prevents infinite loops with 10-second timeouts
- Python 3.8+
- macOS (for TextEdit integration)
- Google Generative AI API key
- Install Dependencies:
pip install mcp google-generativeai python-dotenv pillow- Set up API Key:
# Create .env file
echo "GEMINI_API_KEY=your_actual_api_key_here" > .envGet your API key from: https://aistudio.google.com/app/apikey
- Start the AI Agent:
python talk2mcp-2.pyThe AI will automatically:
- Connect to the MCP server
- Discover available tools
- Solve the mathematical problem
- Create a visual representation in TextEdit
| Tool | Description | Parameters | Return Type |
|---|---|---|---|
add |
Add two numbers | a: int, b: int |
int |
subtract |
Subtract two numbers | a: int, b: int |
int |
multiply |
Multiply two numbers | a: int, b: int |
int |
divide |
Divide two numbers | a: int, b: int |
float |
power |
Calculate a^b | a: int, b: int |
int |
sqrt |
Square root | a: int |
float |
cbrt |
Cube root | a: int |
float |
factorial |
Factorial of a number | a: int |
int |
log |
Natural logarithm | a: int |
float |
remainder |
Modulo operation | a: int, b: int |
int |
sin |
Sine function | a: int |
float |
cos |
Cosine function | a: int |
float |
tan |
Tangent function | a: int |
float |
| Tool | Description | Parameters | Return Type |
|---|---|---|---|
add_list |
Sum all numbers in a list | l: list |
int |
strings_to_chars_to_int |
Get ASCII values of characters | string: str |
list[int] |
int_list_to_exponential_sum |
Sum of exponentials | int_list: list |
float |
fibonacci_numbers |
Generate Fibonacci sequence | n: int |
list |
mine |
Custom mining function | a: int, b: int |
int |
| Tool | Description | Parameters | Return Type |
|---|---|---|---|
create_combined_textedit_document |
Create document with rectangle and solution | x1, y1, x2, y2, solution_text |
dict |
open_text_editor |
Open TextEdit application | None | dict |
draw_rectangle_in_text_editor |
Draw ASCII rectangle | x1, y1, x2, y2 |
dict |
add_text_in_text_editor |
Add formatted text | text: str |
dict |
send_email |
Send solution via email | email_content: str |
dict |
The AI agent follows this structured approach:
- Tool Discovery: Connects to MCP server and retrieves available tools
- Problem Analysis: Parses the mathematical problem
- Planning: Creates a step-by-step solution plan
- Execution: Calls appropriate tools in sequence
- Visualization: Creates TextEdit document with results
- Iteration: Up to 3 attempts with feedback loops
Problem: "Find the ASCII values of characters in INDIA and then return sum of exponentials of those values. After solving, draw a rectangle in TextEdit to visualize the result."
AI Solution Steps:
strings_to_chars_to_int("INDIA")โ[73, 78, 68, 73, 65]int_list_to_exponential_sum([73, 78, 68, 73, 65])โ[result]create_combined_textedit_document(50, 50, 200, 150, "FINAL_ANSWER: [result]")
The AI uses a strict response format:
- Function Calls:
FUNCTION_CALL: function_name|param1|param2|... - Final Answers:
FINAL_ANSWER: [result]
# In talk2mcp-2.py
max_iterations = 3 # Maximum problem-solving iterations
timeout = 10 # LLM response timeout in secondsThe system automatically converts parameters based on tool schemas:
integerโint()numberโfloat()arrayโlistwith type conversionstringโstr()
MCP/
โโโ example2.py # MCP Server with mathematical tools
โโโ talk2mcp-2.py # AI Client using Google Gemini
โโโ README.md # This documentation
โโโ .env # Environment variables (create this)
โโโ __pycache__/ # Python cache files
The system creates proportional rectangles based on coordinates:
display_width = max(10, min(80, width // 5))
display_height = max(3, min(25, height // 10))Solutions are presented with:
- ASCII art rectangles
- Centered text
- Timestamps
- Auto-generated labels
- Clean, readable formatting
- Automatic temporary file creation
- TextEdit integration via
subprocess - Clean file cleanup after display
-
"GEMINI_API_KEY not found"
# Create .env file echo "GEMINI_API_KEY=your_key_here" > .env
-
"No module named mcp"
pip install mcp
-
TextEdit not opening
- Ensure you're on macOS
- Check TextEdit is installed
- Verify file permissions
-
Tool execution errors
- Check parameter types match tool schemas
- Verify tool names are correct
- Review error logs for specific issues
Enable detailed logging:
# In talk2mcp-2.py, uncomment debug lines
print(f"DEBUG: Raw function info: {function_info}")
print(f"DEBUG: Final arguments: {arguments}")Modify the query in talk2mcp-2.py:
query = """Your custom mathematical problem here"""In example2.py, add new tools:
@mcp.tool()
def your_new_tool(param1: int, param2: str) -> float:
"""Your tool description"""
return your_calculation(param1, param2)Modify the system prompt in talk2mcp-2.py:
system_prompt = f"""Your custom AI instructions..."""- Multi-Platform Support: Windows and Linux compatibility
- Enhanced Visualization: More drawing tools and shapes
- Advanced Math: Matrix operations, calculus functions
- Real-time Collaboration: Multiple AI agents working together
- Voice Integration: Speech-to-text problem input
- Web Interface: Browser-based problem solving
- Response Time: ~2-5 seconds per tool call
- Accuracy: High mathematical precision
- Reliability: Robust error handling and recovery
- Scalability: Supports complex multi-step problems
This project is for educational and demonstration purposes, showcasing the power of Model Context Protocol for AI agent development.
- Fork the repository
- Create a feature branch
- Add your enhancements
- Test thoroughly
- Submit a pull request
For issues and questions:
- Check the troubleshooting section
- Review the debug output
- Examine the MCP server logs
- Verify your API key configuration
Built with โค๏ธ using Model Context Protocol and Google Gemini AI